Unnamed: 0
int64
0
1.91M
id
int64
337
73.8M
title
stringlengths
10
150
question
stringlengths
21
64.2k
answer
stringlengths
19
59.4k
tags
stringlengths
5
112
score
int64
-10
17.3k
400
67,800,199
auth_registrations_mapping error: could not create while pip install twilio on cmd with admin access
<p>Note: Most of the solutions to similar problem suggest that, I retry on CMD admin access. I have tried and still it wont install and returns similar error.</p> <pre><code>SoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\twilio\rest\api\v2010\account\sip\domain\auth_types\a...
<p>Twilio developer evangelist here.</p> <p>I believe you have hit the <a href="https://stackoverflow.com/questions/1880321/why-does-the-260-character-path-length-limit-exist-in-windows">Windows path length limit of 260 characters</a>, which is why this file is failing. You can enable longer paths by <a href="https://d...
python|twilio
0
401
67,049,153
How can i compare two DateTimeFields with current time
<p>Event has two DateTimeField's and i need to compare them to the actual date time in a same method.</p> <pre><code>from django.utils import timezone event_starts = models.DateTimeField(_(&quot;Event starts&quot;)) registration_closes_at = models.DateTimeField( _(&quot;Registration ends:&quot;), null=True, bl...
<p>Notice that <code>registration_closes_at</code> field is nullable, therefore you need to handle that case in the condition.</p> <p>My guess is that you would like to ignore the <code>registration_closes_at</code> when it is null, so the condition would look like:</p> <pre><code>def is_registration_open(self): if...
python|django|datetime|django-models
0
402
42,810,374
How to output nothing
<p>Hi I wrote a program which tells me if there is or not hexadecimals in the input.</p> <pre><code>hexadecimal = ['0','1','2','3','4','5','6','7','8','9','a','A','b','B','c','C','d','D','e','E','f','F'] output = '' for c in hexadecimal: digit = input('Digit: ') output += c.join(digit) if digit == '': print(...
<p>Use another if statement before appending it to <code>output</code>:</p> <pre><code>if len(output) == 0 and len(digit) == 0: print("input is blank") </code></pre> <p>This checks that the user hasn't previously entered anything and hasn't currently entered anything, if both are true then tell them the input is ...
python
1
403
72,456,647
Django Login with Email or Phone Number
<p>I have been trying to find a solution of a problem in Django for a very long time. The problem is I am trying to develop a login system than can use either email or phone number to authenticate user.</p>
<p>Well, that can be done using by creating a custom user model . I have tested this. It works.</p> <p>First steps</p> <p>The first thing you need to do is create a new Django project. Make sure you don't run migrations because there are still a few things we need to do before then.</p> <p>After creating your new Djang...
python|django|authentication|django-models|django-rest-framework
1
404
65,557,065
Multi Layer Perceptron Deep Learning in Python using Pytorch
<p>I am having errors in executing the train function of my code in MLP.</p> <p>This is the error:</p> <p>mat1 and mat2 shapes cannot be multiplied (128x10 and 48x10)</p> <p>My code for the train function is this:</p> <pre><code>class net(nn.Module): def __init__(self, input_dim2, hidden_dim2, output_dim2): super(n...
<p>From the limited message, I guess the place you are wrong are the following snippets:</p> <pre><code>x = self.fc3(x) x = F.softmax(self.fc3(x)) </code></pre> <p>Try to replace with:</p> <pre><code>x = self.fc3(x) x = F.softmax(x) </code></pre> <hr /> <p>A good question should include: error backtrace information a...
python|pytorch|perceptron|mlp
2
405
50,803,021
Read Excel with multiple headers and unnamed column
<p>I recieve some Excel files like that :</p> <pre><code> USA UK plane cars plane cars 2016 2 7 1 3 # a comment after the last country 2017 3 1 8 4 </code></pre> <p>There is an unknown amount of countries and there can be a comment after the...
<p>It's possible Pandas won't be able to fix your special use case, but you can write a program that fixes the spreadsheet using <a href="https://openpyxl.readthedocs.io/en/stable/" rel="nofollow noreferrer">openpyxl</a>. It has really clear documentation, but here's an overview of how to use it:</p> <pre><code>import...
python|pandas
0
406
50,573,104
Convert numpy rows into columns based on ID
<p>Suppose I have a <code>numpy</code> array that maps between IDs of two item types:</p> <pre><code>[[1, 12], [1, 13], [1, 14], [2, 13], [2, 14], [3, 11]] </code></pre> <p>I would like to rearrange this array such that each row in the new array represents all items that matched the same ID in the original array...
<p>Here is a general and mostly Numpythonic approach:</p> <pre><code>In [144]: def array_packer(arr): ...: cols = arr.shape[1] ...: ids = arr[:, 0] ...: inds = np.where(np.diff(ids) != 0)[0] + 1 ...: sp = np.split(arr[:,1:], inds) ...: result = [np.unique(a[: cols]) if a.sh...
python|arrays|numpy|scipy
3
407
26,445,122
Errors loading JSON with Flask and Angular
<p>I've solved my issue, but I'd like to know what was going wrong so I can address it in the future. I'm having issues decoding incoming JSON for use in my Flask application.</p> <p><strong>The code that sends it in Angular:</strong></p> <pre><code>$http.post("/login", JSON.stringify($scope.loginForm)) .success(fu...
<p>You can omit <code>JSON.stringify</code> and pass object directly to <code>$http.post()</code> method because angular will serialize it to JSON automatically it <code>formData</code> is object. So I assume that <code>JSON.stringify</code> will force angular to send is as <code>x-www-form-urlencoded</code> instead of...
python|json|angularjs|flask
0
408
26,897,922
Accessing python generators in parallel using multiprocessing module
<p>I have a Python generator which pulls in a pretty huge table from a data warehouse. After pulling in the data, I am processing the data using celery in a distributed manner. After testing I realized the the generator is the bottleneck. It can't produce enough tasks for celery workers to work on. This is when I have ...
<p>I think you may be trying to solve this problem at the wrong level of abstraction. Python generators are inherently stateful, and thus you can't split a generator across processes without some form of synchronization, and that will kill any performance gains that you might achieve through parallelism. I would recomm...
python|parallel-processing|generator
8
409
45,066,842
How do you pass a generated PDF to an API as an IO stream without writing it to disk?
<p>I am using PyPDF2 to generate a PDF, and I would like to upload this PDF to <a href="http://cloudinary.com/documentation/" rel="nofollow noreferrer">Cloudinary</a>, which accepts images as IO objects.</p> <p>The example from their docs: <code>cloudinary.uploader.upload(open('/tmp/image1.jpg', 'rb'))</code></p> <p>In...
<p>Got the answer from Cloudinary support:</p> <p>The result from getvalue() on the StringIO object needs to be base64 encoded and prepended with a tag: </p> <pre><code>out = StringIO.StringIO() output.write(out) cloudinary.uploader.upload("data:image/pdf;base64," + base64.b64encode(out.ge...
python|pdf|io|pdf-generation|cloudinary
0
410
44,944,208
What does DeprecationWarning mean when running Python
<p>I ran a Python program and got a <code>DeprecationWarning</code>, like:</p> <pre><code>D:\programs\anaconda2\lib\site-packages\sklearn\utils\deprecation.py:70: DeprecationWarning: Function log_multivariate_normal_density is deprecated; The function log_multivariate_normal_density is deprecated in 0.18 and will be r...
<p>In general developers are developing libraries and in developing sometime add o change thing and sometime remove theme. removing is danger because user may used that and if a developer want to remove a thing first have to notify others to don't use this feature or things and after this he can remove. and Deprecation...
python|deprecation-warning
6
411
64,955,136
I have a ModuleNotFoundError: No module named 'Crypto'
<p>Please need help</p> <p>When I try to run myfile.py it says, ModuleNotFoundError: No module named 'Crypto' ,but I already have the path for 'conda' and 'anaconda3' in my environment variables, I also have uninstalled and reinstalled pycryptodome yet it still says ModuleNotFoundError: No module named 'Crypto'.</p> <b...
<p>Your package list seems to be missing the required library (<code>pyCrypto</code>).</p> <p>Not too familiar with conda, but try:</p> <pre><code>$ conda install pyCrypto </code></pre> <p>Here is an example with just python:</p> <pre><code>root@47cbabc35dca:/# python Python 3.9.0 (default, Nov 18 2020, 13:28:38) [GCC ...
python
0
412
64,808,992
How to harness for loop with functionality of multiple buttons
<p>I am stuck with code below. Either I cannot find simple answer to my problem due to not narrow enough search or I am just too blind to see. Anyway I am looking to put the &quot;+&quot; and &quot;-&quot; buttons to use. They suppose to literally do what their assigned symbols do. With my level of python knowledge I c...
<p>Since you are only using 2 buttons for this, I think having 2 functions won't be too bad. However, if you would have more than 2 buttons, I think a lambda function would be good. I'm not sure what your code is trying to accomplish here but my best guess is that you are trying to add and subtract numbers? I made a ca...
python|user-interface|tkinter
0
413
61,318,824
Kivy Widgets doesn't shows up
<p>Im getting a strange error. I can only see <strong>black window</strong> without text label. I've also tried many other widgets and gets the same bug!</p> <p>It came up after I fixed - <strong>Kivy does not detect OpenGL 2.0</strong> by setting environmental variable KIVY_GL_BACKEND = angle_sdl2</p> <p>I even tried ...
<p>instead of OpenGL, use sdl2</p> <pre><code>import os os.environ['KIVY_TEXT'] = 'sdl2' os.environ['KIVY_IMAGE'] = 'sdl2' </code></pre>
python|python-3.x|opengl|kivy
0
414
60,368,528
How could I store lambda functions inside a dictionary in python?
<p><a href="https://editor.p5js.org/cbrwn/sketches/xKE8rHPL" rel="nofollow noreferrer">Someone</a> shared their code and I saw a bunch of functions that were stored in what seemed to me to be a dictionary and. So, I liked the idea and I <em>borrowed</em> them. The code that the person wrote it in was in JS, and I work ...
<p>As you mentioned in the comments that you still can't figure out how to do it using string keys for dictionary, I'm posting this answer. Though, it was partially mentioned in the comments how to do this.</p> <pre><code>a = { 'linear': lambda t: t, 'easeInQuad': lambda t: t ** 2, 'easeOutQuad': lambda t:...
javascript|python|lambda|conditional-operator
1
415
57,982,794
Using a function define var and then passing to a constructor
<p>I want client code to call a function, that assigns user inputted values to variables and pass them to an object to be used as user defined attributes.</p> <p>But I'm not able to call any methods for the object</p> <p>I've tried including the methods for the object in the function, but it doesn't seem to change an...
<pre><code>def function(): a = input("blahblah") return foo(a) class foo(object): def __init__(object): self.a = object print(self.a) def DoThing(): print(self.a) #Main the_object = function() the_object.DoThing() </code></pre> <p>or</p> <pre><code>class foo(object): de...
python|function|oop|object|nameerror
0
416
58,147,257
Find diagonal without cycle or diagonal
<p>I was trying to find the diagonal of matrix <code>b</code> without using cycle or diag. I got an error: <code>'numpy.ndarray' object has no attribute 'index'</code>. Not sure how to fix this.</p> <pre><code>b = np.random.randint(low = 1, high = 11, size = (10,10)) print(list(map(lambda x: x[a.index(x)], a))) </cod...
<p>The numpy ndarray object doesn't behave exactly like a python list, specifically, as the error specifies, it does not have an 'index' function. Here is one way to go around this:</p> <p>You can first convert b from a numpy ndarray to a standard python list, in the following way:</p> <pre><code>b = b.tolist() </cod...
python|numpy|diagonal|index-error
1
417
69,472,736
Python how to make datetime update time
<p>Im using datetime with pytz, but i cant get time to update.</p> <pre><code>format = &quot;[%B %d %H:%M]&quot; now_utc = datetime.now(timezone('UTC')) greece = now_utc.astimezone(timezone('Europe/Athens')) date = greece.strftime(format) </code></pre> <p>For example i print(date) at 11:30, it stays like that. Any idea...
<p>As it is, <code>date</code> remains the same throughout the runtime. There is nothing to update it at the current time. If you want to check and print the time at regular intervals, you need to define a function and have your script call it after that amount of time.</p> <pre><code>import time fmt = &quot;[%B %d %H:...
python|datetime|pytz
0
418
55,513,923
Understanding module & absolute / relative package imports
<p>I have created a package containing sub-folders and I would like <strong>to include a parent module from a sub-package module</strong>. </p> <p>I have tried to follow the project structure suggested here <a href="https://docs.python-guide.org/writing/structure/" rel="nofollow noreferrer">https://docs.python-guide.o...
<p>Every import will be relative to the location where the script is being run, in your case, main.py. </p> <p>So, the point of view of your program is:</p> <pre><code>-logger.py -__init__.py -db/ ---__init__.pt ---EntryPoint.py </code></pre> <p>The program is not aware that he is an module called watches, so if you...
python|python-3.x
0
419
42,190,249
How to 'save as' an edited image (png) using a file dialog in tkinter and Pil in Python
<p>I am trying to create an image editor that adds text to an image using pillow. My problem is with saving my edited image so that the user can choose the name of the save file by opening up a save-as dialog. Looking at other questions and answers, I came up with this:</p> <pre><code>def onOpen(self): im = Im...
<p>You should save the image through the save method that in Image object:</p> <pre><code>file = filedialog.asksaveasfile(mode='w', defaultextension=".png") if file: im.save(file) # saves the image to the input file name. </code></pre>
python|image|tkinter|pillow
3
420
42,371,500
Find one line and get the next lines
<p>With this code I get the full line which includes <code>Name</code>. But I need to get this line AND the next 2 lines. I have no clue how I can do this.</p> <pre><code>def daten(s): for i in s: if i.find('Name') &gt;= 1: daten = i return daten </code></pre> <p>Example:</p> <pre...
<p>This is another solution - if <code>s</code> is a file:</p> <pre><code>def daten(s): with open(s, 'r') as f: lines = f.read().splitlines() for i,line in enumerate(lines): if 'Name' in line: return lines[i:i+3] </code></pre> <p>It searches for the word 'Name' in any of the lines and if find it - re...
python|find|return|line|next
1
421
54,120,789
Determining whether a Pandas df column is an array
<p>I want to see if a column in my dataframe is an actual <code>list</code> type in python. Here is what I'm currently doing:</p> <pre><code>is_list_field = all([isinstance(_val, list) for _val in df.iloc[:,1] if _val]) </code></pre> <p>Does the above seem like it covers all scenarios (nan? empty string, null, etc.),...
<p>Not fast but at least work </p> <pre><code>df.applymap(lambda x : type(x)==list).all() A False B True dtype: bool </code></pre> <p>Data Input</p> <pre><code>df=pd.DataFrame({'A':[1,2],'B':[[1,2],[1,2]]}) </code></pre>
python|pandas
1
422
58,270,645
How to check if given data exist or Not in mongodb and python
<p>I used below code.</p> <pre><code>from pymongo import MongoClient client=MongoClient() db=client.mydb if db.mycollections.find({"name": 'Chinna',"password":'chinna11'}).count() &gt; 0: print("true") else: print("false") </code></pre> <p>but it return below an error,</p> <pre><code>DeprecationWarning: cou...
<p>Assuming you're not interested in the documents and only what to count the matching ones, replace .find() with .count_documents():</p> <pre><code>from pymongo import MongoClient client=MongoClient() db=client.mydb if db.mycollections.count_documents({"name": 'Chinna',"password":'chinna11'}) &gt; 0: print("true...
python|mongodb
0
423
58,522,777
Generating matches for 5th, 7th, 9th etc. Places
<p>I have a method that generates matches for each best of two teams from group stage. </p> <pre><code>Group A T1───┐ │ T2───┘ ├───┐ T3───┐ │ ├───T1 │ │ │ T4───┘ │ ├───T6 Group B ├───│ T5───┐ │ ├───T2 │ │ │ T6───┘ │ ├───T5 ├───┘ T7───┐ │ T8───┘ </code></pre> <hr>...
<p>You can use recursion to get the desired result in case of <strong>N</strong>-teams¹ in <strong>M</strong>-groups²:</p> <pre><code>def playoff2g(g1, g2, r): """ Get matches for 2 groups """ if len(g1) &gt; 1: r.extend([(g1[0], g2[1]), (g2[0], g1[1])]) playoff2g(g1[2:], g2[2:], r) elif le...
python|python-3.x|tournament
0
424
65,070,648
Python: How to slice string using string?
<p>Assuming that the user entered:</p> <pre><code>&quot;i like eating big apples&quot; </code></pre> <p>Want to remove &quot;eating&quot; and &quot;apples&quot; together with whatever is in between these two words. Output in this case</p> <pre><code>&quot;i like&quot; </code></pre> <p>In another case, if the user enter...
<p>You can do the follwoing:</p> <pre><code>s = &quot;i like eating big apples&quot; start_ = s.find(&quot;eating&quot;) end_ = s.find(&quot;apples&quot;) + len(&quot;apples&quot;) s[start_:end_] # 'eating big apples' </code></pre> <p>Using <code>find()</code> to find the starting indices of the desired word in the st...
python|string|input|indexing|slice
1
425
65,460,083
How do i get the innermost item inside a dictionary in python
<p>I loaded a file into a dictionary in python. Suppose it look something like this:</p> <pre><code>{'dictionary': {'a': {'second_level': {'data': 'hello'}}, 'b': {'another_level': {'this_one_has_three_levels': {'data': 'hi'}}}}} </code></pre> <p>Assuming that i don't know any of the keys except for the...
<p>A recursive approach is usually the simplest if nesting depth is not known in advance. Here is an example with a generator function:</p> <pre><code>def get_data(dct, key): if key in dct: yield f&quot;{key}&gt;{dct[key]}&quot; for k, v in dct.items(): if isinstance(v, dict): for s ...
python|json|loops|dictionary|yaml
0
426
28,487,338
Replace specific words in python
<p>If I have a string "this is", and I want to replace "is" to "was". When I use <code>replace ("is", "was")</code>, I got "thwas was", but what i am expecting is "this was", is there any solution?</p>
<p>You need to do something more sophisticated than a regular string replace. I'd suggest using Regular Expressions (<a href="https://docs.python.org/2/library/re.html" rel="nofollow">the <code>re</code> module</a>), and using the <code>\b</code> escape sequence to match <em>word boundaries</em>:</p> <pre><code>import...
python|replace
6
427
28,502,597
Effective closures in python
<p>With Python 2.7x I'm attempting to create a Map object which can reference itself with a 'This' or 'self'. In Javascript this would be roughly, </p> <pre><code>myObj = function(){ obj = {}; this = obj; obj = { 'a':'b', 'b':this.a }; return obj; }() </code></pre> <p>But in Python you can't do multi-line lamb...
<p>If you're trying to implement a closure with a map, this would work fine</p> <pre><code>mymap = {a:1,b:"foo"} # all of your previously initialized and constant data mymap["self"] = mymap </code></pre> <p>Then you can call</p> <pre><code>mymap["self"]["b"] </code></pre> <p>Here's how you can write code using this...
python|python-2.7
2
428
14,411,261
Writing a p2p client/server app
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/3275004/how-to-write-a-twisted-server-that-is-also-a-client">How to write a twisted server that is also a client?</a> </p> </blockquote> <p>How can I create a tcp client server app with twisted, where also the ...
<p>The question you have to ask yourself is: why is the server sending a request?</p> <p>Presumably something has happened in the world that would prompt the server to send a request; it wouldn't just do it at random. Even if it did it at random, the thing that has happened in the world would be "some random amount o...
python|twisted
1
429
14,492,641
MongoAlchemy embedded documents
<p>Does anyone know how to create a model with an embedded document with mongo alchemy? I've search in the documentation, but there isn't any example about doing that.</p>
<p>have a look at:</p> <p><a href="https://github.com/jeffjenkins/MongoAlchemy/blob/master/examples/examples.py" rel="nofollow">https://github.com/jeffjenkins/MongoAlchemy/blob/master/examples/examples.py</a></p> <p>Theres a sample there, but for completeness, yes MongoAlchemy can use embedded documents like this:</p...
python|flask|mongoalchemy
3
430
68,621,974
Issue with the Python any() function
<p>I am trying to convert a list of lists into a single list with '1's if <strong>any</strong> of the elements in a single list is 1 and 0 otherwise. I have the following list:</p> <pre><code>result =[[-1, -1, 0], [1, 0, -1], [1, 1, 0]] </code></pre> <p>and if I use <code>any()</code> on the first list</p> <p>i.e. <cod...
<p><code>any</code> tests if any value is truthy, not if any value equals <code>True</code>. All non-zero integers are truthy so <code>any([-1, -1, 0])</code> is <code>True</code>.</p> <p>See for details <a href="https://docs.python.org/3/library/stdtypes.html#truth-value-testing" rel="nofollow noreferrer">Truth Value...
python|list|any
1
431
6,508,963
Text display with matplotlib
<p>I'm having a problem with the <code>plt.text()</code> method in matplotlib and I am hoping someone can help me. Below is a basic linear regression example where I would like to display some text (slope = ) and the actual slope of the line on the graph:</p> <pre><code>import csv import scipy as sp import scipy.stats...
<pre><code>str='slope'+str(slope) plt.text(2, 30, str, fontsize=15) </code></pre> <p>or just <code>plt.text(2, 30, r'slope='+str(slope), fontsize=15)</code></p>
python|numpy|matplotlib|scipy
4
432
6,766,447
Help with passing variables w/ csrfContext
<p>I have a login page, and in my view I pass it the csrfContext variable for the csrf_token tag. However, problems arise when I try to pass more than just that variable into the context. For example, if I use locals()</p> <pre><code>return render_to_response('base_index.html', locals()) </code></pre> <p>I get a csrf...
<p>I would not recommend using locals() in this way. In more complex views you may end up passing much more to the template rendering that is required.</p> <p>A better way to do this is to create the RequestContext, and either pass in the values you want to add, or add them after: <a href="https://docs.djangoproject.c...
python|django|csrf
0
433
6,710,676
Python: Waiting for a file to reach a size limit in a CPU friendly manner
<p>I am monitoring a file in Python and triggering an action when it reaches a certain size. Right now I am sleeping and polling but I'm sure there is a more elegant way to do this:</p> <pre><code>POLLING_PERIOD = 10 SIZE_LIMIT = 1 * 1024 * 1024 while True: sleep(POLLING_PERIOD) if stat(file).st_size &gt;= SIZ...
<p><strong>Linux Solution</strong></p> <p>You want to look at using <a href="http://pyinotify.sourceforge.net/" rel="nofollow">pyinotify</a> it is a Python binding for <a href="http://en.wikipedia.org/wiki/Inotify" rel="nofollow">inotify</a>.</p> <p>Here is an example on watching for <code>close</code> events, it isn...
python|multithreading|sleep|polling
4
434
56,950,411
Duplicate every value in array as a new array
<p>I have an numpy ndarray input like this</p> <pre><code>[[T, T, T, F], [F, F, T, F]] </code></pre> <p>and I want to duplicate every value as a new array, so the output would be</p> <pre><code>[[[T,T], [T,T], [T,T], [F,F]] [[F,F], [F,F], [T,T], [F,F]]] </code></pre> <p>How can I do this? Thank you in advance</...
<p>One way would be using <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.dstack.html" rel="nofollow noreferrer"><code>np.dstack</code></a> to replicate the array along the third axis:</p> <pre><code>np.dstack([a, a]) array([[['T', 'T'], ['T', 'T'], ['T', 'T'], ['F', 'F']],...
python|numpy|numpy-ndarray
4
435
25,777,060
How do I call a python script on the command line like I would call a common shell command, such as cp?
<p>Suppose I've got a script I can run with:</p> <pre><code>python hello_world.py &gt;&gt;&gt; "Hello, world!" </code></pre> <p>How can I configure hello_world.py to be executable <strong>without</strong> <code>'python'</code> or <code>'./'</code>:</p> <pre><code>hello_world &gt;&gt;&gt; "Hello, word!" </code></pre>...
<p>If you're on Linux or Unix, at the top your file, it's typically something like </p> <pre><code>#!/bin/python </code></pre> <p>or </p> <pre><code>#!/usr/bin/python </code></pre> <p>You'll need execution perms to run the file as well, in that manner. Use chmod</p> <pre><code>chmod +x hello_world.py </code></pre>...
python|linux|shell|terminal
4
436
20,689,760
Tkinter, canvas, create_text and zooming
<p>Is it normal that Tkinter's Canvas' <code>create_text</code> 's font size doesn't change when I change the Canvas' scale with <code>canvas.scale</code> ?</p> <p>I thought that, as it is a high level GUI management system, I wouldn't have to resize manually the text done with <code>create_text</code> after a zooming...
<p>It's normal, even if not entirely what you want. The <code>scale</code> method just changes the coordinate lists, but <code>text</code> items only have one of those so they just get (optionally) translated.</p> <p>This also applies to <code>image</code> and <code>bitmap</code> items. And features of other items lik...
python|user-interface|canvas|tkinter|tcl
1
437
72,004,640
How can the x-axis dates be formatted without hh:mm:ss using matplotlib DateFormatter?
<p>I am pulling in data on Japanese GDP and graphing a stacked barchart overlayed with a line. I would like for the x-axis to have only yyyy-mm and no timestamp. I read about a compatability issue with pandas and matplotlib epochs. Is that the issue here? When I try to use matplotlib Dateformatter, the returned dates b...
<p>Don't use <code>DateFormatter</code> as it is causing trouble, rather change format of the dataframe index using <code>df.index = pd.to_datetime(df.index, format = '%m/%d/%Y').strftime('%Y-%m')</code></p> <p>Here is what I did with your gdp.csv file</p> <pre><code>import matplotlib.pyplot as plt import pandas as pd...
pandas|matplotlib
0
438
71,891,143
How to not overwrite a value of a dictionary when taking and storing a user's input? (Python)
<p>I'm a python beginner tried making a contact book/address book program. I take a user input/contact info(value) and store it as a value to a dictionary, however while the program still running if I try to enter a new contact info(new value) it will overwrite the existing one, how do I solve this? so I can add as man...
<p>I think your problem is that every time your user press 1 to input a new contact your code goes like this:</p> <pre class="lang-py prettyprint-override"><code>print(&quot;\nAdding a new contact!&quot;) global cnt_lst global new cnt_lst = {} # &lt;- here you are erasing your dicti...
python|dictionary
2
439
15,108,618
Parallel Document Conversion ODT > PDF Libreoffice
<p>I am converting hundreds of ODT files to PDF files, and it takes a long time doing one after the other. I have a CPU with multiple cores. Is it possible to use bash or python to write a script to do these in parallel? Is there a way to parallelize (not sure if I'm using the right word) batch document conversion usin...
<p>You can run libreoffice as a daemon/service. Please check the following link, maybe it helps you too: <a href="http://www.linuxquestions.org/questions/blog/sag47-492023/headless-file-conversion-using-libreoffice-as-a-service-35310/" rel="nofollow" title="Useful link">Daemonize the LibreOffice service</a></p> <p>Oth...
python|bash|libreoffice
4
440
29,744,407
PyDev can't recognize all module members correctly
<p>I have two examples:</p> <p><img src="https://i.stack.imgur.com/LdsqH.png" alt="enter image description here"></p> <p>As you can see PyDev marks Process in first example and PULL in second as "Undefined variable from import (...)". <strong>However, code is executed without any problems. It's just PyDev can't resol...
<p>Yes, you can ask PyDev to analyze modules through a shell.</p> <p>See: <a href="http://pydev.org/manual_101_interpreter.html" rel="nofollow">http://pydev.org/manual_101_interpreter.html</a> for more details (mostly the forced builtins part).</p>
python-3.x|ide|pydev
2
441
29,350,463
Jinja2 does not render blocks
<p>I am going through a flask tutorial and want to create a blog using flask. For this purpose I took some code from the tutorial and wrote some code myself. The problem is, that the Jinja2 templating engine only seems to render some of the blocks I declared in the templates and I don't know why.</p> <p>This is what I...
<p>You are implementing each block in a different html file, but you render <code>index.html</code>. What Jinja2 does when you tell it to render <code>index.html</code> is grab the base template (<code>base.html</code>) and look at what modification <code>index.html</code> brings - in your case, updating the <code>cont...
python|flask|jinja2|html-rendering
8
442
21,395,463
How can I update a plot with periodic information coming through a serial port (every ~100-200 msec)? Do I need an RTOS?
<p>I'm sending positioning information (x,y,z coordinates in double data type) from a microcontroller via a Serial Communication Interface (SCI). I would like to use a program to receive this information and update this coordinate every time I receive a new coordinate, preferably in Python. </p> <p>What is a good libr...
<p>No, an RTOS is not necessary. Any modern system should very easily be able to handle reading serial data every 100ms.</p> <p>Just get started reading from the serial port, and processing your data.</p> <ul> <li><a href="http://pyserial.sourceforge.net/" rel="nofollow">pySerial</a></li> </ul>
python|plot|serial-port|embedded|microcontroller
2
443
62,780,414
Unable to replicate gdal output
<p>I have a set of GRIB files that are fliped (longitude spans from 0 to 365), and I am using <code>gdal</code> to first transform the data to GeoTIFF, and then warp the gridded data to a standard WGS84 longitude (-180 to 180). So far, I have been using a combination of <code>gdal_translate</code> and <code>gdalwarp</...
<ul> <li>First option, get GDAL 3.4 where this problem is solved, GRIBs get automagically transformed from 0-360 to -180-180 when being converted from GRIB to GeoTIFF</li> <li>Second option, use <code>geosub</code> available from NPM (<code>npm -g install geosub</code>) to download NOAA's GRIBs if this is what you are ...
python|geospatial|gdal|osgeo
1
444
62,603,957
An optimized matrix multiplication library in Python (similar to Matlab) but is NOT numpy
<p>According to the NumPy <a href="https://numpy.org/doc/1.18/reference/generated/numpy.matrix.html" rel="nofollow noreferrer">documentation</a> they may deprecate their <code>np.matrix</code> class. And while arrays do have their multitude of use cases, they cannot do everything. Specifically, they will &quot;break&qu...
<p>Actually, <code>numpy</code> offers BLAS-powered matrix mutiplication through the <code>matmul</code> operator <code>@</code>. This invokes the <code>__matmul__</code> magic method for a given class.</p> <p>All you have to do in the above example is <code>W @ x</code>.</p> <p>Other linear algebra stuff can be found ...
python|matlab|numpy|matrix
1
445
70,040,998
How to transform output of neural network and still train?
<p>I have a neural network which outputs <code>output</code>. I want to transform <code>output</code> before the loss and backpropogation happen.</p> <p>Here is my general code:</p> <pre><code>with torch.set_grad_enabled(training): outputs = net(x_batch[:, 0], x_batch[:, 1]) # the prediction of the NN...
<p>The error is quite correct about what the issue is - when you create a new tensor with <code>requires_grad = True</code>, you create a leaf node in the graph (just like parameters of a model) and not allowed to do in-place operation on it.</p> <p>The solution is simple, you do not need to create the <code>new_tensor...
python|deep-learning|neural-network|pytorch|backpropagation
2
446
70,144,604
Return specific functions of a class from another function
<p>I have 2 classes, A and B</p> <pre class="lang-py prettyprint-override"><code>class A: def name(self): return B(name=self) class B: def __init__(self, name): self.name = name def hi(self): return &quot;Hi!&quot; + self.name def bye(self): return &quot;Bye!&quot; +...
<p>That would contradict Python's typing system.</p> <p>In statically typed languages, not only does a data object in the memory has a type, but also the variable which references it, and the two types do not have to be identical (though they have to match). The class members accessible through the referencing variable...
python|oop
0
447
70,366,082
Scrapy crawler: Unable to store multiple urls into postgres
<p>I have created a crawler using scrapy python.I want to store multiple urls fetched by the crawler into the postgres table.When i start the crawler the urls are fetched and table gets created into the postgres but the data is not getting stored.</p> <p><strong>Technology used:</strong> Scrapy,Python</p> <p><strong>Ou...
<p>You can use <code>scrapy</code> <code>ITEM_PIPELINES</code> to achieve this. See sample implementation below</p> <pre class="lang-py prettyprint-override"><code>import scrapy import psycopg2 class DBPipeline(object): def open_spider(self, spider): # connect to database try: self.conn...
python|postgresql|scrapy
1
448
53,651,984
How to get the first item in a group by that meets a certain condition in pandas?
<p>I have the following code:</p> <pre><code>grouped_stats = stats.groupby( stats.last_mv.ne( stats.last_mv.shift()).cumsum() ) </code></pre> <p>last_mv is a decimal value In the code above I am grouping by consecutive values</p> <p>I am trying two ways to obtain the first value that is 0.25% above the first item in...
<p>I believe you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.transform.html" rel="nofollow noreferrer"><code>transform</code></a> for <code>Series</code> with same size like original <code>DataFrame</code> filled by first values per groups:</p> <pre><code>stats[ stat...
python|python-3.x|pandas
2
449
53,399,765
How can I replace a substring in a Python pathlib.Path?
<p>Is there an easy way to replace a substring within a <code>pathlib.Path</code> object in Python? The <a href="https://realpython.com/python-pathlib/" rel="noreferrer">pathlib module is nicer in many ways</a> than storing a path as a <code>str</code> and using <code>os.path</code>, <code>glob.glob</code> etc, which a...
<p>You are correct. To replace old with new in Path p, you need:</p> <pre><code>p = Path(str(p).replace(old, new)) </code></pre> <hr /> <p>EDIT</p> <p>We turn Path p into str so we get this str method:</p> <blockquote> <p>Help on method_descriptor:</p> <p>replace(self, old, new, count=-1, /)</p> <p>Return a copy with a...
python|python-3.x|pathlib
37
450
45,833,188
how to merge array of images which are generated by for loop
<p>I have a set of 5 images and I must resize them all in (16,16) dimension. Then, I have to print each image as a column vector.</p> <p>For this, I use a <code>for</code> loop to resize all the images but I can't merge them in an array. What should I do if I want to print 5 column matrix of 5 images side by side as a...
<p>Try appending all images to an array then join them using <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.concatenate.html" rel="nofollow noreferrer">np.concatenate(.., axis=1)</a>. For example, change as follows: </p> <pre><code>imgs = [] for i in files: abc=cv2.imread(i,0) d=(16,16) ...
python|python-3.x
0
451
54,943,382
Google speech recognition API credentials error
<p>I am trying to integrate a the google speech recognition API, but i keel getting an error saying ApplicationDefaultCredentialsError. I've been searching and I keep seeing something like : <code>set GOOGLE_APPLICATION_CREDENTIALS=[PATH]</code>, but I don't know where actually to type that in the terminal and where to...
<p>You will need to export the credentials to the environment. </p> <p>For mac -</p> <pre><code>export GOOGLE_APPLICATION_CREDENTIALS="[PATH]" </code></pre> <p>For Windows via PowerShell-</p> <pre><code>$env:GOOGLE_APPLICATION_CREDENTIALS="C:\Users\username\Downloads\[FILE_NAME].json" </code></pre> <p>Where <code>...
python
0
452
33,439,843
Importing libraries in Python
<p>I'm new to Python, so this question might be easy. But I tried to search on the internet and didn't reach an explanation.</p> <p>I'm trying to imitate a simple script dealing with xml where it imports the following</p> <pre><code>from xml.etree import ElementTree from xml.etree.ElementTree import Element from xml....
<p>You should be able to do:</p> <pre><code>from xml.etree.ElementTree import * </code></pre> <p>However, this is bad form since you could have conflicting names from different package imports. It's always best to specify the exact classes you want and alias them as needed--class name like <code>Element</code> one ...
python|xml|python-2.7
0
453
40,909,274
Read and parse a tab delimited file PHP
<p>I worked out this Python script to read a tab delimited file and place the values where the line starts with <code>'\t'</code> in a <code>array</code>. The code which I used for this: </p> <pre><code>import sys from collections import OrderedDict import json import os file = sys.argv[1] f = open(file, 'r') dir...
<p>I didn't get the point of Read variable - it is always True in your code, the last 'elif' statement would be enough. Below is php version of your script</p> <pre><code>&lt;?php $fileName = $argv[1]; $dir = '/dir/to/JSONs/'; $fullPath = $dir . $fileName . '.json'; $data = []; $output = fopen($fi...
php|python
2
454
40,956,101
django aggregate and filter
<p>I'm going to convert this sql to django commands:</p> <pre><code>SELECT core.id, core.title, core.age_id, core.cat_id, max(date) AS max_date FROM core WHERE core.state = 'ABC' GROUP BY cat_id, age_id </code></pre> <p>I tried this, but not works correctly:</p> <pre><code>Core.objects.values('id', 'title'...
<p>You have to do this with <a href="https://docs.djangoproject.com/en/1.10/ref/models/querysets/#values" rel="nofollow">values()</a> but restrict fields that you want to group by</p> <pre><code>Core.objects.values('age_id', 'cat_id').filter(state='ABC').annotate(Max('date'), Count('age_id', 'cat_id')) </code></pre>
python|sql|django
1
455
40,971,433
Python Selenium Element does not exist
<p>Been struggling to click a certain nested li in a ul. Each attempt throws an error. Im trying to use xpath however any approach would be welcome. Also take into consideration that there is some extra text after the span tag. </p> <p>Script:</p> <pre><code> driver.find_element_by_xpath("//label[text()=contains(span...
<ol> <li>The spelling of "Tomorrow" is different in the XPath and HTML.</li> <li>In <code>contains()</code> function, try <code>contains(., 'Tommorow')</code>. Replace <code>span</code> with <code>.</code>.</li> </ol> <p>Correct XPath will be (Check the spelling of "Tomorrow")</p> <pre><code>//label[text()=contains(....
python|python-2.7|selenium-webdriver|phantomjs
1
456
38,342,079
Python - Getting A Page's Complete HTML Via Url / Request ERROR
<p>I'm trying to get the html of this page:</p> <pre><code> url = 'http://www.metacritic.com/movie/oslo-august-31st/critic-reviews' </code></pre> <p>and I'm trying to get it using requests:</p> <pre><code> oslo = requests.get(url) </code></pre> <p>but they seem to know that I'm accessing it this way and when I open...
<p>You need to specify a <a href="https://en.wikipedia.org/wiki/User_agent" rel="nofollow"><code>User-Agent</code> header</a> to get 200 response:</p> <pre><code>import requests url = 'http://www.metacritic.com/movie/oslo-august-31st/critic-reviews' response = requests.get(url, headers={'User-Agent': 'Mozilla/5.0 (M...
python|html|url|web-scraping|python-requests
1
457
38,098,101
how do i overwrite to a specific part of a text file in python
<p>For example if in my text file i have,</p> <p>Explosion,Bomb,Duck Jim,Sam,Daniel</p> <p>and i wanted to change the Daniel in that file, so that nothing else would be affected. How would I achieve this without overwriting the whole file.</p>
<p>You can use <code>fileinput</code></p> <pre><code>import fileinput with fileinput.FileInput(fileToSearch, inplace=True, backup='.bak') as file: for line in file: print(line.replace(textToSearch, textToReplace), end='') #testToSearch:- Daniel #textToReplace:- newName </code></pre> <p>O...
python|file
1
458
31,167,967
Python 3.4 - Text to Speech with SAPI
<p>I was trying to use this code to convert text to speech with Python 3.4, but since my computer's main language is not English (I'm using Win7x64) the voice and the accent are wrong (Because I want it to "speak" English).</p> <pre><code>import win32com.client speaker = win32com.client.Dispatch("SAPI.SpVoice") speake...
<p>Chances are that your OS only came with one voice as it is. There are several ways you can get English sounding output using IPA (<em>International Phonetic Language</em>) and SVSFIsXML as a flag in your speak call... but I'm guessing you'd want something less complicated than that.</p> <p>The first thing I'd do is...
python|windows|python-3.x|sapi
5
459
29,200,353
How to speed quicksort with numba?
<p>I am trying to implement the quicksort algorithm using numba in Python.</p> <p>It appears to be a lot slower than the numpy sort function.</p> <p>How could I improve it? My code is here:</p> <pre><code>import numba as nb @nb.autojit def quick_sort(list_): """ Iterative version of quick sort """ #...
<p>In general, if you don't force the <code>nopython</code> mode you have high chances of getting no performance improvement. Citing from <a href="http://numba.pydata.org/numba-doc/dev/glossary.html#term-nopython-mode" rel="nofollow">the docs about <code>nopython</code> mode</a>:</p> <blockquote> <p>[<code>nopython<...
python|numpy|numba
3
460
8,796,783
pymssql ( python module ) unable to use temporary tables
<p>This isn't a question, so much as a pre-emptive answer. (I have gotten lots of help from this website &amp; wanted to give back.)</p> <p>I was struggling with a large bit of SQL query that was failing when I tried to run it via python using pymssql, but would run fine when directly through MS SQL. (E.g., in my ca...
<p>Update: July 2016</p> <p>The previously-accepted answer is no longer valid. The second "will NOT work" example does indeed work with pymssql 2.1.1 under Python 2.7.11 (once <code>conn.autocommit(1)</code> is replaced with <code>conn.autocommit(True)</code> to avoid "TypeError: Cannot convert int to bool"). </p>
python|pymssql
2
461
58,844,138
Python: how do you change the value of a global variable in a function?
<p>Why can't I change the variable can_answer to False without getting this error? This is just some quick code I wrote.</p> <pre class="lang-py prettyprint-override"><code>import random questions = ["What's 1+1?", "What's 2+2?"] def question(): global can_answer can_answer = True print(random.choice(question...
<p>Use the <code>global var</code> before using the variable</p> <p>In this case, guess you wrote wrong here </p> <pre><code> if can_answer == 2 or 4: </code></pre> <p>Isn't <code>answer</code></p> <pre><code>import random questions = ["What's 1+1?", "What's 2+2?"] def question(): global can_answer can_ans...
python|global-variables|local-variables
1
462
52,024,271
Set dataframe column value based count of values and group by
<p>The problem:</p> <p>I have a basic python/pandas dataframe with a unit id ("Sarzs_no") and a column based on time of the day("Time_of_day", two values: day/night).</p> <p><a href="https://i.stack.imgur.com/qEauz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qEauz.png" alt="enter image descript...
<p>You can get count per groups by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.size.html" rel="nofollow noreferrer"><code>GroupBy.size</code></a>, create <code>DataFrame</code> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.join.html" ...
python|pandas|dataframe
2
463
52,121,560
Python - Key of max value in nested dict, generalization
<p>I would like to know how we can return the key value of nested dicts. The case of dict of dict (case 1) has already been answer elsewhere, but I do not manage to generalise</p> <p>Case 1: dict of dict</p> <pre><code>dict = {'key1': {'subkey1': value11, 'subkey2': value12, ...} 'key2': {'subkey1': value21, ...
<p>This answer assumes you know the path of the nested key. Then one possible view of case 2 is:</p> <pre><code>((d.get(key)).get(subkey1)).get(subsubkey1) </code></pre> <p>You want to apply function <code>get</code> in a cumulative way, notice that <code>get</code> can be exchanged with the operator <code>[]</code>,...
python|dictionary|nested|key|max
0
464
51,569,298
Class doesn't recognize the attribute
<pre><code>class Hand: def __int__(self): self.value= 0 self.ace=False self.Cards = [] def __str__(self): hand_comp="" for card in self.Cards: card_name=card.__str__() hand_comp+= " " + card_name return 'The card has %s' %(hand_comp)...
<p>You are using wrong keyword for initializing class It should be <strong>init</strong> not <strong>int</strong>.</p> <pre><code>def __init__(self): </code></pre>
python|class|oop|object
0
465
51,688,936
Python 3.6 - Save dictionary containing type 'bytes' to file
<p>I'm working on a project where I identify all the unique occurrences of fixed size blocks within a binary file and save then save the result to a binary file (it needs to work across multiple languages).</p> <p>My approach is the following: I read each block of the file, hash, and store the unique hashes and binary...
<p>Have you tried</p> <pre><code>import pickle with open('out.pickle', 'wb') as f: pickle.dump(dict, f, protocol=pickle.HIGHEST_PROTOCOL) with open('out.pickle', 'rb') as f: b_dict = pickle.load(f) # This is to check that you saved the same dict in memory print dict == b_dict </code></pre>
python|python-3.x|dictionary
3
466
67,413,075
Store Instance of Class in String
<p>How can I store an instance of a class in a string? I tried <code>eval</code>, but that didn't work and threw <code>SyntaxError</code>. I would like this to work for user-defined classes and built-in classes (<code>int</code>, <code>str</code>, <code>float</code>).</p> <p>Code:</p> <pre class="lang-py prettyprint-ov...
<p>The convention is to return a string with which you could instantiate the same object, if at all reasonable, in the <code>__repr__</code> method.</p> <pre><code>class TestClass: def __init__(self, number): self.number = number def __repr__(self): return f'{self.__class__.__name__}({self.numbe...
python|string|class
3
467
63,331,710
AWS cdk python, which IAM role for a glue crawler with a daily trigger?
<p>I am trying to deploy a <code>glue crawler</code> for an s3. Unfortunately I cant manage to find an appropriate IAM role that allows the crawler to run. The permissions I need are just to read/write to S3, and logs:PutLogsEvent, but somehow I am not getting it right. Here is my code, it can be deployed but the <code...
<p>As it turns out, I needed to pass the name and policy in a different way</p> <pre><code> glue_role = iam.Role( self, 'glue_role_id2323', role_name = 'Rolename', assumed_by=iam.ServicePrincipal('glue.amazonaws.com'), managed_policies=[iam.ManagedPolicy.from_aws_managed_policy_name('...
python-3.6|amazon-cloudformation|amazon-iam|aws-glue|aws-cdk
3
468
36,631,821
python get checkbutton value after end of mainloop
<p>I want to find out, which checkbuttons were checked after application is closed. If i save checkbuttons values in any collection, it's not possible to have an access to that collection after application is destroyed.</p> <pre><code>app = Application(path_to_files) app.initialize(data) app.mainloop() #i want to know...
<p>OK, I modified your code a bit. You will find explanations as comments inside the code. I added the protocol method (which you can call with <code>self.master.protocol</code>) and changed the close method, so that before it destroys the app it iterates through the checkbuttons and collects the flags in a directory,...
python|tkinter
1
469
36,602,181
Python list can't delete first item
<p>I'm trying to create a list of text files from a directory so I can extract key data from them, however, the list my function returns also contains a list of the file pathways as the first item of the list. I've tried del full_text[0] which didn't work, as well as any other value, and also the remove function. Any i...
<p>You can use slicing to get rid of the first element - <code>full_text[1:]</code>. This creates a copy of the list. Otherwise, you can <code>full_text.pop(0)</code> and resume using <code>full_text</code></p>
python|list
0
470
13,517,568
How to create new PyQt4 windows from an existing window?
<p>I've been trying to call a new window from an existing one using python3 and Qt4.</p> <p>I've created two windows using Qt Designer (the main application and another one), and I've converted the .ui files generated by Qt Designer into .py scripts - but I can't seem to create new windows from the main application.</...
<p>Although <code>pyuic</code> can create executable scripts with the <code>-x, --execute</code> option, it is mainly intended for testing.</p> <p>The main purpose of <code>pyuic</code> is to create <em>static</em> python modules from Qt Desgner <code>ui</code> files that allow you to <em>import</em> the contained GUI...
python|window|pyqt|qt-designer|pyuic
13
471
22,073,515
Python - Should I use read-only @property without init or setter?
<p>Trying to get my head around property decorators. I found a solution posted for setting read-only attributes <a href="https://stackoverflow.com/questions/3640700/alternative-to-passing-global-variables-around-to-classes-and-functions">here</a>. Setting a private attribute and then providing a @property getter method...
<p>There is no problem. <code>@property</code> is just doing less than you think. All it is is a bit of syntactic sugar to replace: <code>a = foo.x</code> with <code>a = foo.x.getter()</code>, and <code>foo.x = bar</code> with <code>foo.x.setter(bar)</code>. That is, it allows you to replace attribute access with me...
python|class|properties
2
472
17,038,142
Is there any equivalent of Perl's XML::TreePP in Python?
<p>Perl's XML::TreePP is really good for XMP parsing/writing. Is there any equivalent class in Python?</p>
<p>import xml.etree.ElementTree</p> <p>see <a href="http://docs.python.org/2/library/xml.etree.elementtree.html" rel="nofollow">http://docs.python.org/2/library/xml.etree.elementtree.html</a></p>
python|xml
0
473
16,679,995
Python not ignoring empty items in list
<p>I have this code to print some strings to a text file, but I need python to ignore every empty items, so it doesn't print empty lines.<br> I wrote this code, which is simple, but should do the trick:</p> <pre><code>lastReadCategories = open('c:/digitalLibrary/' + connectedUser + '/lastReadCategories.txt', 'w') for ...
<p>Test for boolean truth instead, and reverse your test so that you are certain that <code>.split()</code> will work in the first place, <code>None.split()</code> would throw an exception:</p> <pre><code>if category is not None and category.split(",")[0]: </code></pre> <p>The empty string is 'false-y', there is no n...
python|list|for-loop
4
474
16,928,061
Can I trick numpy.histogram into behaving like numpy.bincount?
<p>So, I have lists of words and I need to know how often each word appears on each list. Using ".count(word)" works, but it's too slow (each list has thousands of words and I have thousands of lists). </p> <p>I've been trying to speed things up with numpy. I generated a unique numerical code for each word, so I could...
<p>Don't use numpy for this. Use <a href="http://docs.python.org/2/library/collections#counter-objects" rel="noreferrer"><code>collections.Counter</code></a> instead. It's designed for this use case.</p>
python|numpy|histogram
6
475
43,699,578
Does this mean I have a Nvidia GPU?
<pre><code>abigail@abilina:~/nlp$ lspci 00:00.0 Host bridge: Intel Corporation Skylake Host Bridge/DRAM Registers (rev 07) 00:01.0 PCI bridge: Intel Corporation Skylake PCIe Controller (x16) (rev 07) 00:02.0 Display controller: Intel Corporation HD Graphics 530 (rev 06) 00:14.0 USB controller: Intel Corporation Sunri...
<p>To answer the question in the title: yes, you have a NVIDIA GPU, a GeForce GTX 750 Ti. You can use this GPU with TensorFlow if you install CUDA (see here for a full list of GPUs that can be used with CUDA: <a href="https://developer.nvidia.com/cuda-gpus" rel="nofollow noreferrer">https://developer.nvidia.com/cuda-gp...
tensorflow|deep-learning|gpu
3
476
43,514,814
Add argparse arguments on the go
<p>So basically, I have 10-50 additional parameter configurations that I want to potentially send into the script via <code>argparse</code> - and I don't want to configure them all in the python script.</p> <p>It's only me running the script, so there is no security issue. Is there any way I could call my script with<...
<p>Where are your configuration parameters defined ? If your program has a list of such parameters, you can always use a loop to add all parameters.</p> <pre><code>for parameter_name in parameter_names: argparser.add_argument( '--' + parameter_name, action='store', metavar='&lt;string&gt;' ) </code></pre> <p>Th...
python|argparse
3
477
55,251,122
QSS not applied to first QSizeGrip in (composite widget) in QVBoxLayout
<p>As shown below, the widget <code>TestWidget</code> contains a <code>QFrame</code> and a CSS-styled <code>QSizeGrip</code>. Several <code>TestWidget</code> instances are placed in a <code>QVBoxLayout</code></p> <pre><code>from PySide import QtGui, QtCore import sys class TestWidget(QtGui.QWidget): def __init__(...
<p>What is observed is a predetermined behavior but not documented, if the <a href="https://code.qt.io/cgit/qt/qtbase.git/tree/src/widgets/widgets/qsizegrip.cpp?h=dev#n156" rel="nofollow noreferrer">source code</a> is revised it will be observed:</p> <pre><code>Qt::Corner QSizeGripPrivate::corner() const { Q_Q(con...
python|pyside|qtstylesheets|pyside2
1
478
47,857,982
Save Pandas df containing long list as csv file
<p>I am trying to save a pandas dataframe as .csv file. Currently my code looks like this:</p> <pre><code>with open('File.csv', 'a') as f: df.to_csv(f, header=False) </code></pre> <p>The saving works but the problem is that the lists in my dataframe are just compressed to [first,second,...,last] and all the e...
<p>I had issues while saving dataframes too. I had a dataframe in which some columns consisted of lists as its elements. When I saved the datfarme using <code>df.to_csv</code> and then read it from disk using <code>df.read_csv</code>, the list and arrays were turned into a string of characters. Hence <code>[1,2,3]</cod...
python|pandas|csv
5
479
66,103,664
How to correctly specify the type of a variable in Python in order to prevent unresolved reference in PyCharm?
<p>I have a function:</p> <pre class="lang-py prettyprint-override"><code>def foo(path): &quot;&quot;&quot; :param path: Path to a folder :type path: pathlib.Path &quot;&quot;&quot; new_path = path / 'tmp' return new_path </code></pre> <p>which gets a <code>pathlib.Path</code> object and adds '...
<p>In the below example PyCharm does issue a warning <code>Unresolved reference 'Path'</code> because in the annotation the type <code>Path</code> that type hints <code>argument_path</code> has not been imported from <code>pathlib</code>. The warning is issued both for the argument and the variable.</p> <pre class="lan...
python|pycharm|python-typing
2
480
72,578,307
Filling dataframe with average of previous columns values
<p>I have a dataframe with having 5 columns with having missing values. How do i fill the missing values with taking the average of previous two column values. Here is the sample code for the same.</p> <pre><code>coh0 = [0.5, 0.3, 0.1, 0.2,0.2] coh1 = [0.4,0.3,0.6,0.5] coh2 = [0.2,0.2,0.3] coh3 = [0.8,0.8] coh4 = [0.5...
<p>For the exception you named, the first <code>NaN</code>, you can do</p> <pre class="lang-py prettyprint-override"><code>df.iloc[1, -1] = df.iloc[0, -1] </code></pre> <p>though it doesn't make a difference in this case as the mean of .2 and .8 is .5, anyway.</p> <p>Either way, the rest is something like a rolling win...
python|pandas|dataframe
1
481
39,806,895
find all files matching exact name with and without an extension
<p>I'm using glob to scan a specified directory to find all files matching the specified name, but I can't seem to get it to work with files with no extension without finding files matching the name and then some...</p> <p>For example, here's some files:<br> - file<br> - file2<br> - file.dat</p> <p>The resulting list...
<p>Shortly after posting this question, I thought of the answer, but gave up the phone before I could post it...</p> <p>So instead of relying on glob to find the royal all files, have it only look for files with extensions.</p> <p>Here's how to validate if glob is even needed:</p> <pre><code>path = 'subdirectory/fil...
python|glob
0
482
40,534,282
Django - Two Users Accessing The Same Data
<p>Let's say that I have a <code>Django</code> web application with two users. My web application has a global variable that exist on the server (a <code>Pandas Dataframe</code> created from data from an external <code>SQL</code> database).</p> <p>Let's say that a user makes an <code>update</code> request to that <cod...
<p>Ehm... Django is not a server. It has a single-threaded development server in it, but it should not be used for anything beyond development and maybe not even for that. Django applications are deployed using WSGI. WSGI server running your app is likely to start several separate worker threads and will be killing and...
python|django|multithreading
2
483
9,694,348
Django's authentication backends change
<p>I have to change the Django's authentication backend (the default is django.contrib.auth.AuthenticationBackend) to one of my own. The problem is that since Django stores the authentication backend for a requested user in the session, it throws errors to me when I try to use the new backend. The option is to delete a...
<p>Look at the Pinax project's <a href="https://github.com/pinax/pinax/blob/master/pinax/apps/account/auth_backends.py" rel="nofollow noreferrer">account auth_backends </a>, there it replaces with own one. I think Pinax code helps you while changing Django's authentication backend.</p>
python|django
0
484
10,057,234
OpenCV: how to restart a video when it finishes?
<p>I'm playing a video file, but how to play it again when it finishes?</p> <p>Javier</p>
<p>If you want to restart the video over and over again (aka looping it), you can do it by using an if statement for when the frame count reaches <code>cap.get(cv2.cv.CV_CAP_PROP_FRAME_COUNT)</code> and then resetting the frame count and <code>cap.set(cv2.cv.CV_CAP_PROP_POS_FRAMES, num)</code> to the same value. I'm us...
python|c++|c|opencv
11
485
63,316,534
String is in array returning strange results
<p>I'm creating a dynamic array of UUIDs, and I have another list of existing UUIDs, I want to delete items from the existing list that aren't in the new dynamic list. I'm trying to do this like this</p> <pre><code># Remove components that aren't being updated new_component_id_for_existing_sections = [] for component i...
<p>Turns out this was a type issue, existing_component.component.id is a UUID, and the array items are strings, and it didn't like comparing UUID -&gt; Strings.</p> <p>Adding this solved the issue <code>existing_component.component.id.__str__()</code></p>
python
1
486
47,348,598
Pyqt5 QtableWidget and integrated combobox fails to call a function when combobox items change
<p>I have the below code :</p> <pre><code>import sys from PyQt5.QtGui import * from PyQt5.QtCore import * from PyQt5.QtWidgets import * class tabdemo(QMainWindow): def __init__(self): super(tabdemo, self).__init__() self.setGeometry(50,50,500,500) self.centralWidget = QWidget() sel...
<p>Use the <code>currentIndexChanged</code> signal of the combobox.</p> <p>You can set a property on the combobox to store and recover which row (and column if you want) it belongs to.</p> <pre><code> for j in attr: self.tableWidget.setItem(i, 0, QTableWidgetItem(j)) combobox = QComboBox() ...
python|combobox|pyqt|signals|qtablewidget
1
487
47,123,834
Add error if no vowel detected in input string
<p>I'm writing a program that is supposed to take an input and output what the most common vowel is as seen here:</p> <pre><code>while True: string = input("Enter a line of text: ") vowel = "aeiouAEIOU" x = Counter(c for c in string.upper() if c in vowel) most = {k: x[k] for k in x if x[k] == max(x.v...
<p>Since you already have a counter of all vowels (<code>x</code>) it would be a waste to check (again) whether user input contains vowels. You could simply check that <code>x</code> is empty (i.e., that it has not counted any vowels):</p> <pre><code>if not x: print("Error, no vowels were detected in the user inpu...
python
2
488
70,760,201
Optimizing DB queries
<p>I need to verify existence of entities in the database.</p> <pre><code> If db_is_team_exist(team_id): If db_is_user_exist_by_id(user_id): ok else: raise ObjectDoesNotExist(&quot;user&quot;, user_id) else: raise ObjectDoesNotExist(&quot;team&quot;, team_id) </code></pre> <p>Query fun...
<p>You can technically use a single query like:</p> <pre><code>SELECT 1 WHERE EXISTS (SELECT 'x' FROM teams WHERE id='{team_id}') AND EXISTS (SELECT 'x' FROM users WHERE id='{user_id}') </code></pre> <p>Please use proper parameterized queries though.</p>
python|sql|postgresql
0
489
58,471,694
Python/Selenium/Chromedriver: the script opens just a blank Google Chrome page
<p>I have a problem with a browser automation script on a specific windows 7 machine. The code is written in python 3.7.4 with Selenium and Chromedriver. When I run it from a command line only Chrome browser starts but it does not open the url. This problem occurs only on one windows 7 machine and I can't figure out it...
<p>Check the Chrome browser version you have installed in the machine and compare it with the Chrome driver version.</p> <p>You can learn more about these changes <a href="https://chromedriver.chromium.org/downloads/version-selection" rel="nofollow noreferrer">here</a> and download latest drivers <a href="https://chro...
python|selenium|selenium-chromedriver
1
490
30,140,924
My Pygame messagetoscreen function doesnt show text
<p>I am following a youtube tutorial series, and I came across this problem with my pygame game. I made a function called messagetoscreen, and it works fine in the video, but it doesn't work for me.</p> <p>Here is my code:</p> <pre><code>#Imports import pygame pygame.init() pygame.font.init() import sys import rando...
<p>The answer is that I blitted the text to the screen before I filled gamedisplay with white. Remember to blit text after drawing a background.</p> <p>Here is the code that draw graphics in the while loop:</p> <pre><code>gamedisplay.fill(white) pygame.draw.rect(gamedisplay, green, (rect1x, rect1y, rect1sizex, rect1s...
python|function|fonts|pygame
0
491
27,461,682
computing rolling averages by integer days in pandas
<p>I have taken some data from a csv and put it into a dataframe:</p> <pre><code>from pandas import read_csv df = read_csv('C:\...', delimiter = ',', encoding = 'utf-8') df2 = df.groupby(['i-j','day'])['i-j'].agg({'count'}) </code></pre> <p><img src="https://i.stack.imgur.com/Uq3fb.png" alt="dataframe"></p> <p>I wou...
<p>There may be a better way to do this, but given your starting DataFrame of <code>df2</code> the following should work.</p> <p>First reindex <code>df2</code> to fill in the missing days with zeros:</p> <pre><code>new_index = pd.MultiIndex.from_product([df2.index.get_level_values(0).unique(), range(31)]) df2 = df2.r...
python|pandas|time-series|dataframe
1
492
43,363,177
Python Multiprocessing Pipe hang
<p>i'm trying to build a program to send a string to process Tangki and Tangki2 then send a bit of array data each to process Outdata, but it seems not working correctly. but when i disable gate to the Outdata everything works flawlessly. </p> <p>this is the example code:</p> <pre><code>import os from multiprocessing...
<p>it's actually because buffer size limit? but adding <code>dout=[x,y,degree,tinggi]</code> and <code>dout=[x,y,degree,tinggi]</code> reset the size of data to minimal, or by assigning <code>dout=[0,0,0,0]</code> and <code>dout2=[0,0,0,0]</code> right after <code>selang1.send(dout)</code> and <code>selang2.send(dout2)...
python-3.x|pipe|multiprocessing
0
493
48,636,840
PyCharm does not recognized a module in the project
<p>I ran in the following problem: I created a project in Pycharm and my PyCharm does not recognized a modules from the packages. </p> <p>I use Python 3.6</p> <p>Please see the screenshot:</p> <p><img src="https://i.stack.imgur.com/pu1Za.png" alt="enter image description here"></p>
<p>Try to do the following steps:</p> <ol> <li>Go to <code>File-&gt;Settings</code> (it'll open a window). In the right box, go to <code>Project-&gt;Project structure</code>. In the left click in <code>+ add content root</code> and pick the folder module you'd like to add. After that, mark this folder as <code>Source</...
python|pycharm
0
494
66,801,788
Google OAuth2 - Error: redirect_uri_mismatch
<p>I'm trying to run this project <a href="https://github.com/googleapis/python-analytics-data" rel="nofollow noreferrer">https://github.com/googleapis/python-analytics-data</a> I create new client OAuth 2.0 in Cloud Platform and I have the client_secret_code and I add uri http://localhost to the client OAuth settings ...
<blockquote> <p>redirect_uri_mismatch</p> </blockquote> <p>This is a configuration issue. The redirect uri you added in google cloud console for your project must exactly match the one that your code is sending.</p> <p>THe easiest solution is to check the error message it should tell you the Redirect uri that is missi...
python|google-oauth|uri|google-developers-console|google-analytics-data-api
0
495
51,391,691
Call a Python function from NodeJS
<p>I need to call a python function from a NodeJS service code. I checked <a href="https://stackoverflow.com/questions/23450534/how-to-call-a-python-function-from-node-js">this link</a> and wrote below nodeJS code</p> <pre><code>const express = require('express') const app = express() let runPy = new Promise(function...
<p>I guess you misunderstand the process of calling python. You are not calling python function in <code>node</code> directly but call the process to run a shell command that run <code>./ml.py</code> and collect the console output.</p> <p>If that's clear then the problem is obvious, you define the function in python b...
python|node.js
6
496
73,766,377
2 download click button with same class using selenium python
<p>I am unable to click on 2 download buttons with same button class. below is the code</p> <pre><code>file=driver.find_element_by_xpath(&quot;(//button[@class='MuiButtonBase-root MuiIconButton-root IconButton-sc-iv40hv-1 cLszZl IconButton-sc-iv40hv-0 hbJxSM DownloadButton-sc-19l7ggt-0 gHtfyl MuiIconButton-colorPrimary...
<p>To get the specific button try with class and index OR try with text and index whichever you comfortable.</p> <p>Example you have 2 buttons like this</p> <p><strong>Button 1 :</strong></p> <pre><code>&lt;button class=&quot;expedition_button awesome-button &quot; onclick=&quot;attack(null, '2', 1, 0, '')&quot;&gt;Att...
python|selenium
0
497
17,516,672
Ordering by subquery in SQLAlchemy
<p>I'm trying to select the newest threads (Thread) ordered descending by the time of the most recent reply to them (the reply is a Post model, that's a standard forum query). In SQL I'd write it like this:</p> <pre><code>SELECT * FROM thread AS t ORDER BY (SELECT MAX(posted_at) FROM post WHERE thread_id = t.id) DESC ...
<p>looks fine to me, here's a test:</p> <pre><code>from sqlalchemy import * from sqlalchemy.orm import * from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class Thread(Base): __tablename__ = 'thread' id = Column(Integer, primary_key=True) class Post(Base): __tablename__...
python|mysql|sqlalchemy|flask-sqlalchemy
4
498
17,190,031
Python subprocess: wait for command to finish before starting next one?
<p>I've written a Python script that downloads and converts many images, using wget and then ImageMagick via chained<code>subprocess</code> calls: </p> <pre><code>for img in images: convert_str = 'wget -O ./img/merchant/download.jpg %s; ' % img['url'] convert_str += 'convert ./img/merchant/download.jpg -resize ...
<p><em>Normally</em>, <a href="http://docs.python.org/2/library/subprocess.html#subprocess.call" rel="noreferrer"><code>subprocess.call</code></a> is blocking.</p> <p>If you want <em>non blocking</em> behavior, you will use <a href="http://docs.python.org/2/library/subprocess.html#subprocess.Popen" rel="noreferrer"><c...
python|imagemagick|subprocess|imagemagick-convert
19
499
64,255,129
How to use a pandas interval to lookup values, to fill another dataframe
<p>I have two dataframes (<code>df1</code>, <code>df2</code>):</p> <pre><code>x id 35 4 55 3 92 2 99 5 </code></pre> <p>and</p> <pre><code>id x val 1 (0.0, 50.0] 1.2 2 (90.0, inf] 0.5 3 (0.0, 50.0] 8.9 3 (50.0, 90.0] 9.9 4 (0.0, 50.0] 4.3 4 (50.0, 90.0] 1.1 4 ...
<ul> <li>A value can be found in a <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Interval.html" rel="nofollow noreferrer"><code>pd.Interval</code></a> <ul> <li><code>40 in pd.Interval(0.0, 50.0, closed='right')</code> evaluates as <code>True</code></li> </ul> </li> <li>Likewise, if a <code>...
python|python-3.x|pandas|dataframe|lookup
3