qid
int64
46k
74.7M
question
stringlengths
54
37.8k
date
stringlengths
10
10
metadata
listlengths
3
3
response_j
stringlengths
29
22k
response_k
stringlengths
26
13.4k
__index_level_0__
int64
0
17.8k
70,168,761
I am trying to click on a check box. Below is the HTML Code ``` <div class="mb-1 p-3 termsCheck"> <input class="form-check-input float-end" type="checkbox" value="" id="flexCheckDefault" required=""> <label class="form-check-label float-end" for="flexCheckDefault"><span> Agree to Terms ...
2021/11/30
[ "https://Stackoverflow.com/questions/70168761", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13572791/" ]
`max_func` should return a function that takes an argument (`x`), applies it to `f` and `g` and then return the maximal value: ``` def max_func(f, g): def mf(x): return max(f(x), g(x)) return mf ```
In your code, you are calling only f(x) in both if and else statement. You can try: ``` def max_func(f,g): if f(x)> g(x): return f(x) else: return g(x) def new_function (x:int): -> int return new_function ```
3,507
41,950,021
I'm learning python and working on exercises. One of them is to code a voting system to select the best player between 23 players of the match using lists. I'm using `Python3`. My code: ``` players= [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] vote = 0 cont = 0 while(vote >= 0 and vote <23): vote = input(...
2017/01/31
[ "https://Stackoverflow.com/questions/41950021", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7493136/" ]
Change ``` vote = input('Enter the name of the player you wish to vote for') ``` to ``` vote = int(input('Enter the name of the player you wish to vote for')) ``` You are getting the input from the console as a string, so you must cast that input string to an `int` object in order to do numerical operations.
When you use the input function it automatically turns it into a string. You need to go: ``` vote = int(input('Enter the name of the player you wish to vote for')) ``` which turns the input into a int type value
3,510
41,908,655
i need to create a dataframe containing tuples from a series of dataframes arrays. What I need is the following: I have dataframes `a` and `b`: ``` a = pd.DataFrame(np.array([[1, 2],[3, 4]]), columns=['one', 'two']) b = pd.DataFrame(np.array([[5, 6],[7, 8]]), columns=['one', 'two']) a: one two 0 1 2 1 3...
2017/01/28
[ "https://Stackoverflow.com/questions/41908655", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6316272/" ]
you can use `numpy.rec.fromarrays((a.values, b.values)).tolist()`: ``` In [34]: pd.DataFrame(np.rec.fromarrays((a.values, b.values)).tolist(), columns=a.columns, index=a.index) Out[34]: one two 0 (1, 5) (2, 6) 1 (3, 7) (4, 8) ``` merging three DF's: ``` In ...
You could use `zip` over columns of `a`, `b` ``` In [31]: pd.DataFrame({x: zip(a[x], b[x]) for x in a.columns}) Out[31]: one two 0 (1, 5) (2, 6) 1 (3, 7) (4, 8) ```
3,515
68,767,995
I have a string like this: ``` txt = ''' lea_po () { val : 96.9; wh : "CP D "; related : DD; leak () { va : 0.008; when : " SI"; in : V; } **stagestat (" E I P", "I 2 ") { data : " H H/L - R : - - - : L - - , \ - : - - - : L - - , \ - - - ...
2021/08/13
[ "https://Stackoverflow.com/questions/68767995", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13699970/" ]
* Make sure you have `Unicode True` at the start of your script. * Make sure you save your script as UTF-8 BOM or UTF-16LE BOM. * !include nsDialogs before commctrl.nsh * Make sure you are using the Unicode version of all plug-ins. Characters that "look Chinese" is a symptom of treating ASCII as UTF-16. Strings cut of...
Have you tried to add command "unicode True" at the top of the script?
3,516
47,344,625
content of my python file ``` class myclass(object): def __init__(self): pass def myfun(self): pass print ("hello world") ``` Output on executing file ``` hello world ``` Query ``` since I did not create object of class . How's it still able to print "hello world" ```
2017/11/17
[ "https://Stackoverflow.com/questions/47344625", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3812837/" ]
The class body executes at class definition time, and that's how the language is designed. From section [9.3.1 Class Definition](https://docs.python.org/3/tutorial/classes.html#class-definition-syntax) syntax: > > In practice, the statements inside a class definition will usually be function definitions, but other ...
It will get a call, as python work like that. Your code will always return output. **hello world** ``` class myclass(object): def __init__(self): pass def myfun(self): print("hello world") pass ``` If you want to avoid it you have to add print statement inside the method.
3,517
54,005,909
I am attempting to create a contract bridge match point scoring system. In the list below the 1st, 3rd, etc. numbers are the pair numbers (players) and the 2nd, 4th etc. numbers are the scores achieved by each pair. So pair 2 scored 430, pair 3 scored 420 and so on. I want to loop through the list and score as follow...
2019/01/02
[ "https://Stackoverflow.com/questions/54005909", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1903663/" ]
List appears to be a poor data structure for this, I think you are making everything worse by flattening your elasticsearch object. > > Note there are a few minor mistakes in listings below - to make sure > I'm not solving someone's homework for free. I also realize this is > not the most efficient way of doing so....
The main problem with your code is, that the loop is one short, you have 7 entries. Then you should convert the numbers to `int`, so that the comparison is correct. In your code, you get for ties 0 points. Instead of having a list, with flattend pairs, you should use tuple pairs. ``` ns_list = [] for row in arr["hits"...
3,518
50,159,438
I tried reproducing some of the examples described [here](https://www.boost.org/doc/libs/1_63_0/libs/python/doc/html/numpy/tutorial/ndarray.html), but I experience the following problem with the code below, which was written by just copy-pasting relevant parts of the linked page. ``` #include <boost/python.hpp> #inclu...
2018/05/03
[ "https://Stackoverflow.com/questions/50159438", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7141288/" ]
This week I had the same issue. To solve my problem I use dynamic memory: ``` np::ndarray test(){ int *data = malloc(sizeof(int) * 5); for (int i=0; i < 5; ++i){ data[i] = i + 1; } p::tuple shape = p::make_tuple(5); p::tuple stride = p::make_tuple(sizeof(int)); p::object own; np::dt...
Creating a new reference to the array before returning it solved the problem. Good news is that `np::ndarray` has a [`copy()`](https://github.com/boostorg/python/blob/4f6d547c0af4c400dc5d059ccd847426ff21852f/src/numpy/ndarray.cpp#L177) method that achieves exactly the same thing. Thus, you should add ``` np::ndarray n...
3,521
70,042,756
I'm running a python code to calculate the distance between certain coordinates. The original data looks like: ``` a = np.array([[1,40,70],[2,41,71],[3,42,73]]) #id, latitude, longitude ``` and I'm looking forward to get the distance between every pair, the result should look like: ``` [1, 2, 100(km)] [1, 3, 200...
2021/11/20
[ "https://Stackoverflow.com/questions/70042756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17454717/" ]
1- run : ``` php artisan make:middleware AccountType ``` 2- Add it to the *routeMiddleware* array in your kernel file by opening `app/Http/Kernel.php`: ``` 'accType' => \App\Http\Middleware\AccountType::class, ``` 3- Edit `AccountType` file: ``` public function handle($request, Closure $next) { // If user accou...
If your want to have a multi authenticate system, whit different logics, its better to implement multiple guard and define them in your desire models : ``` [...] 'guards' => [ [...] 'admin' => [ 'driver' => 'session', 'provider' => 'admins', ], 'writer' => [ 'driver' => 'session...
3,522
47,845,358
Given a string, find the rank of the string amongst its permutations sorted lexicographically. Note that the characters might be repeated. If the characters are repeated, we need to look at the rank in unique permutations. Look at the example for more details. Input : 'aba' Output : 2 The order permutations with ...
2017/12/16
[ "https://Stackoverflow.com/questions/47845358", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7549959/" ]
``` long long int pow_mod(long long int a,long long int b) { long long MOD=1000003; if(a == 1) return 1; long long int x =1 ,y = a; while(b>0) { if(b%2) { x = (x*y)%MOD; } y = (y*y)%MOD; b = b>>1; } return x; } int Solution::findRank(s...
You could generate the permutations, sort them, and find your original string: ``` from itertools import permutations def permutation_index(s): return sorted(''.join(x) for x in permutations(s)).index(s) ```
3,527
20,048,001
``` f = open('file.txt') print f.read() ``` That was pretty straight forward wasn't it? That works because python knows how to read and write`.txt` files. How do these formats even work? I wish to build a python program to read atleast the major formats of documents (including pdfs), spreadsheets and presentations. ...
2013/11/18
[ "https://Stackoverflow.com/questions/20048001", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2672265/" ]
No, you have completely misunderstood what your code is doing. Python doesn't "know" how to read .txt files, because there is no "format" here. It is just opening a plain file and printing out the bytes it finds there. Something like PDF or DOC is completely different. The bytes by themselves do not mean anything: the...
You will need to look up the specification for each format you want to deal with, [this](http://www.idpf.org/epub/301/spec/epub-overview.html) is the specification for ePub for example, it's a bit broad but you get the idea, then you need figure out yourself how you want to deal with it.
3,528
13,536,350
On using this regular expression in python : `pathstring = '<span class="titletext">(.*)</span>'` `pathFinderTitle = re.compile(pathstring)` My output is: ``` Govt has nothing to do with former CAG official RP Singh: Sibal</span></a></h2></div><div class="esc-lead-article-source-wrapper"> <table class="al-attribu...
2012/11/23
[ "https://Stackoverflow.com/questions/13536350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/733583/" ]
`.*` is a *greedy* match of any characters; it is going to consume as many characters as possible. Instead, use the non-greedy version `.*?`, as in ``` pathstring = '<span class="titletext">(.*?)</span>' ```
`.*` will match `</span>` so it keeps on going until the last one. The best answer is: Don't parse html with regular expressions. Use the [lxml](http://lxml.de/installation.html) library (or something similar). ``` from lxml import html html_string = '<blah>' tree = html.fromstring(html_string) titles = tree.xpath("...
3,530
32,878,530
I have a Python/Django project that I manage using PyCharm. Everything was working perfectly under Mac OSX Yosemite. This morning I upgraded to the final release version of El Capitan, now I cannot run the project. The error I get is: > > Error loading MySQLdb module: No module named MySQLdb > > > I've tried all ...
2015/10/01
[ "https://Stackoverflow.com/questions/32878530", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1402166/" ]
Happened to me as well. I removed the package, installed mysql using [Homebrew](http://brew.sh/) and then reinstall the package. ``` pip uninstall MySQL-python brew install mysql pip install MySQL-python ``` If you run into any issues with brew, be sure to check their [troubleshooting page on El Capitan](https://git...
View this post : [MySQL Improperly Configured Reason: unsafe use of relative path](https://stackoverflow.com/questions/31343299/mysql-improperly-configured-reason-unsafe-use-of-relative-path) And if you have updated Xcode, open 1 time Xcode for agreement the licence.
3,535
62,804,653
I see that all of the examples per the documentation use some form of a simple web application (For example, Flask in Python). Is it possible to use cloud run as a non web application? For example, deploy cloud run to use a python script and then use GCP Scheduler to invoke cloud run every hour to run that script? Basi...
2020/07/08
[ "https://Stackoverflow.com/questions/62804653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11287314/" ]
It's mandatory to answer to HTTP request. It's the contract of Cloud Run * Stateless (no volume attached to the container) * Answer to HTTP request However, if you already have a python script, it's easy to wrap it in a flask webserver. Let's say, you have something like this (I assume that the file name is `main.py`...
It depends what is being installed in the container image, as there is no requirement that one would have to install a web-server. For [example](https://github.com/syslogic/cloudbuild-android), with such an image I can build Android applications, triggered whenever a repository changes (file excludes recommend) ...and ...
3,536
26,268,268
I have the following string in a seperate .txt file: ``` L#$KJ#()JSEFS(DF)(SD*F #KJ$H#K$JH@#K$JHD) SF SDFLKJ#{P@$OJ{SDPFODS{PFO{ #K$HK#JHSFHD(*SHF)SF{HP #L$H@โ€#$Hโ€@#L$KH#โ€@L$K #~L$KJ#:$SD)FJ)S(DJF)(S #$KJH#$ SDLKFJD(FJ)SDJFSDLFKS ~L#$KJ:@LK$#J$ LSJDF(S*JDF(*SJDF(*J(DSF*J ``` I have to take every element by column...
2014/10/08
[ "https://Stackoverflow.com/questions/26268268", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3643019/" ]
From <https://docs.recurly.com/api/recurlyjs/jsonp_endpoints> ``` $.ajax({ dataType: 'jsonp', url: 'https://{subdomain}.recurly.com/jsonp/{subdomain}/plans/{plan_code}', data: { currency: 'USD', }, success: function (data) { // do stuff }, } ```
You should *not* use the V2 API from the browser. Doing so risks exposing your private API key. If someone has your API key they can make calls charging customers, modifying subscriptions, causing all sorts of problems. Look at the JSONP endpoints that Byaxy linked to.
3,538
14,389,513
I need to parse html table of the following structure: ``` <table class="table1" width="620" cellspacing="0" cellpadding="0" border="0"> <tbody> <tr width="620"> <th width="620">Smth1</th> ... </tr> <tr bgcolor="ffffff" width="620"> <td width="620">Smth2</td> ... </tr> <tr bgcolor="...
2013/01/17
[ "https://Stackoverflow.com/questions/14389513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1988698/" ]
You didn't include the XPath, so I'm not sure what you're trying to do, but if I understood correctly, this should work ``` xpath1 = "tbody/tr" r = requests.post(url,data) html = lxml.html.fromstring(r.text) rows = html.xpath(xpath1) data = list() for row in rows: data.append([c.text for c in row.getchildren()]) ...
Your `.xpath(xpath1)` XPath expression failed to find any elements. Check that expression for errors.
3,539
39,448,121
I'm trying to upload a file using ftp in python, but I get an error saying: ``` ftplib.error_perm: 550 Filename invalid ``` when I run the following code: ``` ftp = FTP('xxx.xxx.x.xxx', 'MY_FTP', '') ftp.cwd("/incoming") file = open('c:\Automation\FTP_Files\MaxErrors1.json', 'rb') ftp.storbinary('STOR c:\Automation...
2016/09/12
[ "https://Stackoverflow.com/questions/39448121", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6434729/" ]
The problem is that on the server, the path `c:\Automation\FTP_Files\MaxErrors1.json` is not valid. Instead try just doing: ``` ftp.storbinary('STOR MaxErrors1.json', file) ```
The argument to STOR needs to be the destination file name, not the source path. You should just do `ftp.storbinary('STOR MaxErrors1.json', file)`.
3,540
20,457,271
So im new at python and i would like some help in making code where: When an input is typed if the input has a minimum of three words that match any one thing on a list it would replace the input with the text in the list that matches the criteria Example: Jan -Scans List- -Finds Janice- -Replaces and gives output as...
2013/12/08
[ "https://Stackoverflow.com/questions/20457271", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3065432/" ]
You will need to: * make a replacement words dictionary * get some input * do sanity checking to make sure it fits your parameters * split it into a `list` * loop through your new `list` and replace each word with its replacement in your `dict`, if it is in there I won't write all of this for you. But here's a tip fo...
You Could try this ``` getname = [] for word in args "%s"% (room.usernames).get(args,word) ```
3,542
50,641,831
I am running a playbook against a RHEL 7.4 image which sits behind a proxy. SELINUX and the firewall have been disabled. I am using Ansible 2.5.3 Here is the task ``` - name: Add Docker repository. get_url: url: "{{ docker_yum_repo_url }}" dest: '/etc/yum.repos.d/docker-{{ docker_edition }}.repo' owner: root ...
2018/06/01
[ "https://Stackoverflow.com/questions/50641831", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1768233/" ]
Build your app with sourcemaps, then use a tool like [`source-map-explorer`](https://www.npmjs.com/package/source-map-explorer) that details the size of every part of library that you're using. Some tips with common libraries : * If you're using RxJS 5.5 or higher, use the `.pipe(operator1(), operator2())` syntax, it...
I had a similar issue with large prod bundles and fixed the issue with this command; ``` npm run build ``` I had been using `npm run ng build --prod` but the --prod flag doesn't execute and I was left with a vendor.bundle.js which was 2.9mbs ``` chunk {inline} inline.bundle.js, inline.bundle.js.map (inline) 3.89 ...
3,543
49,520,600
I'm creating a program in python where i need to ask the user for there team name and team members. I need to have the team names in a list and have the team members embedded within the team name. Any Help? ``` # Creating Teams print("Welcome to the program") print("==================================================...
2018/03/27
[ "https://Stackoverflow.com/questions/49520600", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9560138/" ]
`equalsIgnoreCase` just returns a boolean, which indicates, whether two strings are equal if the case of the strings is not considered. What you need is ``` String aLower = a.toLowerCase(); String bLower = b.toLowerCase(); if(aLower.startsWith(bLower)) { // do something } ``` That way you just convert both stri...
Try this : ``` System.out.println((a.toLowerCase()).startsWith(b.toLowerCase())); ```
3,546
38,064,044
I am implementing a simple DSL. I have the following input string: ``` txt = 'Hi, my name is <<name>>. I was born in <<city>>.' ``` And I have the following data: ``` { 'name': 'John', 'city': 'Paris', 'more': 'xxx', 'data': 'yyy', ... } ``` I need to implement the following function: ``` def tokenize...
2016/06/27
[ "https://Stackoverflow.com/questions/38064044", "https://Stackoverflow.com", "https://Stackoverflow.com/users/647991/" ]
Yes, this is a perfect target for regexp. Find the begin/end quotation marks, replace them with braces, and extract the symbol names into a list. Do you have a solid description of legal symbols? You'll want a search such as ``` /\<\<([a-zA-Z]+[a-zA-Z0-9_]*)\>\>/ ``` For classical variable names (note that this excl...
``` import re def tokenize(text): found_variables = [] def replace_and_capture(match): found_variables.append(match.group(1)) return "{{{}}}".format(match.group(1)) return re.sub(r'<<([^>]+)>>', replace_and_capture, text), found_variables fmt, vars = tokenize('Hi, my name is <<name>>. I wa...
3,547
66,565,415
basically im new to python programming and I've just learnt about user input. Im trying to make an if statement that checks if the input is a str or int and then prints a message. If anyone knows how then please comment it, thanks. ``` print("How old are you?") dog = input() final = int(dog) + int(100) if dog == str:...
2021/03/10
[ "https://Stackoverflow.com/questions/66565415", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15051671/" ]
Re how to check types, you can do like this: ```py my_string = "hello" if isinstance(my_string, str): print("I'm a string") else: print("I'm not") # outputs: "I'm a string" ``` However, as commented the input method is always returning a value of type str. So if you want to ensure that the value is only con...
I would use the `type` method to check: ``` print("How old are you?") dog = input() final = int(dog) + int(100) #use type method to check the type of the variable if type(dog) == str: print("No") else: print("\nHeres you name + 100!") print(f"{final}") print("Thanks for playing!") ``` Another thing ...
3,548
57,899,891
I read this (from [here](https://docs.python.org/3.5/reference/datamodel.html#object.__hash__)): > > User-defined classes have `__eq__()` and `__hash__()` methods by default; with them, all objects compare unequal (except with themselves) and `x.__hash__()` returns an appropriate value such that x == y implies both t...
2019/09/12
[ "https://Stackoverflow.com/questions/57899891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3530284/" ]
No, it's more like: ``` def __eq__(self, other) return self is other ``` You can't use `hash()` because it's possible for different objects to have the same hash value.
You can read the following reference: <https://eev.ee/blog/2012/03/24/python-faq-equality/> in the default method where you just try to compare 2 objects while not override the ***eq*** it will see if they are the same 2 objects, more like the following: ``` def __eq__(self, other) return self is other ```
3,549
12,757,832
I began learning Python a little time ago, and I got the first problem. Here's the code: ``` fh = open('/usr/share/dict/words') for line in fh.readlines(): print(line, end='') ``` When I execute it in the Terminal (OS X), it tells me `invalid syntax` error where `end` equal sign is placed. What's the problem her...
2012/10/06
[ "https://Stackoverflow.com/questions/12757832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/764638/" ]
Apparently because the `WebView` had editable content the events were being consumed by a child responder. The workaround was to listen to `WebViewDidChangeNotification` when this happens.
Here is what I think is occurring NSFontManager apparently sends the messages along the responder chain and not to the delegate. I would set my CustomWebViewController to be the delegate of the window.
3,552
5,919,318
I want to nest my custom validators within my schema, like this: ``` MySchema(Schema): class MyValidator(validators.FancyValidator): def _to_python(self, value, state): ... class MyOtherValidator(validators.FancyValidator): def _to_python(self, value, state): ... fi...
2011/05/07
[ "https://Stackoverflow.com/questions/5919318", "https://Stackoverflow.com", "https://Stackoverflow.com/users/315709/" ]
My advice is: you should move the `FancyValidator` subclass definitions to global scope, either (1) in the same module just before the definition of the `Schema` in which they're used, or (2) in a separate module for greater reuse. Unless there is a specific reason why nesting is required, a few extra class names in th...
In python, anything that you define in your class is a field. Be it static variables, variables set with self, methods or classes. If you want to "hide" the classes, or make them "less public", as is probably the right wording in the python dictionary, you should start their names with \_\_. ``` >>> dir(X()) ['A', '_B...
3,553
50,294,263
I'm trying to write simple multi-threaded python script: ``` from multiprocessing.dummy import Pool as ThreadPool def resize_img_folder_multithreaded(img_fldr_src,img_fldr_dst,max_num_of_thread): images = glob.glob(img_fldr_src+'/*.'+img_file_extension) pool = ThreadPool(max_num_of_thread) pool.starmap...
2018/05/11
[ "https://Stackoverflow.com/questions/50294263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3134181/" ]
Blame the GIL. Python has this mechanism called the GIL, global interpreter lock. It is basically a mutex that prevents native threads from executing Python bytecodes at once. This must be done since Python's (at least, CPython) memory management is not thread-safe. In other words, the GIL will prevent you from runni...
You should only use multiprocessing with the number of cpu cores you have available. You are also not using a Queue, so the pool of resources are doing the same work. You need to add a queue to your code. [Filling a queue and managing multiprocessing in python](https://stackoverflow.com/questions/17241663/filling-a-q...
3,554
35,814,637
I am trying to call a Torch 7 program from within a Python cgi-bin script. If I run the following Python script from the command line: ``` # -*- coding: utf-8 -*- from subprocess import call call (['th', 'sample.lua', 'cv/lm_lstm_epoch3.54_0.9324.t7', '-gpuid', '-1', '-primetext', '"ืืžืจ ื”ื’ืื•ืŸ ื”ื’ืจืคืงื ื”ืžืŸ ืื™ืฉ ื˜ื•ื‘ ื”ื™ื” ืฉ...
2016/03/05
[ "https://Stackoverflow.com/questions/35814637", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6001121/" ]
You want to use [check\_output](https://docs.python.org/3/library/subprocess.html#subprocess.check_output) to store the output of the command you are executing. [call](https://docs.python.org/3/library/subprocess.html#subprocess.call) will not do this. Call will only give you the return code of what you are executing. ...
May be you could try [lutorpy](https://github.com/imodpasteur/lutorpy) then you can run the torch code directly with python. You can use require("sample") to import your sample.lua module, and then run the inner function just like you run a python function.
3,557
53,728,124
I'm working on a data-set on which I have certain values which are needed to be rounded to either lower/upper bound. eg. if I want the upper bound to be **9** and lower to **3** and we have numbers like - ``` [ 7.453511737983394, 8.10917072790058, 6.2377799380575, 5.225853201122676, 4.067932296134156 ] ...
2018/12/11
[ "https://Stackoverflow.com/questions/53728124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7618421/" ]
**EDIT:** The best approach in my opinion up to now is using numpy (to avoid "manual" looping) with a simple calculation of the difference arrays between `the_list` and the two bounds (so no expensive multiplication here), to then only conditionally add the one or the other, depending on which is smaller: ``` impor...
A one liner list comprehension using inbuilt `min` function by modifying the key argument to look for an absolute difference ``` upper_lower_bound_list=[3,9] myNumberlist=[ 7.453511737983394, 8.10917072790058, 6.2377799380575, 5.225853201122676, 4.067932296134156 ] ``` List comprehension ``` [min(upper_lower_b...
3,558
67,374,632
I want to take two lists and want to count the values that appear in both but considering **the same position**. ``` a = [1, 2, 3, 4, 5] b = [4, 5, 3, 6, 5] returnMatches(a, b) ``` would return `2`, for instance. ``` a = [1, 2, 3, 4, 5] b = [1, 2, 3, 3, 5] returnMatches(a, b) ``` would return `4`, for instance....
2021/05/03
[ "https://Stackoverflow.com/questions/67374632", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5152497/" ]
Try ```py output = sum([x == y for x, y in zip(a, b)]) ``` I am not sure if it needs further clarification. You might want to look into "list comprehension" and `zip()` if you are not familiar with them.
```py returnMatches = lambda a,b:sum([x==y for x,y in zip(a,b)] ``` This is the same as: ```py def returnMatches(a, b): matches = 0 for x, y in zip(a, b): matches += 1 return matches ``` Take a look at `zip()` for more information on that builtin
3,568
74,575,794
Consider the following simple code: ``` import re def my_match(s): if re.match("^[a-zA-Z]+", s): return True else: return False ``` Is there a way to collapse this in a single `return` statement? In `C` we could do for example: ``` return match("^[a-zA-Z]+", s) ? true : false; ``` Is th...
2022/11/25
[ "https://Stackoverflow.com/questions/74575794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/738154/" ]
Python also supports this, although the syntaxes is a little different than most languages. ``` import re def my_match(s): return True if re.match("^[a-zA-Z]+", s) else False ``` In general, the Python syntax is `val_when_true if cond else val_when_false`, compared to the `cond ? val_when_true : val_when_false`...
A more generell solution would be to use the following code line. It excludes a fit with length 0 as it specificly checks for the None statement. In this case an empty string is impossible but it is more explicit. ```py return re.match("^[a-zA-Z]+", s) is not None ```
3,570
17,217,225
Consider: ``` >>> a = {'foo': {'bar': 3}} >>> b = {'foo': {'bar': 3}} >>> a == b True ``` According to the python doc, [you can indeed use](http://docs.python.org/2/library/stdtypes.html#dict) the `==` operator on dictionaries. What is actually happening here? Is Python recursively checking each element of the di...
2013/06/20
[ "https://Stackoverflow.com/questions/17217225", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3788/" ]
Python is recursively checking each element of the dictionaries to ensure equality. See the [C `dict_equal()` implementation](http://hg.python.org/cpython/file/6f535c725b27/Objects/dictobject.c#l1839), which checks each and every key and value (provided the dictionaries are the same length); if dictionary `b` has the s...
The dictionaries are equal if they have the same keys and the same values for each corresponding key. See some examples: ``` dict(a=1, b=2) == dict(a=2, b=1) False dict(a=1, b=2) == dict(a=1, b=2, c=0) False dict(a=1, b=2) == dict(b=2, a=1) True ```
3,575
54,930,121
I was just wondering, is there any way to convert IUPAC or common molecular names to SMILES? I want to do this without having to manually convert every single one utilizing online systems. Any input would be much appreciated! For background, I am currently working with python and RDkit, so I wasn't sure if RDkit could...
2019/02/28
[ "https://Stackoverflow.com/questions/54930121", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11131756/" ]
OPSIN (<https://opsin.ch.cam.ac.uk/>) is another solution for name2structure conversion. It can be used by installing the cli, or via <https://github.com/gorgitko/molminer> (OPSIN is used by the RDKit KNIME nodes also)
The accepted answer uses the [Chemical Identifier Resolver](https://cactus.nci.nih.gov/chemical/structure) but for some reason the website seems to be buggy for me and the API seems to be messed up. So another way to connvert smiles to IUPAC name is with the the PubChem python API, which can work if your smiles is in ...
3,578
46,289,914
I have python code as follow. jv\_list is populated from resultset retrieve from D.B. query. ``` jv_list = list(result.get_points()) print(jv_list) ``` I am printing jv\_list and it is giving me below mention output. ``` [{u'in': u'19834', u'length-bytes': u'79923888', u'run-time': u'1h50m43.489993955s', u'time': ...
2017/09/19
[ "https://Stackoverflow.com/questions/46289914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3597746/" ]
Try this sequence of commands ``` >>> X = [{u'in': u'19834', u'length-bytes': u'79923888', u'run-time': u'1h50m43.489993955s', u'time': u'2017-09-08T21:20:39.846582783Z'}] >>> for x in X: ... x['answer'] = float(x['length-bytes'])/float(x['in']) ... >>> X [{'in': '19834', 'length-bytes': '79923888', 'run-time': '1...
You can't reliably do that, dictionaries are unordered. With this data structure, you will need to address the elements via their keys. that is `jv_list[0]['length_bytes'] / jv_list[0]['in']` for each pair of elements you want to divide by each other.
3,588
30,702,519
I am trying to run some piece of Python code in a Bash script, so i wanted to understand what is the difference between: ``` #!/bin/bash #your bash code python -c " #your py code " ``` vs ``` python - <<DOC #your py code DOC ``` I checked the web but couldn't compile the bits around the topic. Do you think one i...
2015/06/08
[ "https://Stackoverflow.com/questions/30702519", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3598271/" ]
The main flaw of using a here document is that the script's standard input will be the here document. So if you have a script which wants to process its standard input, `python -c` is pretty much your only option. On the other hand, using `python -c '...'` ties up the single-quote for the shell's needs, so you can onl...
If you prefer to use `python -c '...'` without having to escape with the double-quotes you can first load the code in a bash variable using here-documents: ``` read -r -d '' CMD << '--END' print ("'quoted'") --END python -c "$CMD" ``` The python code is loaded verbatim into the CMD variable and there's no need to es...
3,595
52,810,422
I go through the book: "Malware Data Science Attack Detection and Attribution" in chapter one and use pefile python module to check the AddressOfEntryPoint, I found the sample: ircbot.exe's AddressOfEntryPoint is 0xCC00FFEE when I do pe.dump\_info(). This value is quite large and look wrong. [ircbot.exe's OPTIONAL H...
2018/10/15
[ "https://Stackoverflow.com/questions/52810422", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5742815/" ]
try this ``` select * from yourtable where youcolumn like '%''%' ```
I hope this solves your problem % **'** % -> Finds any values that have " **'** " in any position By executing below query you will get the result which have '(single quote) in them ``` SELECT * FROM TABLE_NAME WHERE COLUMN_NAME LIKE "%'%" ``` i have executed the same query [enter image description here](https:/...
3,600
15,417,574
For python / pandas I find that df.to\_csv(fname) works at a speed of ~1 mln rows per min. I can sometimes improve performance by a factor of 7 like this: ``` def df2csv(df,fname,myformats=[],sep=','): """ # function is faster than to_csv # 7 times faster for numbers if formats are specified, # 2 times ...
2013/03/14
[ "https://Stackoverflow.com/questions/15417574", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1442475/" ]
Lev. Pandas has rewritten `to_csv` to make a big improvement in native speed. The process is now i/o bound, accounts for many subtle dtype issues, and quote cases. Here is our performance results vs. 0.10.1 (in the upcoming 0.11) release. These are in `ms`, lower ratio is better. ``` Results: ...
Your `df_to_csv` function is very nice, except it does a lot of assumptions and doesn't work for the general case. If it works for you, that's good, but be aware that it is not a general solution. CSV can contain commas, so what happens if there is this tuple to be written? `('a,b','c')` The python `csv` module would...
3,605
34,336,040
I am trying to extract the ranking text number from this link [link example: kaggle user ranking no1](https://www.kaggle.com/titericz). More clear in an image: [![enter image description here](https://i.stack.imgur.com/sClUu.png)](https://i.stack.imgur.com/sClUu.png) I am using the following code: ``` def get_single...
2015/12/17
[ "https://Stackoverflow.com/questions/34336040", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4157666/" ]
The data is databound using javascript, as the "data-bind" attribute suggests. However, if you download the page with e.g. `wget`, you'll see that the rankingText value is actually there inside this script element on initial load: ``` <script type="text/javascript" profile: { ... "ranking": 96, "rankingText": "...
This could because of dynamic data filling. Some javascript code, fill this tag after page loading. Thus if you fetch the html using requests it is not filled yet. ``` <h4 data-bind="text: rankingText"></h4> ``` Please take a look at [Selenium web driver](http://www.seleniumhq.org/projects/webdriver/). Using this ...
3,614
46,465,389
I have a python string like this; ``` input_str = "2548,0.8987,0.8987,0.1548" ``` I want to remove the sub-string at the end after the last comma, including the comma itself. The output string should look like this; ``` output_str = "2548,0.8987,0.8987" ``` I am using python v3.6
2017/09/28
[ "https://Stackoverflow.com/questions/46465389", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3848207/" ]
With `split` and `join` ======================= ``` ','.join(input_str.split(',')[:-1]) ``` ### Explanation ``` # Split string by the commas >>> input_str.split(',') ['2548', '0.8987', '0.8987', '0.1548'] # Take all but last part >>> input_str.split(',')[:-1] ['2548', '0.8987', '0.8987'] # Join the parts with com...
There's [the split function](https://www.tutorialspoint.com/python/string_split.htm) for python : ``` print input_str.split(',') ``` Will return : ``` ['2548,0.8987,0.8987', '0.1548'] ``` But in case you have multiple commas, [rsplit is here for that](https://docs.python.org/2/library/stdtypes.html#str.rsplit) : ...
3,620
71,310,217
My goal is to use gpu(GE FORCE GTX 850M). I have tried according to this guide(<https://docs.anaconda.com/anaconda/user-guide/tasks/tensorflow/>). Tensoflow 2.8 is installed and keras also. But when I execute the test code, the output is as below. It must be that the code does not or cannot use gpu. What went wrong? `...
2022/03/01
[ "https://Stackoverflow.com/questions/71310217", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5554839/" ]
The anaconda guide looks outdated, because since Tensorflow 2.0, tensorflow and tensorflow-gpu are merged into one. If you are using Tensorflow 2, I would advise you this guide <https://www.tensorflow.org/install/gpu> which has worked for me (do not download the latest cuDNN SDK version which is bugged but the one ind...
In this guide <https://www.tensorflow.org/install/source_windows>, there are version configuration .It helped.
3,627
9,430,644
``` class test: def __init__(self): test_dict = {'1': 'one', '2': 'two'} def test_function(self): print self.test_dict if __name__ == '__main__': t = test() print t.test_dict ``` Error: ``` AttributeError: test instance has no attribute 'test_dict' ``` Also, if i execute code: `t.t...
2012/02/24
[ "https://Stackoverflow.com/questions/9430644", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1031769/" ]
You forgot `self`. Change this: ``` def __init__(self): test_dict = {'1': 'one', '2': 'two'} ``` with: ``` def __init__(self): self.test_dict = {'1': 'one', '2': 'two'} ``` `self` is your *instance* inside the methods in your class. That is not because `self` is a special keyword but because `self` is us...
You made an error in your `__init__`. This: ``` def __init__(self): test_dict = {'1': 'one', '2': 'two'} ``` Should be: ``` def __init__(self): self.test_dict = {'1': 'one', '2': 'two'} ```
3,628
13,174,127
I want to be able to capture the value of an HTML attribute with a python regexp. currently I use ``` re.compile( r'=(["\'].*?["\'])', re.IGNORECASE | re.DOTALL ) ``` My problem is that I want the regular expression to "remember" whether the attribute started with a single or a double quote. I found the bug in my c...
2012/11/01
[ "https://Stackoverflow.com/questions/13174127", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1616042/" ]
You can capture the first quote and then use a backreference: ``` r'=((["\']).*?\2)' ``` However, regular expressions are [not the proper approach to parsing HTML](https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454). You should consider using a DOM pars...
The following would be more efficient in theory: ``` regex = r'"[^"]*"|\'[^']*\'' ``` For the reference, here's Jeffrey Friedl's [expression](http://regex.info/dlisting.cgi?ed=3&id=36481) for html tags (from the owl book): ``` < # Opening "<" ( # Any amount of . . . "[^"]*" # ...
3,630
21,067,443
I can use the following code to change a string to a variable and then call function of the library that was previously imported. ``` >>> import sys >>> x = 'sys' >>> globals()[x] <module 'sys' (built-in)> >>> globals()[x].__doc__ ``` Without first importing the module, I have an string to variable but I can't use t...
2014/01/11
[ "https://Stackoverflow.com/questions/21067443", "https://Stackoverflow.com", "https://Stackoverflow.com/users/610569/" ]
Most Python coders prefer using [`importlib.import_module`](http://docs.python.org/2.7/library/importlib.html#importlib.import_module) instead of `__import__`: ``` >>> from importlib import import_module >>> mod = raw_input(":") :sys >>> sys = import_module(mod) >>> sys <module 'sys' (built-in)> >>> sys.version_info #...
You are looking for [`__import__`](http://docs.python.org/2/library/functions.html#__import__) built-in function: ``` __import__(globals()[y]) ``` Basic usage: ``` >>>math = __import__('math') >>>print math.e 2.718281828459045 ``` You can also look into `importlib.import_module` as suggested in another answer and...
3,631
46,963,157
I'm trying to implement an efficient way of creating a frequency table in python, with a rather large numpy input array of `~30 million` entries. Currently I am using a `for-loop`, but it's taking far too long. The input is an ordered `numpy array` of the form ``` Y = np.array([4, 4, 4, 6, 6, 7, 8, 9, 9, 9..... etc]...
2017/10/26
[ "https://Stackoverflow.com/questions/46963157", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8840045/" ]
You can simply do this using Counter from collections module. Please see the below code i ran for your test case. ``` import numpy as np from collections import Counter Y = np.array([4, 4, 4, 6, 6, 7, 8, 9, 9, 9,10,5,5,5]) print(Counter(Y)) ``` It gave the following output ``` Counter({4: 3, 9: 3, 5: 3, 6: 2, 7: 1,...
I think numpy.unique is your solution. <https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.unique.html> ``` import numpy as np t = np.random.randint(0, 1000, 100000000) print(np.unique(t, return_counts=True)) ``` This takes ~4 seconds for me. The collections.Counter approach takes ~10 seconds. But t...
3,634
36,433,011
At this moment I have a game that drops falling colored blocks (*obstacles*) from the top of the screen, and the objective is for the player to dodge said (*obstacles*) by moving either left or right. I currently have set up where every time the user runs the script, the blocks will be a different color, but the probl...
2016/04/05
[ "https://Stackoverflow.com/questions/36433011", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3777680/" ]
Add relative positioning to the container and absolute positioning to the icon ``` #menui { left: 0; position:absolute; } .smalltop { background-color: #FFF; list-style-type: none; margin: 0 auto; position:relative; } ``` **[jsFiddle example](https://jsfiddle.net/j08691/pzLbruhx/1/)**
Just give property `float:left` to `#menui`, and see the result
3,636
71,775,713
I'm trying to do some interesting integration problems for my Calculus I students under Anaconda python 3.8.5 and sympy version 1.9, So question 1 is: integrate(sin(m \* x)\* cos(n \* x), x) [![enter image description here](https://i.stack.imgur.com/lOzzI.png)](https://i.stack.imgur.com/lOzzI.png) whereas x is the ...
2022/04/07
[ "https://Stackoverflow.com/questions/71775713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8438488/" ]
If you want to say that `m` and `n` are not equal (and get the answer you gave) make one odd and one even: ``` >>> var('m',odd=True) m >>> var('n',even=True) n >>> integrate(sin((m) * x)* cos(n * x), x) -m*cos(m*x)*cos(n*x)/(m**2 - n**2) - n*sin(m*x)*sin(n*x)/(m**2 - n**2) ``` (You get an interesting result if you j...
First of all, what version of SymPy are you using? You can verify that with: ```py import sympy as sp print(sp.__version__) ``` If you are using older versions, maybe the solver is having trouble. The following solution has been tested on SymPy 1.9 and 1.10.1. ```py # define a, x as ordinary symbols with no assumpt...
3,638
7,774,740
This is an extension question of [PHP pass in $this to function outside class](https://stackoverflow.com/questions/7774444/php-pass-in-this-to-function-outside-class) And I believe this is what I'm looking for but it's in python not php: [Programmatically determining amount of parameters a function requires - Python](...
2011/10/14
[ "https://Stackoverflow.com/questions/7774740", "https://Stackoverflow.com", "https://Stackoverflow.com/users/266763/" ]
Use [Reflection](http://php.net/book.reflection), especially [ReflectionFunction](http://php.net/class.reflectionfunction) in your case. ``` $fct = new ReflectionFunction('client_func'); echo $fct->getNumberOfRequiredParameters(); ``` As far as I can see you will find [getParameters()](http://php.net/reflectionfunct...
Only way is with reflection by going to <http://us3.php.net/manual/en/book.reflection.php> ``` class foo { function bar ($arg1, $arg2) { // ... } } $method = new ReflectionMethod('foo', 'bar'); $num = $method->getNumberOfParameters(); ```
3,639
60,973,894
[Open Street Map (pyproj). How to solve syntax issue?](https://stackoverflow.com/questions/59596835/open-street-map-pyproj-how-to-solve-syntax-issue) has a similar question and the answers there did not help me. I am using the helper class below a few hundred times and my console gets flooded with warnings: ``` /opt/...
2020/04/01
[ "https://Stackoverflow.com/questions/60973894", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1497139/" ]
In order to keep using the old syntax (feeding the transformer `(Lon,Lat)` pairs) you can use the `always_xy=True` parameter when creating the transformer object: ```py from pyproj import Transformer transformer = Transformer.from_crs(4326, 3857, always_xy=True) points = [ (6.783333, 51.233333), # Dusseldorf ...
This is my current guess for the fix: ``` #e4326=Proj(init='epsg:4326') e4326=CRS('EPSG:4326') #e3857=Proj(init='epsg:3857') e3857=CRS('EPSG:3857') ``` **Projection helper class** ``` from pyproj import Proj, CRS,transform class Projection: ''' helper to project lat/lon values to map ''...
3,640
66,514,262
i want to plot a graphs of my csv file data now i want epoch as x axis and on y axis the label "acc" and "val\_acc" is plot i try the following code but it gives blank graph ` ``` x = [] y = [] with open('trainSelfVGG.csv','r') as csvfile: plots = csv.reader(csvfile, delimiter=',') for row in plots: ...
2021/03/07
[ "https://Stackoverflow.com/questions/66514262", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12673562/" ]
You are correct, a string cannot be returned as an array via the `return` statement. When you pass or return an array, only a pointer to its first element is used. Hence the function `get_name()` returns a pointer to the array defined locally with automatic storage (aka *on the stack*). This is incorrect as this array ...
You are returning address of `real_name` from `get_name` method which will go out of scope after the function returns. Instead allocate the memory of string on heap and return its address. Also, the caller would need to free the string memory allocated on the heap to avoid any memory leaks.
3,641
27,088,984
I am learning python so this question may be a simple question, I am creating a list of cars and their details in a list as bellow: ``` car_specs = [("1. Ford Fiesta - Studio", ["3", "54mpg", "Manual", "ยฃ9,995"]), ("2. Ford Focous - Studio", ["5", "48mpg", "Manual", "ยฃ17,295"]), ("3. Vauxhall...
2014/11/23
[ "https://Stackoverflow.com/questions/27088984", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4284218/" ]
Just append the tuple to the list making sure to separate new\_name from the list with a `,`: ``` new_name = input("What is the name of the new car?") new_doors = input("How many doors does it have?") new_efficency = input("What is the fuel efficency of the new car?") new_gearbox = input("What type of gearbox?") new_p...
You are not setting the first element go your tuple correctly. You are appending the name to the length of car specs as you expect. Also new\_name is as string, when you do new\_name[x] your asking python for the x+1th character in that string. ``` new_name = input("What is the name of the new car?") new_doors = inpu...
3,643
41,474,163
I was doing Singly-Linked List implementation and I remember Linus Torvalds talking about it [here](https://youtu.be/o8NPllzkFhE?t=890). In a singly-linked list in order to remove a node we should have access to the previous node and then change the node it is currently pointing to. Like this [![enter image descripti...
2017/01/04
[ "https://Stackoverflow.com/questions/41474163", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1597944/" ]
Sure you can do this in Python. What he's saying is that you have some data structure that represents the list itself and points to the head of the list, and you manipulate that just as you would the pointer in a list item when you're dealing with the first list item. Now Python is not C so the implementation would be...
You cannot use Linus's specific trick in Python, because, as you well know, Python does not have pointers (as such) or an address-of operator. You can still, however, eliminate a special case for the list head by giving the list a dummy head node. You can do that as an inherent part of the design of your list, or you c...
3,644
34,522,741
A request comes to tornado's GET handler of a web app. From the `GET` function, a `blocking_task` function is called. This `blocking_task` function has `@run_on_executor` decorator. But this execution fails. Could you please help on this. It seems that motor db is not able to execute the thread. ``` import time from ...
2015/12/30
[ "https://Stackoverflow.com/questions/34522741", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5722595/" ]
Finally following code works, Thank you @kwarunek Also added parameters to the callback function. ``` import time from concurrent.futures import ThreadPoolExecutor from tornado import gen, web from tornado.concurrent import run_on_executor from tornado.ioloop import IOLoop import argparse from common.config import A...
From [docs](http://www.tornadoweb.org/en/stable/concurrent.html#tornado.concurrent.run_on_executor) > > IOLoop and executor to be used are determined by the io\_loop and > executor attributes of self. To use different attributes, pass keyword > arguments to the decorator > > > You have to provide a init threadp...
3,649
61,257,025
I'm new to python and tkinter and I try to create a tool witch loops every 5 seconds over a directory to list all the files. In my code the filenames in the list appears only after I interupt the loop. My goal is to start a loop by clicking on a button to start the endless loop to list the files and a stop button to ...
2020/04/16
[ "https://Stackoverflow.com/questions/61257025", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10474530/" ]
Unary means one, so what they are talking about is a constructor with a single parameter. The standard name for such a thing is a [conversion constructor](https://stackoverflow.com/questions/15077466/what-is-a-converting-constructor-in-c-what-is-it-for).
Unary refers to one or singular, so a 'Unary constructor' ideally refers to a constructor with a single parameter.
3,652
45,628,813
Previously I was working without unittests and I had this structure for my project: ``` -main.py -folderFunctions: -functionA.py ``` Just using init file in folderFunctions, and importing ``` from folderFunctions import functionA ``` everything was working good. Now I have also unittests wihch I orga...
2017/08/11
[ "https://Stackoverflow.com/questions/45628813", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5178905/" ]
If you want your library/application to become bigger and easy to package I hardly recommend to separate source code from test code, because test code shouldn't be packaged in binary distributions (egg or wheel). You can follow this tree structure: ``` +-- src/ | +-- main.py | \-- folder_functions/ # <- Python...
The more elegant way is `from folderFunctions.folderTest import testFunctionA` and make sure that you have an `__init__.py` file in the `folderTest` directory. You may also look at this [question](https://stackoverflow.com/questions/8953844/import-module-from-subfolder)
3,653
49,054,768
I'm going to optimize three variable `x`, `alpha` and `R`. `X` is a one dimensional vector, `alpha` is a two dimensional vector and `R` is a scalar value. How can I maximize this function? I write below code: ``` #from scipy.optimize import least_squares from scipy.optimize import minimize import numpy as np sentences...
2018/03/01
[ "https://Stackoverflow.com/questions/49054768", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2742177/" ]
I find the solution. ``` from scipy.optimize import least_squares from scipy.optimize import minimize import numpy as np def func(x_f, *args, sign=1.0): """ Objective function """ sentences_lengths, length_constraint, sentences_idx, sentences_scores, damping, pairwise_idx, overlap_matrix\ ...
I can do this task. ``` from scipy.optimize import least_squares from scipy.optimize import minimize import numpy as np def func(x_f, *args, sign=1.0): """ Objective function """ sentences_lengths, length_constraint, sentences_idx, sentences_scores, damping, pairwise_idx, overlap_matrix\ ...
3,654
34,586,114
In Django, the convention is to put all of your static files (i.e css, js) specific to your app into a folder called **static**. So the structure would look like this: ``` mysite/ manage.py mysite/ --> (settings.py, etc) myapp/ --> (models.py, views.py, etc) static/ ``` In `mysite/settings.py` I ...
2016/01/04
[ "https://Stackoverflow.com/questions/34586114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Collect static files from multiple apps into a single path ---------------------------------------------------------- Well, a single Django *project* may use several *apps*, so while there you only have one `myapp`, it may actually be `myapp1`, `myapp2`, etc By copying them from inside the individual apps into a sing...
It's useful when there are multiple django apps within the site. `collectstatic` will then collect static files from all the apps in one place - so that it could be served up in a production environment.
3,655
60,418,192
Julia newbe here, transitioning from python. So, I want to build what in Python I would call list, made of lists made of lists. In my case, it's a 1000 long list whose element is a list of 3 lists. Until now, I have done it this way: ``` BIG_LIST = collect(Array{Int64,1}[[],[],[]] for i in 1:1000) ``` This served...
2020/02/26
[ "https://Stackoverflow.com/questions/60418192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10139617/" ]
First, if you know that intermediate lists always have 3 elements, you'll probably be better off using [`Tuple` types](https://docs.julialang.org/en/v1/manual/types/#Tuple-Types-1) for those. And tuples can specify independently the types of their elements. So something like this might suit your purposes: ``` julia> l...
Francois has given you a great answer. I just wanted to raise one other possibility. It sounds like your data has a fairly complicated, but specific, structure. For example, the fact that your outer list has 1000 elements, and your inner list always has 3 lists... Sometimes in these situations it can be more intuitiv...
3,661
44,651,760
When I run `python manage.py migrate` on my Django project, I get the following error: ``` Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/hari/project/env/local/lib/python2.7/site- packages/django/core/management/__init__.py", line 363, in ...
2017/06/20
[ "https://Stackoverflow.com/questions/44651760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3186922/" ]
Since you are using a custom User model, you can do 4 steps: 1. Comment out django.contrib.admin in your INSTALLED\_APPS settings > > > ``` > INSTALLED_APPS = [ > ... > #'django.contrib.admin', > ... > ] > > ``` > > 2. Comment out admin path in urls.py > > > ``` > urlpatterns = [ > ... > #path...
If you set **AUTH\_USER\_MODE**L in **settings.py** like this: ``` AUTH_USER_MODEL = 'custom_user_app_name.User' ``` you should comment this line before run **makemigration** and **migrate** commands. Then you can uncomment this line again.
3,662
54,235,347
I am implementing a GUI in Python/Flask. The way flask is designed, the local host along with the port number has to be "manually" opened. Is there a way to automate it so that upon running the code, browser(local host) is automatically opened? I tried using webbrowser package but it opens the webpage after the sess...
2019/01/17
[ "https://Stackoverflow.com/questions/54235347", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9557881/" ]
Use timer to start new thread to open web browser. ``` import webbrowser from threading import Timer from flask import Flask app = Flask(__name__) @app.route("/") def hello(): return "Hello World!" def open_browser(): webbrowser.open_new("http://127.0.0.1:5000") if __name__ == "__main__": Timer(1, ...
**I'd suggest the following improvement to allow for loading of the browser when in debug mode:** *Inspired by [this answer](https://stackoverflow.com/a/9476701/10521959), will only load the browser on the first run...* ``` def main(): # The reloader has not yet run - open the browser if not os.environ.get...
3,672
42,506,954
I'm calling `curl` from a Perl script to POST a file: ```perl my $cookie = 'Cookie: _appwebSessionId_=' . $sessionid; my $reply = `curl -s -H "Content-type:application/x-www-form-urlencoded" -H "$cookie" --data \@portports.txt http://$ipaddr/...
2017/02/28
[ "https://Stackoverflow.com/questions/42506954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4153606/" ]
The `files` parameter encodes your file as a multipart message, which is not what you want. Use the `data` parameter instead: ``` import requests url = 'http://www.example.com/' headers = {'Content-Type': 'application/x-www-form-urlencoded'} cookies = {'_appwebSessionId_': '1234'} with open('foo', 'rb') as file: ...
First UTF-8 decode your URL. Put headers and files in a JSON object, lesse all\_data. Now your code should look like this. ```python all_data = { { 'file': ('portports.txt', open('portports.txt', 'rb')) }, { 'Content-type' : 'application/x-www-form-urlencoded', 'Cookie' : '_appweb...
3,673
57,812,562
I want to see the full trace of the code till a particular point so i do ``` ... import traceback traceback.print_stack() ... ``` Then it will show ``` File ".venv/lib/python3.7/site-packages/django/db/models/query.py", line 144, in __iter__ return compiler.results_iter(tuple_expected=True, chunked_fetch=sel...
2019/09/05
[ "https://Stackoverflow.com/questions/57812562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2897115/" ]
Pygments lists the available [lexers](http://pygments.org/docs/lexers/). You can do this with Python3TracebackLexer. ``` from pygments import highlight from pygments.lexers import Python3TracebackLexer from pygments.formatters import TerminalTrueColorFormatter err_str = ''' File ".venv/lib/python3.7/site-packages/d...
Alternatively, use the [rich](https://github.com/willmcgugan/rich) library. [With just two lines of code](https://rich.readthedocs.io/en/latest/traceback.html), it will prettify your tracebacks... and then some! ```py from rich.traceback import install install() ``` How does it look afterwards? Take a gander: [![F...
3,674
40,081,601
I have a instance of django deployed in Heroku as follow, Procfile: ``` web: python manage.py collectstatic --noinput ; gunicorn MY_APP.wsgi --log-file - worker: celery -A MY_APP worker beat: celery -A MY_APP beat ``` This instance can receive 2000-4000 requests per minute, and sometimes it is too much. I know I s...
2016/10/17
[ "https://Stackoverflow.com/questions/40081601", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1073310/" ]
The first thing that springs to mind is to check out connection pooling and/or persistent database connections. Depending on how much database access your app is using, this could significantly increase the number of RPM your app is able to handle. Check out [this StackOverflow question](https://stackoverflow.com/ques...
The whole point of Heroku is that you can dynamically scale your app. You can spin up new web workers with `heroku ps:scale web+1` for example.
3,675
6,261,459
Here is a test case I've created for a problem I found out. For some reason the dict() 'l' in B() does not seem to hold the correct value. See the output below on my Linux 11.04 Ubuntu, python 2.7.1+. ``` class A(): name = None b = None def __init__(self, name, bname, cname, dname): self.name = na...
2011/06/07
[ "https://Stackoverflow.com/questions/6261459", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
What happened is that you created a class attribute. Create an instance attribute instead by instantiating in `__init__()`.
It looks like you are trying to "declare" instance attributes at the class level. Class attributes have their own specific uses in Python, and it is wrong to put them there if you are not intending to ever use the class attributes ``` class A(): name = None # Don't do this b = None # Don't do this def...
3,676
30,969,533
I have a task to draw a potential graph with 3 variables, x , y, and z. I don't think we can draw the function U(x, y, z) directly with matplotlib. So what I'm planning to do is to draw cross sectional plots of x-y and y-z. I believe this is enough because the function U(x, y, z) has periodic behavior. I'm quite new t...
2015/06/21
[ "https://Stackoverflow.com/questions/30969533", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4358807/" ]
String literals in SQL are denoted by single quotes (`'`). Without them, and string would be treated as an object name. Here, you generate a where clause `title = Test`. Both are interpreted as columns names, and the query fails since there's no column `Test`. To solve this, you could surround `Test` by quotes: ``` ...
Change your WHERE clause to be... ``` ... title = 'test' ``` The way it is written it is looking for a column named Test.
3,677
7,360,654
I am trying to *generate* self signed SSL certificates using Python, so that it is platform independent. My target is the \*.pem format. I found [this script](http://sunh11373.blogspot.com/2007/04/python-utility-for-converting.html) that generates certificates, but no information how to self-sign them.
2011/09/09
[ "https://Stackoverflow.com/questions/7360654", "https://Stackoverflow.com", "https://Stackoverflow.com/users/722291/" ]
The script you've linked doesn't create self-signed certificate; it only creates a request. To create self-signed certificate you could use [`openssl`](https://www.openssl.org/docs/faq.html#USER4) it is available on all major OSes. ``` $ openssl req -new -x509 -key privkey.pem -out cacert.pem -days 1095 ``` If you...
You could use the openssl method that J.F. Sebastian stated from within Python. Import the OS lib and call the command like this: ``` os.system("openssl req -new -x509 -key privkey.pem -out cacert.pem -days 1095") ``` If it requires user interaction, it might work if you run it via subprocess pipe and allow for raw...
3,678
47,441,401
I have an 8\*4 numpy array with floats (myarray) and would like to transform it into a dictionary of dataframes (and eventually concatenate it into one dataframe) with pandas in python. I'm coming across the error "ValueError: DataFrame constructor not properly called!" though. Here is the way I attempt it: ``` my...
2017/11/22
[ "https://Stackoverflow.com/questions/47441401", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8938572/" ]
You are trying to cast a list of 2 numbers to int. [int only takes a number or a string as its argument](https://docs.python.org/3/library/functions.html#int). What you want is to [map](http://book.pythontips.com/en/latest/map_filter.html#map) the int function to each item in the list. ``` >>> w, h = map(int, input()...
`int(...)` constructs an integer which cannot be unpacked to a tuple `W, H`. What you probably want is ``` W, H = (int(x) for x in input().split(" ")) ```
3,679
40,853,556
I have a list of tuples in python containing 3-dimenstional data, where each tuple is in the form: (x, y, z, data\_value), i.e., I have data values at each (x, y, z) coordinate. I would like to make a 3D discrete heatmap plot where the colors represent the value of data\_values in my list of tuples. Here, I give an exa...
2016/11/28
[ "https://Stackoverflow.com/questions/40853556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3076813/" ]
### New answer: It seems we really want to have a 3D Tetris game here ;-) So here is a way to plot cubes of different color to fill the space given by the arrays `(x,y,z)`. ``` from mpl_toolkits.mplot3d import Axes3D import numpy as np import matplotlib.pyplot as plt import matplotlib.cm import matplotlib.colorbar ...
I've update the code above to be compatible with newer version of matplot lib. ```py import numpy as np import matplotlib.pyplot as plt import matplotlib.colorbar from matplotlib import cm viridis = cm.get_cmap('plasma', 8) #Our color map def cuboid_data(center, size=(1,1,1)): # code taken from # http://stac...
3,680
13,855,056
I have a list of numbers, let's say `[1091, 2053, 4099, 4909, 5023, 9011]`. Here every number has it's permutation in a list too. Now i want to group these permutations of each other, so the list becomes `[[1091, 9011], [2053, 5023], [4099, 4909]]`. I know how to use [`groupby`](http://docs.python.org/2/library/itertoo...
2012/12/13
[ "https://Stackoverflow.com/questions/13855056", "https://Stackoverflow.com", "https://Stackoverflow.com/users/596361/" ]
``` import itertools as it a = [1091, 2053, 4099, 4909, 5023, 9011] sort_string = lambda x: sorted(str(x)) [[int(x) for x in v] for k,v in it.groupby(sorted(a, key=sort_string), key=sort_string)] # [[1091, 9011], [2053, 5023], [4099, 4909]] ```
You can use `collections.Counter` to represent each number as a tuple of `integer, total_occurrences` and then store all the data in instances in a dictionary: ``` from collections import Counter, defaultdict dest = defaultdict(list) data = [1091, 2053, 4099, 4909, 5023, 9011] data = ((Counter([int(x) for x in str(d...
3,681
14,087,547
**Conclusion:** It's impossible to override or disable Python's built-in escape sequence processing, such that, you can skip using the raw prefix specifier. I dug into Python's internals to figure this out. So if anyone tries designing objects that work on complex strings (like regex) as part of some kind of framework,...
2012/12/30
[ "https://Stackoverflow.com/questions/14087547", "https://Stackoverflow.com", "https://Stackoverflow.com/users/482691/" ]
I think you have an understandable confusion about a difference between Python string literals (source code representation), Python string objects in memory, and how that objects can be printed (in what format they can be represented in the output). If you read some bytes from a file into a bytestring you can write th...
I think you will have to go the join route. Here's an example: ``` >>> m = {chr(c): '\\x{0}'.format(hex(c)[2:].zfill(2)) for c in xrange(0,256)} >>> >>> x = "\x20\x01\x0d\xb8\x85\xa3\x00\x00\x00\x00\x8a\x2e\x03\x70\x73\x34" >>> print ''.join(map(m.get, x)) \x20\x01\x0d\xb8\x85\xa3\x00\x00\x00\x00\x8a\x2e\x03\x70\x73...
3,683
45,625,042
I have a master python script, that goes and automates configuring nodes in parallel in a distributed system setup in our lab. I run multiple instances of kickstart.py and it goes and configures all nodes in parallel. How do I create log handler such that each instance of kickstart.py configures each node separately i...
2017/08/10
[ "https://Stackoverflow.com/questions/45625042", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8448115/" ]
A solution using `st_distance` from the `sf` package. `my_df_final` is the final output. ``` # Load packages library(tidyverse) library(sp) library(sf) # Create ID for my_df_1 and my_df_2 based on row id # This step is not required, just help me to better distinguish each point my_df_1 <- my_df_1 %>% mutate(ID1 = row...
Based on this [answer](https://stackoverflow.com/questions/31668163/geographic-distance-between-2-lists-of-lat-lon-coordinates) you could do ``` library(geosphere) mat <- distm(my_df_1[2:1], my_df_2[2:1], fun = distVincentyEllipsoid) cbind(my_df_1, my_df_2[max.col(-mat),]) ``` Which gives: ``` # START_LAT STAR...
3,684
58,351,041
I am trying to install a virtualenv in windows 10 using a step process I found on some website. The steps are as follows, but only care about 1-4 for now: 1. Run Windows Power Shell as Administrator 2. pip install virtualenv 3. pip install virtualenvwrapper-win 4. mkvirtualenv โ€˜C:\Users\username\Documents\Virtualenvโ€™ ...
2019/10/12
[ "https://Stackoverflow.com/questions/58351041", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12204393/" ]
The compiler changes the name of the local function, preventing you from calling it using its original name from the debugger. See [this question](https://stackoverflow.com/questions/45337983/why-local-functions-generate-il-different-from-anonymous-methods-and-lambda-expr) for examples. What you can do is temporarily m...
I'll have to say that I haven't tried it and will not bother to do so because there's a lot more to local functions than you think and I would put it very low in terms of priority for the debugger. Try putting your code in [sharplab.io](https://sharplab.io/) and see what it takes to make that local function.
3,685
53,539,612
I have a big `tab separated` file like this: ``` chr1 9507728 9517729 0 chr1 9507728 9517729 5S_rRNA chr1 9537731 9544392 0 chr1 9537731 9547732 5S_rRNA chr1 9497727 9507728 0 chr1 9497727 9507728 5S_rRNA chr1 9517729 9527730 0 chr1 9517729 9527730 5S_rRNA chr8 1118560 1118591 1 ch...
2018/11/29
[ "https://Stackoverflow.com/questions/53539612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10657934/" ]
If there is no common data between different clients/orgs, there is no point of having a shared channel between them. Taking care of permissions overs data will complicate your network setup. It would be better to abstract out that detail from network design. You should have one org corresponding to each client. In ea...
I think you could encrypt every client's data by passing the transient key to chaincode,and just manage the keys, this may be light weight and fesible for your scenery.
3,686
22,650,001
I have a Django application running on [Dotcloud](http://dotcloud.com/ "Dotcloud"). I have tried to add [Logentries](http://logentries.com/ "Logentries") logging which works in normal usage for my site, but causes my cron jobs to fail with this error - `Traceback (most recent call last): File "/home/dotcloud/curren...
2014/03/26
[ "https://Stackoverflow.com/questions/22650001", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3458323/" ]
This is what you want: ``` List<Card> cards = IntStream.rangeClosed(1, 4) .boxed() .flatMap(value -> IntStream.rangeClosed(1, 13) .mapToObj(suit -> new Card(value, suit)) ) .collect(Collectors.toList()); ``` Points to note: * you have to box the ints because `flatMap` on primit...
Another way to get what you want (based on Maurice Naftalin's answer): ``` List<Card> cards = IntStream.rangeClosed(1, 4) .mapToObj(value -> IntStream.rangeClosed(1, 13) .mapToObj(suit -> new Card(value, suit)) ) .flatMap(Function.identity()) .collect(Collectors.toList()) ; ``` Additional points to note:...
3,687
51,634,841
I have a little project in python to do. I have to parse 4 arguments in my program. so the commands are: -i (store the source\_file) -d (store the destination\_file) -a (store the a folder named: i386, x64\_86 or all ) -p (store the folder named: Linux, Windows or all) The folder Linux has 2 folders in: i386 and x64\...
2018/08/01
[ "https://Stackoverflow.com/questions/51634841", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10123257/" ]
After peeking into [the PHP source code](https://github.com/php/php-src/blob/master/ext/gd/gd.c#L2287), to have some insights about the "[imagecreatefromstring](http://php.net/manual/en/function.imagecreatefromstring.php)" function, I've discovered that it handles only the following image formats: * JPEG * PNG * GIF...
Save your pptx again in PPT 2007 format in open office or MS Powerpoint.Its format issue.You are opening a very recent PPT format with 2007
3,688
56,581,577
Python says that TrackerMedianFlow\_create() is no longer an attribute of cv2. I've looked here but it's not the same: [OpenCV, How to pass parameters into cv2.TrackerMedianFlow\_create function?](https://stackoverflow.com/questions/47723349/opencv-how-to-pass-parameters-into-cv2-trackermedianflow-create-function) I'v...
2019/06/13
[ "https://Stackoverflow.com/questions/56581577", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7174600/" ]
for opencv 4.5.1 user opencv-contrib-python ``` import cv2 cv2.legacy_TrackerMedianFlow() ```
`TrackerMedianFlow` is a [module within the opencv-contrib package](https://github.com/opencv/opencv_contrib/tree/master/modules/tracking/src), and does not come standard with the official OpenCV distribution. You will need to install the opencv-contrib package to access `TrackerMedianFlow_create()` Per the [document...
3,689
55,643,507
I am getting this valid error while preprocessing some data: ``` 9:46:56.323 PM default_model Function execution took 6008 ms, finished with status: 'crash' 9:46:56.322 PM default_model Traceback (most recent call last): File "/user_code/main.py", line 31, in default_model train, endog, exog, _, _, rawDf = pre...
2019/04/12
[ "https://Stackoverflow.com/questions/55643507", "https://Stackoverflow.com", "https://Stackoverflow.com/users/732570/" ]
Your `preprocess` function is declared `async`. This means the code in it isn't actually run where you call `preprocess`, but instead when it is eventually `await`ed or passed to a main loop (like `asyncio.run`). Because the place where it is run is no-longer in the try block in `default_model`, the exception is not ca...
Do the line numbers in the error match up with the line numbers in your code? If not is it possible that you are seeing the error from a version of the code before you added the try...except?
3,692
54,836,440
There is a chance this is still a problem and the Pyinstaller and/or Folium people have no interest in fixing it, but I'll post it again here in case someone out there has discovered a workaround. I have a program that creates maps, geocodes etc and recently added the folium package to create some interactive maps in ...
2019/02/22
[ "https://Stackoverflow.com/questions/54836440", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9431874/" ]
I had the same problem. Pyinstaller could not work with the Python Folium package. I could not get your cx\_Freeze solution to work due to issues with Python 3.7 and cx\_Freeze but with a day of stress I found a Pyinstaller solution which I am sharing with the community. Firstly you have to edit these 3 files: 1. \...
I could not get this to work using pyinstaller. I had to instead use cx\_Freeze. `pip install cx_Freeze` cx\_Freeze requires that a setup.py file is created, typically in the same folder as the main script that is being converted to an exe. My setup.py file looks like this: ``` import sys from cx_Freeze import setu...
3,693
20,364,207
Hey I've been trying to add Python 3.3 to windows powershell by repacing 27 with 33 in the path. I tried to post a screenshot but turns out I need 10 rep so I'll just copy and paste what I've attempted: ``` [Enviroment]::SetEnviromentVariable("Path", "$env:Path;C:\Python33", "User") ``` > ``` [Enviroment]::SetEnvi...
2013/12/03
[ "https://Stackoverflow.com/questions/20364207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3063721/" ]
Python 3.3 comes with PyLauncher (py.exe), which is installed in the C:\Windows directory (already on the path) and enables any installed Python to be executed via command line as follows: ``` Windows PowerShell Copyright (C) 2009 Microsoft Corporation. All rights reserved. PS C:\> py Python 3.3.3 (v3.3.3:c3896275c0f...
The windows environment variable `path` is searched left to right. If the path to the 2.7 binaries is still in the variable, it will never find the 3.3 binaries, whose path you are appending to the end of the path variable. Also, you are not adding the path to PowerShell. The windows python binaries are what PowerShel...
3,696
48,272,511
I have CLI tool I need open ([indy](https://github.com/hyperledger/indy-node/blob/stable/getting-started.md)), and then execute some commands. So I want to write a bash script to do this for me. Using python as example it might look like: ``` #!/bin/bash python print ("hello world") ``` But ofcourse all this doe...
2018/01/16
[ "https://Stackoverflow.com/questions/48272511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1068446/" ]
You forgot to add minutes to `setMinutes`: ``` function getUserTimeZoneDateTime() { var currentUtcDateTime = moment.utc().toDate(); var mod_start = new Date(currentUtcDateTime.setMinutes(currentUtcDateTime.getMinutes() + GlobalValues.OffsetMinutesFromUTC - currentUtcDateTime.getTimezoneOffset())); var cur...
``` var now = new Date().getTime(); ``` This gets the time and stores it in the variable, here called `now`. It should get the time wherever the user is. Hope this helps!
3,697
73,064,635
I was trying to capture a video in kivy/android using camera4kivy. but it seems that this function won't work. I tried capture video with location, subdir and filename (kwarg\*\*) but still nothing happend. ``` from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.uix.image import Image from came...
2022/07/21
[ "https://Stackoverflow.com/questions/73064635", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19499522/" ]
You can use `Map` collection: ``` new Map(fooArr.map(i => [i.name, i.surname])); ``` As [mdn says about `Map` collection](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map): > > The Map object holds key-value pairs and remembers the original > insertion order of the keys. Any val...
To add to the previous answer. This React guide explains the arrays and how to use or set your keys for them: <https://reactjs.org/docs/lists-and-keys.html#keys> I would recommend making `<div>`s for each result or make a `<table>` with `<tr>` and `<td>` to store the individual items. Give each div or row a key and it ...
3,698
53,900,909
Iโ€™m new to python. Why is this code not printing the top50 films? ``` #!/usr/bin/python3 import requests from bs4 import BeautifulSoup import warnings warnings.filterwarnings("ignore", category=UserWarning, module='bs4') # website url = "https://www.imdb.com/search/title?release_date=" year = input("Enter you're fav...
2018/12/23
[ "https://Stackoverflow.com/questions/53900909", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10222187/" ]
You haven't yet issued a request, then you can parse the response content. This should get the full list: ``` r = requests.get(output) soup = BeautifulSoup(r.text, "lxml") # Display the top 50 films movieList = soup.find_all('div', attrs={'class': 'lister-item mode-advanced'}) for n, x in enumerate(movieList, 1): ...
Thanks Guys for the help but i already solved it. ``` i = 1 movieList = soup.find_all('div', attrs={'class': 'lister-item mode-advanced'}) for x in tqdm(movieList): div = x.find('div', attrs={'class': 'lister-item-content'}) # print(str(i) + '.') header = x.findChild('h3', attrs={'class': 'lister-item-he...
3,701
3,413,144
I am using Selenium RC to do some test now. And the driver I use is python. But now, I faced a problem, that is: every time Selenium RC runs, and open a url, it opens 2 windows, one is for logging and the other one is for showing HTML content. But I can't close them all in script. Here is my script: ``` #!/usr/bin/e...
2010/08/05
[ "https://Stackoverflow.com/questions/3413144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/411728/" ]
I've fix this problem. It happens because I installed firefox-bin not firefox. Now I've removed firefox-bin and have installed firefox, it works now. stop() will close all windows that selenium opened. Thank you for your reminds [AutomatedTester](https://stackoverflow.com/users/108827/automatedtester)
I may suggest to make a system command with python to close the firefox windows Bussiere
3,702
11,479,955
I started learning python today from the tutorial on the official site. When reading about **filter(function, sequence)** i thought of making a function that returns if a number is prime to use it with the filter. ``` notDividedBy = [2,3,4,5,6,7,8,9] def prime(num): """True if num is prime, false otherwise""" ...
2012/07/14
[ "https://Stackoverflow.com/questions/11479955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/596298/" ]
Creating many many copies of lists is not a particularly efficient way of doing things. Instead use the `xrange()` (Python 2.x) or `range()` (Python 3) iterator. Here's one (naive) way you could implement a primality test: ``` from math import sqrt def isPrime(n): if n < 2: return False if n == 2: return True...
One thing off the bat, if you are going to implement prime testing in this fashion, there's no reason to use an auxillary array ``` def prime(num): """True if num is prime, false otherwise""" check = True #if num in copy: # copy.remove(num) for x in range(2,x-1): if num % x == 0: ...
3,705
25,204,021
I'm using Continuum's Anaconda Spyder for python. All of a sudden it's giving me this error, although it's supposed to be free: ``` Vendor: Continuum Analytics, Inc. Package: mkl Message: trial mode EXPIRED 14 days ago You cannot run mkl without a license any longer. A license can be purchased it at: http://...
2014/08/08
[ "https://Stackoverflow.com/questions/25204021", "https://Stackoverflow.com", "https://Stackoverflow.com/users/961627/" ]
There is a free trial that starts when you `conda install mkl`. If you want to remove it, use `conda remove --features mkl`.
The MKL optimizations are not free: <https://store.continuum.io/cshop/mkl-optimizations/>. There is a trial period but after that it costs you money. Interesting that you used it for a while. Maybe it's an issue with license checking or there was no mechanism to actually check for a license. When you install the packa...
3,710
26,152,787
i'm just starting to learn python and I need to solve this problem but i'm stuck. We've been given a function (lSegInt)to find the intersections of lines. What I need to do is to format the data properly inorder to pass it through this function too find how many time two polylines intersect. Here's the data: ``` pt1...
2014/10/02
[ "https://Stackoverflow.com/questions/26152787", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4099447/" ]
There are a couple of flaws with your CSS code but the biggest one causing the display issue is: ``` .box2 { float: middle; ``` } There is no `float: middle;` property. You need to either set them all to `float:left;` (or `float:right;`) or use an entirely different approach. (like using `display: table-cell;`)
<http://jsfiddle.net/rishabh66/kLfb2wet/> . Add `float: left;` to all divs to make horizontally align boxes inside parent div.
3,713
40,521,707
Whenever I am trying to perform normalization over the array obtained from the csv file . My code wont work because i have n't provided the custom file. I an getting an error message as : ``` x = np.myarray ``` **AttributeError: 'module' object has no attribute'myarray'** As I am new to python ,can anyone please...
2016/11/10
[ "https://Stackoverflow.com/questions/40521707", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6302830/" ]
The answer is simply, it's the maximum that field can hold. > > MySQL retrieves and displays TIME values in 'HH:MM:SS' format (or > 'HHH:MM:SS' format for large hours values). TIME values may range from > '-838:59:59' to '838:59:59'. The hours part may be so large because > the TIME type can be used not only to re...
You are using **strtotime()** strtotime() - Parse English textual datetimes into Unix timestamps: Eg: ``` echo(strtotime("3 October 2005")); output as 1128312000 ``` **HERE TRY THIS** ``` $epoch_time_out_user =strtotime($_POST['timeout'])- (300*60); $dt = new DateTime("@$epoch_time_out_user"); $time_out_us...
3,715
70,640,586
I have a shred library `libcustum.so` in a non standard folder, and a python package where I use `ctypes.cdll.LoadLibrary("libcustom.so")`. How can I set `libcustum.so` path at build time (something similar to rpath) ? ``` env LD_LIBRARY_PATH=/path/to/custum/lib python3 -c "import mypackage" ``` work fine, but I do...
2022/01/09
[ "https://Stackoverflow.com/questions/70640586", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5940776/" ]
This might be somewhat related to [this question](https://stackoverflow.com/questions/32998502/python-importerror-no-module-named-crypto-publickey-rsa). /e: Ok, since you are using [this firebase package](https://pypi.org/project/firebase/), I can hopefully help you out. First of all, it's the package's fault that it ...
I found a workaround for this. I simply used another module to read from the firebase db. Instead of using `firebase` I used `firebase_admin` as mentioned in the [firebase documentation](https://firebase.google.com/docs/database/admin/start#python). `firebase_admin` doesn't use Crypto so there's no more problem from th...
3,716
66,355,390
I'm trying to make a flask pipeline which receives data from a python file and sends the data to react which display them. I currently am stuck trying to receive the data in flask after sending them via post to the URL: `localhost:5000/weather-data` The data is being posted with this Code: ``` dummy_data = {'data': ...
2021/02/24
[ "https://Stackoverflow.com/questions/66355390", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15275815/" ]
If the files requested are big consider use spawn instead of exec. ``` const http = require('http'); const exec = require('child_process').exec; const DOWNLOAD_DIR = './downloads/'; const generate_width_and_height = function() { const random = Math.floor((Math.random() * 100) + 200); console.log(random); retur...
You can use [Javascript Promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) to download multiple files with node and wget. First wrap your inner code in a promise: ```js const downloadFile = (url) => { return new Promise((resolve) => { console.log(`wget ${ur...
3,717
2,399,812
Is there a way to create a 'kiosk mode' in wxpython under Windows (98 - 7) where the application disables you from breaking out of the app using Windows keys, alt-tab, alt-f4, and ctrl+alt+delete?
2010/03/08
[ "https://Stackoverflow.com/questions/2399812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/204535/" ]
If an application could do that it would make a great denial-of-service attack on the machine. In particular Ctrl+Alt+Delete is the [Secure Attention Sequence](http://technet.microsoft.com/en-us/library/cc780332(WS.10).aspx). Microsoft goes to great lengths to insure that when the user hits those keys, they switch to ...
wxPython alone cannot be done with that. You need to do Low Level Keyboard Hook with C/C++ or with equivalent ctypes, for Windows keys, alt-tab, alt-f4, but Ctrl-Alt-Del, I don't think so for Windows XP and above.
3,718
28,911,296
I want convert nametuple to dict with python: I have: ``` CommentInfo(stt=1, gid=12, uid=222) ``` Now I want: ``` {"stt":1,"gid":12,"uid":222} ``` Please help me! Thanks very much!
2015/03/07
[ "https://Stackoverflow.com/questions/28911296", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3214584/" ]
You need to use `_asdict()` function to convert the named tuples into a dictionary. **Example:** ``` >>> CommentInfo = namedtuple('CommentInfo', ["stt", "gid", "uid"]) >>> x = CommentInfo(stt=1,gid=12,uid=222) >>> x._asdict() OrderedDict([('stt', 1), ('gid', 12), ('uid', 222)]) ```
namedtuples has a `._asdict()` method to convert it to an OrderedDict, so if you have an instance in a variable `comment` you can use `comment._asdict()`
3,719
48,842,401
I'm using python 3.6 and selenium 3.8.1, Chrome browser to simulate users entering an order. The app we use has a particularly frustrating implementation for automation - a loading modal will pop up whenever a filter for a product is loading, but it does not truly cover elements underneath it. Additionally, load time f...
2018/02/17
[ "https://Stackoverflow.com/questions/48842401", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2252481/" ]
If you want to wait until modal disappeared and avoid using `time.sleep()` you can try [ExplicitWait](http://selenium-python.readthedocs.io/waits.html#explicit-waits): ``` from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait as wait wait(driver, 10)....
As you mentioned in your question *a loading modal will pop up whenever a filter for a product is loading* irespective of the loader *cover elements underneath it* or not you can simply `wait` for the next intended element with which you want to interact with. Following this approach you can completely get rid of the f...
3,720
67,499,322
i am trying to control my browser using python, what I need is I give commands in terminal that should work on the browser like opening and searching for something(like scorling the bowser) and closing the browser currently I am done with opening the browser and closing
2021/05/12
[ "https://Stackoverflow.com/questions/67499322", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15904381/" ]
A conflict might occur when both of you are changing the same file in the same branch(or while pulling a different branch to your local branch). In such cases, sometimes git would be able to automatically merge the changes when you try to pull your friend's commit. But if the changes are mostly on the same/nearby lines...
It depends if you are working on the same git branch or not. Even If you are working on the same branch but you modify different files you won't get conflicts. You will only get conflicts if you both change the same file.
3,721
48,028,274
this is the code just to find some sort of product :print the product of all the number in this array Modulo 10^9+7 ``` n=int(input()) answer=1 b=10**9 array_1=[] for i in range(n): array_1.append(int(input())) for j in range(n): ...
2017/12/29
[ "https://Stackoverflow.com/questions/48028274", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7756559/" ]
> > array\_1.append(int(input())) by using this i m trying get an array of int by > taking value one by one from user input โ€“ > > > But it looks like you are entering the numbers one after the other as a single string with each number separated by a space. In that case, you should use split to get the individual...
I'm not completely sure what you are trying to achieve here, but just based on looking at it, your code would not accept any of the inputs after `1 2` If you are running this from a terminal, there should be a new line between each input, i.e. ``` ./your_program.py 4 4 3 2 1 ```
3,722
34,207,898
I am having an issue selecting data from a pandas DataFrame with between\_time. When the start and end dates of the query are between two days the result is empty. I am using pandas 0.17.1 (python 2.7) I have the following data frame: ``` mydf = pd.DataFrame.from_dict({'azi': {Timestamp('2015-05-12 00:00:14.348000'):...
2015/12/10
[ "https://Stackoverflow.com/questions/34207898", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5665206/" ]
From the [documentation](http://search.cpan.org/~peco/Email-Send-SMTP-Gmail-0.1.1/lib/Email/Send/SMTP/Gmail.pm): put commas between the email addresses. > > send(-to=>'', [-subject=>'', -cc=>'', -bcc=>'', -replyto=>'', -body=>'', -attachments=>'']) > > It composes and sends the email in one shot > > > to, cc, ...
Simple add all recipients as a comma separated list: ``` (-to=>'pqr@gmail.com,rec2@gmail.com' ... ```
3,723
66,604,878
I am new to CI/CD and Gitlab. I have a CI/CD script to test, build and deploy and I use 2 branches and 2 EC2. My goal is to have a light and not redundant script to build and deploy my changes in functions of the branch. Currently my script looks like this but after looking the Gitlab doc I saw many conditionals keywor...
2021/03/12
[ "https://Stackoverflow.com/questions/66604878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15306690/" ]
The first is creating an anonymous subclass of `MyRunnable`. The second is creating an anonymous subclass of `Thread`, which requires that `MyRunnable` is instantiable; and `MyRunnable` wouldn't actually then be used at all, because it's not invoked in the `run()` method you're defining in the `Thread` subclass. Ther...
You can also use a lambda expression to start a thread. ``` Thread myRunnableThread3 = new Thread(()-> { System.out.println(Thread.currentThread().getName()); System.out.println("myRunnableThread3!");},"MyThread"); myRunnableThread3.start(); ``` Prints ``` MyThread myRunnableThread3! ```
3,724
20,115,972
I tried to use Ambari to manage the installation and maintenance of the Hadoop cluster. After I started ambari server, I use the web page to set up Hadoop cluster. But at the 3rd step-- confirm hosts, the error shows below And I check the log at /var/log/ambari-server, I found: > > INFO:root:BootStrapping hosts ['...
2013/11/21
[ "https://Stackoverflow.com/questions/20115972", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2951132/" ]
Do you provide ssh rsa private key or paste it? and from the place you are installing, make sure you can ssh to any hosts without typing any password. If still the same error, try ambari-server reset ambari-server setup
Pls restart ambari-server **ambari-server restart** and then try accessing Ambari It would work.
3,725
67,219,194
So recently I've been doing a project whera as optimisation I want to use numpy arrays instead of python list built-in. It would be a 2d array with fixed length in both axes. I also want to maximasie cashe use so that code is as fast as it can be. However when playing with id(var) function I gor unexpected results: co...
2021/04/22
[ "https://Stackoverflow.com/questions/67219194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13757444/" ]
`id(var)` does not work as you think it is. Indeed, `id(var)` returns a unique ID for the specified object `var`, but `var` is not a cell of `a`. **`var` is a Python object referencing a cell of `a`**. Note that `a` does not contains such objets as it would be too inefficient (and data would not be contiguous as reques...
The kinds of arrays that you really want are unclear, nor is the purpose. But talk of contiguous (or continuous) and caching, suggests that you aren't clear about how Python works. First, Python is object oriented, all the way down. Integers, strings, lists are all objects of some class, with associated methods, and a...
3,727
3,312,436
Running GNU Emacs 22.2.1 on Ubuntu 9.04. When editing python code in emacs, if a docstring contains an apostrophe, emacs highlights all following code as a comment, until another apostrophe is used. Really annoying! In other words, if I have a docstring like this: ``` ''' This docstring has an apostrophe ' ''' ``` ...
2010/07/22
[ "https://Stackoverflow.com/questions/3312436", "https://Stackoverflow.com", "https://Stackoverflow.com/users/316963/" ]
This appears to work correctly in GNU Emacs 23.2.1. If it's not practical to upgrade, you might be able to copy `python.el` out of the Emacs 23 source code, or perhaps just the relevant pieces of it (python-quote-syntax, python-font-lock-syntactic-keywords, and the code that uses the latter, I think - I'm not much of a...
It may be an emacs bug, but it could also be by purpose. If you insert doctests in your docstrings, as I often do to explain API, I could even wish to have the full python syntax highlighting inside docstrings. But it's probably a bug... (probably emacs syntax highlighter just care of simple and double quotes and igno...
3,728
48,080,359
I am new to python. I want to find the max value from col2 with respect to the values 'men', 'women' and 'people' in col1 of the list. Like, `['men', 12, '1946-Truman.txt'], ['women', 7, '1946-Truman.txt']`and`['people', 49, '1946-Truman.txt']` contain max values of col2 for men, women and people. One possible solutio...
2018/01/03
[ "https://Stackoverflow.com/questions/48080359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6181928/" ]
You may use `pandas` packages. By defining the data frame : ``` import pandas as pd df = pd.DataFrame([['men', 2, '1945-Truman.txt'], ['women', 2, '1945-Truman.txt'], ['people', 10, '1945-Truman.txt'], ['men', 12, '1946-Truman.txt'], ['women'...
You can use `itertools.groupby`: ``` import itertools new_data = [(a, list(b)) for a, b in itertools.groupby(sorted(data, key=lambda x:x[0]), key=lambda x:x[0])] new_final_data = [max(b, key=lambda x:x[1]) for a, b in new_data] ``` Output: ``` [['men', 12, '1946-Truman.txt'], ['people', 49, '1946-Truman.txt'], ['wo...
3,729
42,776,454
I have multiple series of "start" and "stop" times in a set of data, and would like to see if a particular set of dates/times does or does not fall between a given set of "start/stop" times. I'm using pandas in python, and I've tried having the data as dataframes or as timeseries- haven't gotten either to work. I've be...
2017/03/14
[ "https://Stackoverflow.com/questions/42776454", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7697187/" ]
Put `saveFileDialog1.ShowDialog();` inside some button event handler which lets the user save the document. Double-click on the `SaveFileDialog` icon in your Visual Studio designer window as well to add the FileOk event handler and within event handler, put your code like this: ``` private void saveFileDialog1_Fil...
To do this: ``` private void btn_approve_Click(object sender, EventArgs e) { saveFileDialog1.Title = "Save As"; saveFileDialog1.Filter = "DocX|*.docx"; if (saveFileDialog1.ShowDialog() == DialogResult.OK) { var doc = DocX.Create(saveFileDialog1.FileName); doc.InsertParagraph("This is my first para...
3,739
41,467,654
I have a python script on a machine. I could run it from both **ssh connection** and the **console** of the machine. Because the script changes some IP config stuff, I want to disconnect the ssh before doing the IP changing - that way the ssh won't hang and will be closed properly before the IP changes. **So** - is ...
2017/01/04
[ "https://Stackoverflow.com/questions/41467654", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1662033/" ]
You can add header info as a dict on 4 arguments. As far as know is not possible embed in the BODY. ``` import http.client BODY = "***filecontents***" conn = http.client.HTTPConnection("127.0.0.1", 5000) conn.connect() conn.request("PUT", "/file", BODY, {"someheadername":"someheadervalues", "someothe...
The command: ``` conn.request("PUT", "/file", BODY) ``` Is overloaded as below as well, so its pretty straight forward :) ``` conn.request("PUT", "url", payload, headers) ```
3,740
57,717,100
By "comparable", I mean "able to mutually perform the comparison operations `>`, `<`, `>=`, `<=`, `==`, and `!=` without raising a `TypeError`". There are a number of different classes for which this property does hold: ```py 1 < 2.5 # int and float 2 < decimal.Decimal(4) # int and Decimal "alice" < "bob" # str and...
2019/08/29
[ "https://Stackoverflow.com/questions/57717100", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2648811/" ]
Since it is impossible to know beforehand whether a comparison operation can be performed on two specific types of operands until you actually perform such an operation, the closest thing you can do to achieving the desired behavior of avoiding having to catch a `TypeError` is to cache the known combinations of the ope...
What you could do is use `isinstance` before the comparison, and deal with the exceptions yourself. ``` if(isinstance(date_1,datetime) != isinstance(date_2,datetime)): #deal with the exception ```
3,741