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 |
|---|---|---|---|---|---|---|
8,400 | 19,760,184 | parsing a twitter feed in Python into a table | <p>Have a set of tweets that have been saved to a .txt file. </p>
<p>I want to place certain attributes in a sqlite table in Python. I successfully created the table. </p>
<pre><code>import pandas
import sqlite3
conn = sqlite3.connect('twitter.db')
c = conn.cursor()
c.execute(CREATE TABLE Tweet
(
created_at VARCH... | <p>I imagine there is a python library for this already, but I was able to get your tweet string to parse as a dictionary once I replaced these terms that appear unquoted.</p>
<pre><code> false to False
true to True
null to None
</code></pre>
<p>I just assigned the whole bracketed expression to a variable, creatin... | python|sqlite|twitter|pandas | 0 |
8,401 | 19,474,555 | Django's Model save flow | <p>I noticed that there's no guarantee that the data base is updated synchronously after calling save() on a model. </p>
<p>I have done a simple test by making an ajax call to the following method</p>
<pre><code>def save(request, id)
product = ProductModel.objects.find(id = id)
product.name = 'New Product Name'
... | <p>You should have mentioned App Engine more prominently. I've added it to the tags.</p>
<p>This is very definitely because of your lack of understanding of GAE, rather than anything to do with Django. You should read the GAE documentation on <a href="https://developers.google.com/appengine/docs/python/datastore/struc... | python|ajax|django|google-app-engine | 5 |
8,402 | 13,481,582 | Pipe output of python script | <p>I'm running <code>./sample.py --url http://blah.com</code> without error, though if I run <code>./sample.py --url http://blah.com | wc -l</code> or similar I receive an error: </p>
<p><code>UnicodeEncodeError: 'ascii' codec can't encode character u'\u200f' in position 0: ordinal not in range(128)</code></p>
<p>How... | <p>When Python detects that it is printing to a terminal, <code>sys.stdout.encoding</code> is set to the encoding of the terminal. When you <code>print</code> a <code>unicode</code>, the <code>unicode</code> is encoded to a <code>str</code> using the <code>sys.stdout.encoding</code>.</p>
<p>When Python does not detect... | python|terminal|piping | 6 |
8,403 | 57,738,656 | How to stop player sprite passing through blocks with collision detection? | <p>I am trying to stop the player passing through blocks. I would like them to be able to land on the blocks but bounce away if there is a collision on the other sides of the block</p>
<p>I have previously tried changing the distance the player is reset to when they hit a block</p>
<p>Run every frame to check if ther... | <p>In my (not so vast) experience this kind of problems may arise when the player movement is not tested separatately for each dimension.</p>
<p>I suggest you to:</p>
<ol>
<li><p>Separate x and y movements and collision tests, so that you can move your player along x, test for collision and fix x position if needed, ... | python|pygame|collision | 0 |
8,404 | 58,126,489 | How To Solve Error: ImproperlyConfigured: mysqlclient 1.3.13 or newer is required in Django on Windows? | <p>I follow the tutorial from Traversy Media on Youtube videos. When I put the command </p>
<blockquote>
<p>python manage.py migrate </p>
</blockquote>
<p>Then I got such an error like this:</p>
<pre><code>C:\Users\Acer\Project\djangoproject>python manage.py migrate
Traceback (most recent call last):
File "ma... | <p>Are you using a virtual environment? If you have no idea what I'm talking about, see <a href="https://code.tutsplus.com/tutorials/understanding-virtual-environments-in-python--cms-28272" rel="nofollow noreferrer">this</a> blog for a good explanation for what a virtual environment is.</p>
<p>For this example I will... | django|python-3.x|windows | 0 |
8,405 | 43,749,138 | How can I manually interact with a custom Graph Editor in Maya (Using Python) | <p>I've been practicing my python/mel coding and have been interested in creating a graph editor. I did a lot of research online and found this previous question (<a href="https://stackoverflow.com/questions/27107009/how-can-i-keep-an-object-selected-in-the-outliner-after-physically-deselecting-i">How can I keep an obj... | <p>So after some research I decided the easiest thing was to use Maya's own graph editor within my interface</p>
<pre><code># GRAPH ROW
# Section for the graph editor to allow the user to change attributes
paneLayout( configuration='single', parent=form, width=620, height=320 )
# queries Maya's graph editor and places... | python|graph|editor|maya | 0 |
8,406 | 53,548,282 | Append rows from pandas df to a new csv while preserving the headers once? | <p>My goal is to open a very large csv file, read the file, then do stuff on the subset of data. In this case, "stuff" is writing to a blank csv, but in future it will be running functions on the data, 200 rows at a time (this saves computing time on my end for some reason, over running the entire csv through the funct... | <p>Just put <code>header=True</code> in the first time you write.</p>
<pre><code>with open(csvFile, encoding = 'utf8', errors = 'ignore') as csv_file:
chunksize = 200
i = 0
j = 1
for df in pd.read_csv(csv_file, encoding = 'utf-8', chunksize=chunksize, iterator=True):
df.index += j
i += ... | python|python-3.x|pandas|loops|export-to-csv | 2 |
8,407 | 54,617,473 | Combine 4 multidimensional arrays into one array while maintaining the original dimensions - Python | <p>I have 4 multidimensional arrays, each with dimensions of nrow=50 ncol=100. Each array consists of mostly zeros, but does contain lengths of float data (non-zeros). Also, across all 4 arrays, the position of non-zero data is always a zero in that same position in the other arrays. I've therefore been trying to overl... | <p>If the dimensions of the 4 arrays is the same and <em>position of non-zero data is always a zero in that same position in the other arrays</em> as you said you can simply add the arrays together, i.e.</p>
<pre><code>combined = ar1 + ar2 + ar3 + ar4
</code></pre> | python|arrays | 0 |
8,408 | 54,305,527 | Python: Replace a list in place from where it is referenced, not create a new reference/list | <p>I am working with quite big number of values in Python (memory footprint is 5GB). </p>
<p>Sometimes, I need to access values by key, sometimes I need to loop values. For performance reasons, I am converting the Dict to a List at startup, so I can:</p>
<ul>
<li>use the Dict in cases where I want to access values by... | <p>To modify the list in-place, assign to its slice:</p>
<pre><code>my_big_values_list[:] = list(my_big_dict_of_values.values())
</code></pre>
<p>Example:</p>
<pre><code>>>> my_big_dict_of_values = {"a": 1, "b": 2, "c": 3}
>>> my_big_values_list = list(my_big_dict_of_values.values())
>>> a... | python|performance|reference|pass-by-value | 3 |
8,409 | 9,039,505 | Toggling Threads | <p>Should i keep using threads like this or should i use multiprocessing? I'm trying to get the while loop to toggle with a button press.</p>
<p>Thread:</p>
<pre><code>class workingthread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
while 1:
... | <p>Your question is a little bit unclear. I'm trying to focus on the "I'm trying to get the while loop to toggle with a button press" part. To my understanding, you want to have thread activity all the time (by activity I think of not killing the thread), but you only want to occasionally have while-loop body executed.... | python|multithreading|wxpython | 0 |
8,410 | 55,161,611 | How to groupby in pandas where i have column values starting with similar letters | <p>Suppose i have a column with values(not column name) <code>L1 xyy, L2 yyy, L3 abc,</code> now i want to group <code>L1, L2 and L3</code> as L(or any other name also would do).
Similarly i have other values like A1 xxx, A2 xxx, to be grouped form A and so on for other alphabets.
How do i achieve this in pandas?
I hav... | <p>Use indexing by <code>str[0]</code> for return first letter of column and then aggregate some function, e.g. <code>sum</code>:</p>
<pre><code>df = pd.DataFrame({'col':['L1 xyy','L2 yyy','L3 abc','A1 xxx','A2 xxx'],
'val':[2,3,5,1,2]})
print (df)
col val
0 L1 xyy 2
1 L2 yyy 3
2 L3 ... | pandas|group-by | 2 |
8,411 | 47,590,717 | How to run apps in Kivy Launcher if the application uses additional modules? | <p>I have created an app in Kivy.<br>
It uses two modules: <em>requests</em> and <em>geocoder</em>.<br>
How can I run this app by using Kivy Launcher?</p> | <p>You can install them manually into your project directory.<br>
So if you need <code>Requests</code> for example, you can package it with the application.<br>
You can download the source, copy the requests directory into your application’s codebase, and <code>import requests</code> in your python files as you normall... | python|kivy | 0 |
8,412 | 37,263,307 | Index a list in Python with number if list index not outside of range | <p>I'm building a parser in Python and in one step of the parser it needs to look at the next few lines to determine if a value is there. To do this, I'm doing the following:</p>
<pre><code>if "Account Summary" in line:
end_bal_regex = r"Ending balance on (.*?)\s+(-?\$[\d,]+\.\d\d)"
end_date, end_bal = [re.sea... | <p>Change the limit 16 to <code>min(16, len(text[i:]))</code></p>
<pre><code>... for j in range(1, min(16, len(text[i:]))) re.search(r"Ending balance", text[i+j], re.IGNORECASE)][0]
</code></pre> | python|for-loop|indexing|list-comprehension | 1 |
8,413 | 34,152,868 | How to create azure virtual machine via api?? (not the classic one, the one which on new azure manage portal) | <p>I would like to create azure new virtual machines via api or python sdk, the one which we have on azure's new manage portal, which allow me to use features like operate the machine's <code>network security group</code> on the portal. Thanks!
<a href="http://i.stack.imgur.com/YKxmf.png" rel="nofollow">enter image des... | <p>You should use Azure Resource Management Template that enables you to use a declarative form of the environment you wish to create
Description of the template is here
<a href="https://azure.microsoft.com/en-us/documentation/articles/resource-group-authoring-templates/" rel="nofollow">https://azure.microsoft.com/en-u... | python|azure|azureportal | 0 |
8,414 | 39,781,746 | SSHed into my Vagrant virtual machine to run a python script...but the python script doesn't work unless I'm in the VM itself | <p>I have a Vagrant virtual machine that I use for running automated tests. When I vagrant up and open up the console in my virtual machine, I'm able to start my tests with a simple command on the command line. After SSHing into that virtual machine and running the same exact script from the same exact directory, I'm g... | <p>You aren't using the same Python executable in the two environments. For some reason, your vagrant console is using a <a href="https://virtualenv.pypa.io/en/stable/" rel="nofollow">virtual environment</a>.</p>
<p>When you SSH into your VM, run this command before executing your test script:</p>
<pre><code>source /... | python|selenium|ssh|vagrant | 2 |
8,415 | 39,582,309 | For loop not working without range() " string indices must be integers" | <p><code>i</code> is a string, so how can I make this work? </p>
<p>How can I use <code>i</code> as index?</p>
<pre><code>for i in s[1:]:
if s[i] <= s[i-1]:
temp += s[i]
else:
subs.append(temp)
temp = ''
</code></pre>
<p>I've tried to use </p>
<pre><code>for i in s[1:]:
if s.i... | <p>the syntax you are using is corresponding to string iteration (see <a href="http://anandology.com/python-practice-book/iterators.html" rel="nofollow">http://anandology.com/python-practice-book/iterators.html</a>) so the <code>i</code> will iterate on the different characters of the string on note on their indices:</... | python|for-loop | 0 |
8,416 | 32,050,361 | How to filter query in Django template? Need to filter posts based on category | <p>Here is view:</p>
<pre><code>def all(request):
products = Product.objects.all()
context = {'products': products}
template = 'products/all.html'
return render(request, template, context)
</code></pre>
<p>And model:</p>
<pre><code>class Product(models.Model):
title = models.CharField(max_length=120)
des... | <p>You cant do like this,</p>
<pre><code>products = Product.objects.filter(category='womens-clothin')
</code></pre>
<p>because category is type of <code>ManyToManyField</code> not <code>string</code>.</p>
<p>First take Category object. Something like ,</p>
<pre><code>some_category = Category.objects.get(category_na... | python|django|django-templates|django-orm | 3 |
8,417 | 40,427,178 | Copying content of C buffer to numpy array | <p>I have a function in C like this:</p>
<p>source file</p>
<pre><code>// foo.cpp
int foo(int input1, double *output1, int size1, int* output2, int size2)
{
// does stuff and allocate space for output1 and output2
return 0;
}
</code></pre>
<p>header file</p>
<pre><code>// foo.h
int foo(int input1, double *outpu... | <p>The numpy documentation mentions that</p>
<blockquote>
<p>In order to make use of the C-API from another extension module, the <code>import_array</code> function must be called</p>
</blockquote>
<p>It seems you got the segmentation fault error because you didn't include import_array in your code.</p>
<p>The int... | python|c++|c|data-binding|cython | 1 |
8,418 | 9,983,664 | making difflib's SequenceMatcher ignore "junk" characters | <p>I have a lot of strings that i want to match for similarity(each string is 30 characters on average). I found <code>difflib's</code> <code>SequenceMatcher</code> great for this task as it was simple and found the results good. But if i compare <code>hellboy</code> and <code>hell-boy</code> like this</p>
<pre><code>... | <p>If you wish to do as I suggested in the comments, (removing the <em>junk</em> characters) the fastest method is to use <a href="http://docs.python.org/library/stdtypes.html#str.translate" rel="nofollow noreferrer"><code>str.translate()</code></a>.</p>
<p>E.g:</p>
<pre><code>to_compare = to_compare.translate(None, ... | python|difflib|sequencematcher | 4 |
8,419 | 32,179,234 | Vertical scrolling in Android app using Appium-Python | <p><a href="https://i.stack.imgur.com/e1me5.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/e1me5.jpg" alt="enter image description here"></a></p>
<p>Following is the UI for android app. In this a UI of Friends list is visible. It have total number of 26 friends. I want to scroll the UI and want to ... | <p>I had same problem. Most of the suggested solutions didn't work. Anyways, I found a solution you can see below:</p>
<pre><code> # import touch events
from appium.webdriver.common.touch_action import TouchAction
# Find the list element.
list = driver.find_element_by_id('com.abc.android.abc:id/common... | android|python|appium | 3 |
8,420 | 32,719,460 | In Django I want to show a Textarea only during post | <p>I've a simple page for my django project</p>
<ol>
<li>A form with 2 radio buttons</li>
<li>A char field </li>
<li>Submit</li>
</ol>
<p>when Submit is pressed .
in my views.py how can I capture the selected radio button value and value of the char field</p>
<p>When submitted, the same webpage should be reloaded ag... | <p>I'ts because when you redirect with:</p>
<pre><code>return HttpResponseRedirect('index.html',{'posted':"posted"},{'form':form})
</code></pre>
<p>You need to <a href="https://stackoverflow.com/a/936405/3207406">populate the new form</a> with the <code>form</code> value that you previously posted</p>
<pre><code>def... | python|html|django | 0 |
8,421 | 14,319,862 | Injecting HTML into a page using Mechanize | <p>I am writing a webscraping program to get my grades from a website. I used Mechanize to log into the page and navigate to the area I'm scraping. Unfortunately, the page uses Javascript to encrypt the page (possibly to stop me from scraping). I found the decryption script and ported to Python. It works and I used it ... | <p>I ended up just using this:</p>
<pre><code>response = br.open("www.linknotonpagethatiwanttogoto.com")
page = response.read()
</code></pre>
<p>I found out that you store the .open() of a link as a response, instead of using the .follow_link(). Also the browser uses the same cookies so the session cookies are preser... | javascript|python|html|web-scraping|mechanize | 0 |
8,422 | 34,549,620 | Error Spyder Python + opencv 3 | <p>I have installed Opencv 3.1.4 on Spyder Python 2.7, all running on Windows Vista 32bits.</p>
<p>My code is </p>
<pre><code>import cv2
import sys
cascPath = "C:\opencv\sources\data\haarcascades\haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cascPath)
video_capture = cv2.VideoCapture(0)
... | <p>cv2.cv does not exist in opencv3.0 +. You can replace it with an index: try this:</p>
<pre><code>flags=3
</code></pre>
<p>Anyway, I doubt that's the main reason for the error showing. According to the error you posted it did not reach that line. I am suspecting something else. Probably the camera source/frames a... | python|opencv|tracking | 0 |
8,423 | 23,102,346 | Django - Serving Media/Admin files in production with Apache/Webfaction | <p>As it stands my STATIC files are served without issue using the configuration below. </p>
<p>In my settings.py:</p>
<pre><code>MEDIA_ROOT = '/home/chronic88/webapps/media_media/'
MEDIA_URL = '/media/'
STATIC_ROOT = '/home/chronic88/webapps/static_media/'
STATIC_URL = '/static/'
</code></pre>
<p><code>static_medi... | <p>If you configured your Apache to serve the static files from the respective root folders, you also have to run <code>manage.py collectstatic</code> (see <a href="https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#collectstatic" rel="nofollow">docs</a>).</p>
<p>To test static and media files I usually ha... | python|django|apache|webfaction | 1 |
8,424 | 7,799,650 | Is there a way to set a breakpoint on variable access in Python with PyDev? | <p>I have a global variable (I know) that is being changed from a good value to a bad value somewhere. I don't know where, and I'd like to find out where. I would like my debugger (Eclipse/PyDev) to break any time any code writes to this global variable, something akin to hardware breakpoints in OllyDBG. </p>
<p>One t... | <p>Unfortunately, PyDev does not have such a feature (and after thinking a bit on how would that be implemented, I couldn't come up with a way to implement that) -- your solution on changing it for a property is the one I use when I need that feature (and it won't work for a global variable as you said... in this case,... | python|debugging|pydev|breakpoints | 2 |
8,425 | 960,467 | how can I add a QMenu and QMenuItems to a window from Qt Designer | <p>Is there any reason why a QMenu cannot be added from the Qt Designer? I find it weird that you can add other widget types but not this.</p> | <p>I have a single main window with a QGraphicsView and lots of QGraphicsItem objects. Each type of the Items have a different context menu.</p>
<p>I find that not being able to create the contextMenu's, or at least the actions that are in them a serious limitation of QtDesigner. It means that I can create about 10%... | python|qt|widget|designer | 3 |
8,426 | 768,941 | How to use a python api on iPhone? | <p>There is an "<a href="http://code.google.com/p/plurkapipy/" rel="nofollow noreferrer">Unofficial Plurk API in Python</a>".
<a href="http://www.plurk.com/" rel="nofollow noreferrer">Plurk</a> is a twitter-like website.</p>
<p>Can I use the API(python) from Objective-C? Or i have to port them?</p> | <p>Apple's iPhone developer license prohibits applications that use interpreted code. So, python is out, unfortunately.</p> | iphone|python|objective-c | 4 |
8,427 | 42,121,567 | How to recognize images within scanned PDF files? | <p>I am trying to identify images (as opposed to text) within scanned PDF files, ideally using python. Is there any way to do this? As a simple example, say you've scanned a chapter of a book. There are three possible options for a page:</p>
<ol>
<li>Contains text only</li>
<li>Contains an image only (or multiple)</li... | <p>My idea would be to look for features that do not occur in normal text - which might be vertical, black elements spanning multiple lines. My tool of choice is <strong>ImageMagick</strong> and it is installed on most Linux distros and is available for macOS and Windows. I would just run it in the Terminal at the comm... | python|image-processing|machine-learning|computer-vision|ocr | 4 |
8,428 | 47,144,606 | Requests — how to tell if you're getting a success message? | <p>My question is closely related to <a href="https://stackoverflow.com/questions/15258728/requests-how-to-tell-if-youre-getting-a-404">this one</a>.</p>
<p>I'm using the Requests library to hit an HTTP endpoint.
I want to check if the response is a success.</p>
<p>I am currently doing this:</p>
<pre><code>r = reque... | <p><a href="https://requests.readthedocs.io/en/latest/api/#requests.Response.ok" rel="nofollow noreferrer">The response has an <code>ok</code> property</a>. Use that:</p>
<pre><code>if response.ok:
...
</code></pre>
<p>The implementation is just a try/except around <a href="https://github.com/psf/requests/blob/8149... | python|http|python-requests|httprequest|http-response-codes | 72 |
8,429 | 47,092,596 | How to skip first line of questions in quiz in Python? | <p>I want to skip a first line in question. Here is a part of my code:</p>
<pre><code> newques="n"
while newques=="n":
file=open("questions.txt","r")
found=False
for line in file:
split=line.split(",")
question=split[0]
options=split[1]
... | <p>I suppose your questions.txt is such as every question starts in a new line. You read in the file into an array (questions). Then you access that array from inside your loop and advance one question each time (q).</p>
<pre><code>newques="n"
file=open("questions.txt","r")
questions = [line for line in file]
q = 0 #... | python-3.x | 1 |
8,430 | 47,272,045 | Specify format of date being read in by pandas | <p>I am using pandas to read in multiple sets of data from csv files. Is there any way to specify the date format of data being read in with read_csv?</p>
<p>For example I have one data file that has a date time column with the following format:</p>
<pre><code>d/m/y h:mm
</code></pre>
<p>and another with the followi... | <p>I create a csv file named: <strong>table.csv</strong> separated by <code>;</code></p>
<pre><code>date;numbers
1/1/19 9:9;1
25/12/18 11:11;2
;
date;numbers
2019-01-02 09:09:09;3
2018-12-26 11:11:11;4
</code></pre>
<p>Hope this code helps you understand how <code>date_parser</code> dates in diferent <a href="http://... | python|python-3.x|pandas|datetime | 0 |
8,431 | 70,766,215 | Problem with memory allocation in Julia code | <p>I used a function in Python/Numpy to solve a problem in <a href="https://oeis.org/A215721" rel="noreferrer">combinatorial game theory</a>.</p>
<pre><code>import numpy as np
from time import time
def problem(c):
start = time()
N = np.array([0, 0])
U = np.arange(c)
for _ in U:
bits = np.b... | <p>The original code can be re-written in the following way:</p>
<pre><code>function problem2(c)
N = zeros(Int, c+2)
notseen = falses(c+1)
for lN in 1:c+1
notseen .= true
@inbounds for i in 1:lN-1
b = N[i] ⊻ N[lN-i]
b <= c && (notseen[b+1] = false)
... | python|julia|game-theory | 15 |
8,432 | 47,054,318 | Grouping pandas dataframe and collecting multiple values into sets | <p>Assume that I have the following data frame <code>df1</code>:</p>
<pre><code> A B C D
0 foo one 1 0
1 bar two 2 1
2 foo two 3 0
3 bar two 4 1
4 foo two 5 0
5 bar two 6 1
6 foo one 7 0
7 foo two 8 1
</code></pre>
<p>I would like to turn it into a dataframe <code>df2</code>... | <p>Use <code>groupby</code> + <code>agg</code>:</p>
<pre><code>f = {'B' : lambda x: np.unique(x).tolist(),
'C' : lambda x: np.unique(x).tolist(),
'D' : 'first'
}
df.groupby('A', as_index=False).agg(f).reindex(columns=df.columns)
A B C D
0 bar [two] [2, 4, 6] ... | python|pandas|dataframe|data-munging | 2 |
8,433 | 47,003,574 | Pandas - key error - not recognizing column name from csv file | <p>I am picking up the most recent csv file in a folder as shown below, and then converting into a DataFrame 'ES_VX_comb_LL_15M'. </p>
<pre><code>import pandas as pd
import glob
filename2 = max(glob.iglob(r"C:\Users\cost9\OneDrive\Documents\PYTHON\Daily Tasks\Pairs Trading\ES_VX\CSV\15M\Beta\*.csv"))
f6 = open(filena... | <p>You need to set the separator to <code>'\t'</code> since pandas uses <code>','</code> by default.</p>
<pre><code>pd.read_csv(filename, sep='\t')
</code></pre> | python|pandas|csv|dataframe | 0 |
8,434 | 37,603,849 | Unable to import view in Django project | <p>I am starting a very basic Django project (using PyCharm IDE in the process). This is what I do initially.</p>
<ol>
<li><code>cd</code> into my <code>workspace</code> directory and run <code>django-admin.py startproject mysite</code>. This creates the following directory structure:</li>
</ol>
<p><a href="https://i... | <p>You shouldn't add that directory to the path.</p>
<p>You have two issues: firstly, as adriansq points out, you need an empty <code>__init__.py</code> in that directory. And secondly, it is in the wrong place; it should be one level higher, directly under the outer <code>mysite</code> directory.</p> | python|django|pycharm|pythonpath | 1 |
8,435 | 37,646,405 | Trouble with writing files inside loop (Python) | <p>I've been having trouble with the following piece of Python code. It's running without errors, but it isn't exactly giving me the expected output; no files at all are being written.</p>
<pre><code>for l in h:
r=l.rfind(",")+1
s=l[r:-2]
j=0
while j&l... | <p>The problem is that you set s to a string with <code>s=l[r:-2]</code> and then later check for an int with <code>if s[j]==1:</code></p>
<p>Since the condition is never met there won't be any files written. Check for the string "1" instead and it will work:</p>
<pre><code>for l in h: ... | python | 0 |
8,436 | 37,882,805 | Convert string of dates with 'th' 'st' 'rd' 'nd' into date format via python | <p>I am scrapping a website for the dates using beautiful soup. Here is the CSS</p>
<pre><code><div id="listing-details-list">
<h3 class="listing-details-header">
Details:
<span>Posted on: 14th June 2016</span>
</h3>
</div>
</code></pre>
<p>The code I am using for getting the date ... | <p>To parse the dates I would just let the <a href="https://labix.org/python-dateutil" rel="noreferrer"><code>dateutil</code> parser</a> do the job:</p>
<pre><code>>>> from dateutil.parser import parse
>>> l = ["23rd June 2016", "21st July 2016", "20th July 2016", "3rd July 2016"]
>>> for it... | python|regex|string|python-2.7|beautifulsoup | 9 |
8,437 | 37,813,652 | python new line (byte to string) | <p>Code:</p>
<pre><code>word="hello\nhai"
fout=open("sample.txt","w");
fout.write(word);
</code></pre>
<p>Output:</p>
<pre><code>hello
hai
</code></pre>
<p>But this:</p>
<pre><code>word=b"hello\nhai"
str_word=str(word) # stripping ' '(quotes) from byte
str_word=str_word[2:len(str_word)-1] # a... | <blockquote>
<p>I am working on sending and receiving strings over a port. As only bytes can be sent and received I have the above problem.</p>
</blockquote>
<p><code>.encode()</code> strings to create bytes. <code>.decode()</code> bytes to get strings. The default encoding is UTF-8, which can handle all characters ... | python | 3 |
8,438 | 61,376,724 | Iterating through a linked list with chain assignments | <p>Let's say I have the following names and objects</p>
<pre><code>original = n = <original_object>
n = n.next = <new_object>
</code></pre>
<p>After running the above I would expect to see <code>original</code> pointing to <code><original_object></code>, but that doesn't seem to be the case. </p>
<... | <p>As <strong>@Carcigenicate</strong> quickly noted, <a href="https://stackoverflow.com/a/36346517/283296">this answer</a> explains what's happening:</p>
<p>In short, following that argument in my example, If I do:</p>
<pre><code>n = n.next = Node(None)
</code></pre>
<p>that's equivalent to:</p>
<pre><code>temp = N... | python|python-3.x|object|linked-list | 0 |
8,439 | 72,467,770 | Datetime Time Zone Scraping Python | <p>I am trying to scrape and sort articles with a body, headline, and date column. However, when pulling the date, I’m running into an error with the time zone:</p>
<pre><code>ValueError: time data 'Jun 1, 2022 2:49PM EDT' does not match format '%b %d, %Y %H:%M%p %z'
</code></pre>
<p>My code is as follows:</p>
<pre><co... | <p>Note %z in strptime() is for timezone offsets not names and %Z only accepts certain values for time zones. For details see <a href="https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior" rel="nofollow noreferrer">API docs</a>.</p>
<p>Simplest option is to use <a href="https://dateutil.readthedoc... | python|datetime|timezone | 2 |
8,440 | 72,178,473 | pd.read_csv ("file name.csv) fails to run | <p>My PD.read_csv in Pandas is not importing my .csv file for visual representation.It keeps returning an error message. What could be the problem?
I have tried</p>
<pre><code>data=pd.read_csv('Sample-Spreadsheet-10-rows.csv' encoding = "utf-8")
print data.head
</code></pre>
<p>This code has refused to compil... | <p>Missing comma before encoding</p>
<pre><code>data=pd.read_csv('Sample-Spreadsheet-10-rows.csv', encoding = "utf-8")
</code></pre> | python|pandas|image|csv|import | 2 |
8,441 | 43,100,655 | Python split by character only if wrapped in parenthesis | <p>I am parsing a large text file that has key value pairs separated by '='. I need to split these key value pairs into a dictionary. I was simply going to split by '='. However I noticed that some of the values contain the equals sign character. When a value contains the equals sign character, it seems to be always wr... | <p>You could try partition('=') to split from the first instance</p>
<pre><code>'PowSup=PS1(type=Emerson,fw=v.03.05.00)'.partition('=')[0:3:2]
</code></pre> | python|python-2.7 | 3 |
8,442 | 48,146,608 | How to add a variable to a varaiable name | <p>I have Python code that is trying to get the position of a player. However, I always get an error ('cave_' is not defined).</p>
<p>My (error causing)code looks like:</p>
<pre><code>player_pos = cave_(player_pos)[n] #n is a number
</code></pre>
<p>The <code>cave</code> and <code>player_pos</code> variables have be... | <p>Your syntax is wrong for what you are trying to do. Consider this statement:</p>
<pre><code>player_pos = cave_(player_pos)[n]
</code></pre>
<p>First, this will call a function <code>cave_()</code> with the argument <code>player_pos</code>. Next, this will try to extract the <code>n</code>th item from the result.... | python | 0 |
8,443 | 69,704,190 | Node Child Process (Spawn) is not returning data correctly when using with function | <p>I am trying to generate a new score based on the output of my python script.
The python script returning the data correctly and JS program printing correctly
but the problem is when i return the value and print it, it shows undefined</p>
<p>Function Code -</p>
<pre><code>async function generateCanadaScore(creditscor... | <p>You can't <code>await</code> on the event handler. (It returns <code>undefined</code>, so you're basically doing <code>await Promise.resolve(undefined)</code>, which waits for nothing).</p>
<p>You might want to wrap your child process management using <code>new Promise()</code> (which you'll need since <code>child_p... | javascript|python|node.js|function|spawn | 1 |
8,444 | 69,965,065 | Calculate pdf of distribution | <p>I have a normal distribution how can I calculate pdf(probability density function) value from it</p>
<pre><code>#Distribution
from scipy import stats
Distribution = stats.norm(10, 9)
</code></pre> | <pre><code>from scipy import stats
def pdf(x):
return Distribution.pdf(x)
pdf(10)
</code></pre>
<p>--> 0.04432692004460363</p> | python|scipy|statistics|scipy.stats | 2 |
8,445 | 55,977,161 | "NameError: name 'selection' is not defined" Error Showing up | <p>I'm starting coding in my free time and decided to challenge my self by making a small Pokemon esque fighter game. I am currently coding the menu and its options but it has unexpectedly started throwing up a name error.</p>
<p>It works once i move around the positing of the code, such as moving to to be believed tr... | <p>The name <code>selection</code> is <em>local</em> to the function <code>menu</code>. When control will be about to exit the function, this name will be destroyed.</p>
<p>If you want to use the <em>value</em> this name is bound to, you have two choices:</p>
<ol>
<li>Make <code>selection</code> a global variable (an... | python|python-3.x | 1 |
8,446 | 73,431,344 | How to overcome "ValueError: Resolve param in estimatorParamMaps failed" PySpark error? | <p>I am trying to save a grid-searched PySpark <code>TrainValidationSplitModel</code> object, and while tuning the regularization of the logistic regression I'm getting the following strange error:</p>
<pre><code>---------------------------------------------------------------------------
ValueError ... | <p>I solved it. I was calling a previous <code>LogisticRegression</code> model in my <code>ParamGridBuilder</code>:
<code>.addGrid(**lr_1**.regParam, list(np.linspace(0.001, 0.1, 5)))\</code></p>
<p><em>facepalm</em></p> | python|apache-spark|pyspark|apache-spark-mllib|apache-spark-ml | 0 |
8,447 | 73,286,261 | Python Requests / HTTPX - Authenticate All Redirected URL - How To | <p>I wonder if there is a way to authenticate each redirected URL when working with Python modules such as <code>httpx</code> or <code>requests</code>?</p>
<p><strong>Problem Statement</strong></p>
<p>I am trying to connect to an API endpoint under the company network. Due to the company's cyber security measures, the ... | <p>I don't know what requests behavior with regards to auth during redirect is, but the first solution to come to mind is to manually follow the redirects yourself. Put your request in a loop that checks for the 3xx response codes, and handle auth however you want to.</p> | python|api|http|authentication|redirect | 1 |
8,448 | 50,135,808 | python requirements: how to get identical versions? | <p>This question is a consequence of the principal
solution of requirement specifation:</p>
<p><a href="https://stackoverflow.com/questions/50072998">python django pip update problems: how to get compatible versions?</a></p>
<p>I try to synchronize the python requirements between a server
and the local development sy... | <h2>Problem</h2>
<p>This particular module (<code>python-apt</code>) is <a href="https://pypi.org/project/python-apt/#history" rel="nofollow noreferrer">only available on PyPi with version <code>0.7.8</code></a>. However, this release appears to have been a mistake!</p>
<p>One of the developers & Debian package ma... | python|virtualenv|pipenv | 3 |
8,449 | 50,136,482 | Cuda Error Message : F ./tensorflow/core/util/cuda_launch_config.h:127] Check failed: work_element_count > 0 (0 vs. 0) | <p>I'm trying to train a <a href="https://github.com/matterport/Mask_RCNN" rel="nofollow noreferrer">mask rcnn model</a> using Keras on my own dataset on a p2.xlarge EC2 aws instance.</p>
<p>When I launch the training, after a few steps of training:</p>
<pre><code>Epoch 1/1 2/1000 [..............................] ... | <p>I downgraded my tensorflow-gpu package to 1.7.0 and it worked</p> | python|tensorflow | 1 |
8,450 | 50,053,021 | How to parse Xpath expressions in Python? | <p>I need to parse (<strong>not to evaluate</strong>) Xpath expressions in Python to change them, e.g. I have expressions like </p>
<pre><code>//div[...whatever...]//some-other-node...
</code></pre>
<p>and I need to change them to (for example):</p>
<pre><code>/changed-node[@attr='value' and ...whatever...]/another-... | <p>You might be able to use the REx parser generator from Gunther Rademacher. See <a href="http://www.bottlecaps.de/rex/" rel="nofollow noreferrer">http://www.bottlecaps.de/rex/</a> This will generate a parser for any grammar from a suitable BNF, and suitable BNF for various XPath versions is available. REx is a superb... | python|xpath | 2 |
8,451 | 64,036,892 | Filter ForeignKey choices in an Admin Form based on selections in same models ManytoMany Field? | <p>I am making a "matches" model that currently has these fields in them:</p>
<pre><code>event = models.ForeignKey(Event, on_delete=models.RESTRICT)
match_participants = models.ManyToManyField(Wrestler, on_delete=models.RESTRICT, null=True, blank=True,)
match_type = models.CharField(max_length=25, choices=mat... | <p>You can add an extra field in the ManytoMany relationship</p>
<p><a href="https://docs.djangoproject.com/en/2.2/topics/db/models/#extra-fields-on-many-to-many-relationships" rel="nofollow noreferrer">https://docs.djangoproject.com/en/2.2/topics/db/models/#extra-fields-on-many-to-many-relationships</a></p>
<p>models.... | python|django|django-models|django-forms | 0 |
8,452 | 64,081,766 | During a long-running process, will Flask be insensitive to new requests? | <p>My Flask project takes in orders as <code>POST</code> requests from multiple online stores, saves those orders to a database, and forwards the purchase information to a service which delivers the product. Sometimes, the product is not set up in the final service and the request sits in my service's database in an &q... | <p>There's a few different answers that are all valid in different situations. The quick answer is that a job queue like RQ is usually the right solution, especially in the long run as your project grows.</p>
<p>As long as the WSGI server has workers available, another request can be handled. Each worker handles one re... | python|http|flask | 3 |
8,453 | 64,118,353 | How to do matrix multiplication with learnable weights in keras? | <p>I have a model like the one below. I want to add a matrix of learnable weights in the end, which is initialized to the variable <strong>matrix</strong> that I pass to the function create_model.</p>
<p>To get the intuitive idea of what I want to do, imagine the <strong>matrix</strong> is supposed to be the one I pass... | <p>you can simply use a dense layer with no bias to do this multiplication. After the model is built I change the weight of interest with the matrix you provided</p>
<pre><code>def create_model(num_columns, matrix):
inp_layer = Input((num_columns,))
x = Dense(512, activation = 'relu')(inp_layer)
x = De... | python|tensorflow|keras|matrix-multiplication | 1 |
8,454 | 53,206,822 | Count some occurrences grouping data with Pandas | <p>I've a Dataset structured like this: </p>
<pre><code>id date body sentiment
1 1/1/2018 Some Text Positive
2 1/1/2018 Some Text Negative
3 1/1/2018 Some Text None
4 1/2/2018 Some Text Positive
5 1/2/2018 Some Text None
</code></pre>
<p>For each day, I've some ... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.crosstab.html" rel="noreferrer"><code>crosstab</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html" rel="noreferrer"><code>merge</code></a> and left join:</p>
<pre><code>df = df.merge(pd.... | python|pandas|grouping | 5 |
8,455 | 68,703,691 | Convert data types in JSON from Kafka Sparkstreaming | <p>I have a JSON which I am reading from a kafka topic using spark streaming</p>
<pre><code>{"COUNTRY_REGION": "United States", "GROCERY_AND_PHARMACY_CHANGE_PERC": "-7", "PARKS_CHANGE_PERC": "\\\\N", "LAST_UPDATE_DATE": "05:31.7"}
</code>... | <p>If you are not sure about schema of incoming data better not to specify it in first place. Well, we can handle this kind situation if we use <a href="https://docs.confluent.io/platform/current/schema-registry/index.html" rel="nofollow noreferrer">schema registry</a> with data format as avro while <a href="https://st... | python|apache-spark|pyspark|spark-streaming | 0 |
8,456 | 71,499,290 | Sending a Javascript Variable to Flask Python Code without Form-Event | <p>I have a problem with Flask and Javascript. I want to use a website to control a minirobot with joysticks. I have found nippleJS (<a href="https://github.com/yoannmoinet/nipplejs" rel="nofollow noreferrer">https://github.com/yoannmoinet/nipplejs</a>) and included it to my website. I can print the joystick values to ... | <p>Theoretically you could use the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API" rel="nofollow noreferrer"><code>fetch()</code></a> API to send a request to your server which has a JSON body holding the values.</p>
<p>Your <code>on("move")</code> could then look something like this.</p>... | javascript|python|html|flask | 0 |
8,457 | 71,124,765 | Need to update duplicate with existing rows | <p>I need to update(clean) my data by following conditions</p>
<ol>
<li><p>Check if <strong>PS-id</strong> has duplicate values.</p>
</li>
<li><p>Check which has the latest <strong>Date</strong></p>
</li>
<li><p>Update the old row which has the latest <strong>Date</strong> and new <strong>Cam</strong> with the old <str... | <p>IIUC, you want a combination of <a href="https://pandas.pydata.org/docs/reference/api/pandas.core.groupby.DataFrameGroupBy.idxmax.html" rel="nofollow noreferrer"><code>groupby</code>+<code>idxmax</code></a> and <a href="https://pandas.pydata.org/docs/reference/api/pandas.core.groupby.GroupBy.first.html" rel="nofollo... | python|pandas|duplicates | 2 |
8,458 | 71,100,194 | Shuffle a list of numbers, character and symbols | <p>I was in the process of creating a simple program to generate a password with a 'List' consisting of numbers, symbols, and characters. In the process, I wanted to randomize and shuffle them.
I used the random.shuffle method to shuffle the list. My question (Sorry, very new to Python) - why cannot we store the outcom... | <p>random.shuffle() function modifies the original list. This function returns None so it can't store modified list to shuffllefinal var.</p>
<pre><code>mylist = ["apple", "banana", "cherry"]
print("Before shuffle: ", mylist)
random.shuffle(mylist)
print("After shuffle: &quo... | python|variables|methods | 1 |
8,459 | 11,202,168 | Retrieving entry values through separate definition | <p>I'm having problems with the following code (I am a beginner in most things Python related) and am not sure how to use 'self' in this sense. I simply would like to retrieve any values given in the Entry boxes I create (bearing in mind there is a different amount of boxes depending on the if statement) when the start... | <p><code>self</code> only makes sense within a class - it's the conventional way to refer to the "current" instance of the class, ie the one you're actually working with. Outside of a class, you would just use normal parameter names.</p>
<p>I don't know if it would make sense for your functions to be methods of the <c... | python|if-statement|self | 1 |
8,460 | 63,327,763 | Successful summing objects with dictionaries from the same class / It works, but looking for an explanation | <p>I'm looking for help from good people</p>
<p>Why the .copy() has to be inside the __add__ method ? It doesn't work without it.</p>
<pre><code>class Traveler:
def __init__(self):
self.inventory = {}
def add(self, item):
self.inventory[item.lower()] = self.inventory.setdefault(item.lower(), 0)... | <p>In Python when you assign an object (in your case a dictionary) to a variable using the "<code>=</code>" operator <strong>it took the reference</strong>, not a copy of it.</p>
<p>So when you doing <code>total = self.inventory</code>, <code>total</code> and <code>self.inventory</code> <strong>are literally ... | python-3.x|function|dictionary | 0 |
8,461 | 56,760,384 | Pull number of cores dynamically in Dockerfile | <p>Currently I am packaging a web application with Docker, and one line in my <code>Dockerfile</code> is the following</p>
<pre><code>CMD gunicorn -w 4 -b 0.0.0.0:80 main:app
</code></pre>
<p>I was wondering if its possible to change <code>-w 4</code> to something like <code>-w $(num_cores) * 2 + 1</code> </p>
<p>Ho... | <p>If you're in Linux, you can use the <code>nproc</code> command</p>
<pre><code>CMD gunicorn -w $(expr $(nproc) \* 2 + 1) -b 0.0.0.0:80 main:app
</code></pre> | python|docker|gunicorn | 3 |
8,462 | 56,779,830 | How to generate new pages on wxPython notebook with close buttons? | <p>I have the following Toy Example code in which I create two tabs within a <code>wxPython</code> notebook. There is a button to add new pages and within each page I want to have a button that closes the page. However the below code does no action when clicking on the close buttons.</p>
<pre><code>import wx
class Ta... | <p>It could be easier if you use the <code>GetSelection()</code> method of a <code>wx.Notebook</code>. The method returns the index of the currently selected page. After this, you can directly remove the selected page.</p>
<p>Code with comments (####):</p>
<pre><code>import wx
class TabPanel(wx.Panel):
def __ini... | python|wxpython|wxnotebook | 2 |
8,463 | 69,145,417 | np.where on 2D array without masked array or any second argument | <p>I was checking out one code snippets, there was a code like below</p>
<pre><code>z = [[True, False, True],[True, True, True],[False, False, False]]
xz, yz = np.where(z)
print(xz)
print(yz)
</code></pre>
<p>This returns</p>
<pre><code>[0 0 1 1 1]
[0 2 0 1 2]
</code></pre>
<p>If I make</p>
<pre><code>z = [[True, Fals... | <p>If you read carefully the documentation on <a href="https://numpy.org/doc/stable/reference/generated/numpy.where.html" rel="nofollow noreferrer"><code>np.where</code></a>, you find that it's equvivalent to <code>np.asarray(condition).nonzero()</code> in case you only provide the condition parameter, so the behaviour... | python|arrays|numpy|numpy-ndarray|image-masking | 1 |
8,464 | 72,491,067 | How close does my testing accuracy need to be to my training accuracy for ML model | <p>I've built a Random Forrest ML model. My train accuracy is around 97% and my test accuracy is around 85%.</p>
<p>Is this normal or is this too big of a difference? I know there is probably overfitting, but if the test accuracy is high at 85%, does it matter?</p>
<p>Thank you.</p> | <p>check performance by using cross validation. cross validation helps you see how your model will perform with new data.
<a href="https://stats.stackexchange.com/questions/111968/random-forest-how-to-handle-overfitting">https://stats.stackexchange.com/questions/111968/random-forest-how-to-handle-overfitting</a></p>
<... | python|machine-learning|random-forest | 1 |
8,465 | 62,299,038 | Pyqt5 Entry don't appear | <p>I would like to create a simple GUI that assign to each name another name randomly. But the problem is that, after the user decide how many name create, it should show the QLineEdit tag, but i can't see that. There aren't errors. Obviusly,the application is not over. The problem is only the QLineEdit tag. Here ther... | <p>Your QLineEdits are simply invisible; just add:</p>
<pre><code>self.entry[-1].show()
# or self.entry[-1].setVisible(True)
</code></pre>
<p>There's a (discrete) note about that in <a href="https://doc.qt.io/qtforpython/PySide2/QtWidgets/QWidget.html#PySide2.QtWidgets.QWidget" rel="nofollow noreferrer">Qwidget's doc... | python-3.x|pyqt5 | 2 |
8,466 | 62,432,392 | what is difference between d[n:m][n:m] and df[n:m][m]? | <p>I'm trying print values by using the following code I'm getting the output</p>
<pre><code>print(df[2:5][1:3])
0
46 4
45 5
</code></pre>
<p>But for the following code I'm getting error</p>
<pre><code>print(df[2:5][2])
KeyError: 2
</code></pre>
<p>I'm using following dataframe</p>
<pre><code>df = pd.DataFra... | <p>df[n:m][m] - [m] will be just a line.</p> | python-3.x|pandas | 0 |
8,467 | 62,269,988 | Create a new pandas column with repeating a value according with another column | <p>I have a table like this</p>
<pre><code> times v2
0 4 10
1 2 20
2 0 30/n30
3 1 40
4 0 9
</code></pre>
<p>What I want if change the values of v2 when times != 0, and the change consists in adding "\0" as many times as the times columns says.</p>
<pre><code> times... | <p>You can do </p>
<pre><code>df.v2+=df.times.map(lambda x : x*"\n0")
df
Out[325]:
times v2
0 4 10\n0\n0\n0\n0
1 2 20\n0\n0
2 0 30/n30
3 1 40\n0
4 0 9
</code></pre> | python-3.x|pandas | 2 |
8,468 | 62,122,175 | Python Tkinter background | <pre><code>canvas = tk.Canvas(window, width=800, height=600, bg="black") # PEP8: space after comma
canvas.pack()
</code></pre>
<p>Do anyone know how I could import a image from google to set as a background in canvas?</p> | <p>First, download the image as a <code>.png</code>. If you have the latest version of tkinter, then the following will work. </p>
<p>Write this code: </p>
<pre class="lang-py prettyprint-override"><code>canvas = tk.Canvas(window, width=800, height=600, bg="black") # PEP8: space after
canvas.pack()
p = tk.PhotoImage... | python|canvas|tkinter | 1 |
8,469 | 31,596,850 | NumPy: Importing a Sparse Matrix from R into Python | <p>I have a matrix in R that is very large and sparse, created with the 'Matrix' package, and I want to handle in python + numpy. The R object is in the csc format, and if I export it using the function writeMM in the Matrix package, the output looks something like this:</p>
<pre><code>%%MatrixMarket matrix coordinate... | <p>You can use <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.io.mmread.html#scipy.io.mmread" rel="nofollow">scipy.io.mmread</a> which does exactly what you want.</p>
<pre><code>In [11]: mmread("sparse_from_file")
Out[11]:
<4589x17366 sparse matrix of type '<class 'numpy.float64'>'
wi... | numpy|matrix|scipy|sparse-matrix | 4 |
8,470 | 15,952,500 | Thread that returns value when it succeeds or fails? | <p>I have a function that opens up a process and sends commands, gets results and based on this runs more commands. At any stage it could fail and return or at the end it prints out a success statement. Now this all happens on the main thread so my program is stalled while this happens (takes about 6 minutes). How do y... | <p>You've created a background <em>thread</em> in your Python process but it seems you want a background <em>process</em> in your shell.</p>
<p>Python process won't exit until all non-daemonic threads are complete (it joins them on shutdown).</p>
<p>You could put the whole script into background in the shell:</p>
<p... | python | 1 |
8,471 | 25,161,689 | Django Development - Admin CSS file 404 | <p>I'm using <a href="https://docs.djangoproject.com/en/1.6/howto/static-files/" rel="nofollow">this guide</a> to attempt to get this working. Basically, I'm exploring django 1.6 (with python 2.7.6 on Mac OS X Yosemite beta), still working with the stock development server. I'm trying to include a CSS file to override ... | <p>Yes it won't work because Django does not serve by default static assets, in order to have static assets served (mind though this should be the case only for local dev) in your main urls.py file add this to the top:</p>
<pre><code>from django.contrib.staticfiles.urls import staticfiles_urlpatterns
</code></pre>
<p... | python|django|django-admin | 0 |
8,472 | 60,244,402 | Converting from Ordinal Time to Date-Time in Python | <p>I want to convert a precise ordinal time array (see below) to date-time format (YYYY-MM-DD hh:mm:ss.sss) in anaconda/python 3. I cannot find any solutions to this problem that considers the precision of the original data.</p>
<p>The ordinal time array looks like:</p>
<pre><code>[[733414.07083333]
[733414.07430556... | <p>I was facing a similar issue and found a faster way to convert from ordinal to datetime, which is done in your first function.</p>
<pre><code>import datetime
def OrdinalToDatetime(ordinal):
plaindate = datetime.date.fromordinal(int(ordinal))
date_time = datetime.datetime.combine(plaindate, datetime.datetime.... | python|time | 1 |
8,473 | 2,347,266 | Parameters not getting passed properly | <p>Here's an excerpt of my code:</p>
<pre><code>def listFrom(here):
print "[DBG] here: " + here
def book(here, there, amount):
print "[DBG] here: " + here + "; there: " + there + "; amount: " + str(amount)
# Code that takes input and stores it into the string input
# Yes, I know this is dangerous, but it's ... | <p>This code works without problems in Python 2.6 on Linux/x86-32:</p>
<pre><code>>>> def listFrom(here):
... print "[DBG] here: " + here
...
>>> def book(here, there, amount):
... print "[DBG] here: " + here + "; there: " + there + "; amount: " + str(amount)
...
>>> book('LON', 'M... | python|eval | 0 |
8,474 | 66,997,198 | Elements take too much time to load in a popup div | <p>Trying to scrape subscribers data from this page. <a href="https://happs.tv/@Pablo" rel="nofollow noreferrer">https://happs.tv/@Pablo</a> .This is exactly like the facebook's likes box, which opens when we click on likes on a post. I need to scroll inside the pop-up which shows all those who liked a post. That works... | <ol>
<li><p>The response from an API should be less than 3s/request. If your request takes too much data, please load with "SELECT top 10". You should ask your team for performance first.</p>
</li>
<li><p>You can try FluentWait as</p>
<pre><code>driver = Firefox()
driver.get("http://somedomain/url_that_... | python|selenium|web-scraping | 0 |
8,475 | 72,326,614 | Django: How to automatically update a model instance everytime another model instance is updated | <p>In online shop projects, I have a model called Order (and this model stores order instances) and a model called Points. The model Points stores bonus points which are collected by the users when they make orders. But the order may be cancelled, so I would like to be able to monitor when an order is being cancelled (... | <p>Use Django signals: <a href="https://docs.djangoproject.com/en/4.0/ref/signals/#django.db.models.signals.post_save" rel="nofollow noreferrer">https://docs.djangoproject.com/en/4.0/ref/signals/#django.db.models.signals.post_save</a></p>
<p>You can detect that Order instance was saved and which field exactly was updat... | python|sql|django|postgresql|web | 0 |
8,476 | 50,724,765 | How to retrieve all historical public tweets with Twitter Premium Search API in Sandbox version (using next token) | <p>I want to download all historical tweets with certain hashtags and/or keywords for a research project. I got the Premium Twitter API for that. I'm using the amazing <code>TwitterAPI</code> to take care of auth and so on.</p>
<p>My problem now is that I'm not an expert developer and I have some issues understanding ... | <p>First of all, <a href="https://github.com/geduldig/TwitterAPI" rel="nofollow noreferrer">TwitterAPI</a> includes a helper class that will take care of this for you. <code>TwitterPager</code> works with many types of Twitter endpoints, not just Premium Search. Here is an example to get you started: <a href="https://g... | python-3.x|api|twitter | 0 |
8,477 | 50,401,692 | Python 3: Saving API Results into CSV | <p>I'm writing a script which requires a daily updated CSV source file which lists many movie details and have decided to use Python3 to create and update it even though I don't know too much about it.</p>
<p>I believe I've got the code down to pull the information via TheMovieDB.org's API that I need, but currently c... | <pre><code>import json
import http.client
import requests
import csv
conn = http.client.HTTPSConnection("api.themoviedb.org")
payload = "{}"
conn.request("GET", "/3/discover/movie?page=20&include_video=false&include_adult=false&sort_by=primary_release_date.desc&language=en-US&api_key=XXXXXXXXXXXXXXX... | python-3.x|api|csv | 0 |
8,478 | 26,895,207 | How is a unique constraint across three columns defined? | <p>The following <code>EventInvitation</code> model is a simple invitation for one event, sent from a user to another user. I would like to ensure that the invitations are unique across three columns: to_user, from_user and event.</p>
<pre><code>class EventInvitation(db.Model):
__tablename__ = 'event_invitations'
... | <p>You need to add the constraint to the table, not the model. To do this using declarative:</p>
<pre><code>class EventInvitation(db.Model):
# ...
__table_args__ = (
db.UniqueConstraint(event_id, from_id, to_id),
)
</code></pre>
<p>If the table has already been created in the database, you'll nee... | python|sqlalchemy|flask-sqlalchemy | 4 |
8,479 | 26,855,930 | Can't figure out how to print * & whitespace vertically instead of hoirzontally | <p>I tried looking at other threads but still couldn't figure it out.</p>
<p>I am using this code:</p>
<pre><code>numbers = [5,1,5,2,4]
for i in numbers:
for x in range(0,i):
print "*",
print""
</code></pre>
<p>It prints:</p>
<pre><code>* * * * *
*
* * * * *
* *
* * * *
</code></pre>
<p>etc.</p>
<p>I ... | <p>Indeed, you can even use <code>*</code> for 3 different things!</p>
<pre><code>>>> from itertools import izip_longest
>>> for x in reversed(list(izip_longest(*['*'*n for n in numbers], fillvalue=' '))):
... print ' '.join(x)
...
* *
* * *
* * *
* * * *
* * * * *
</code></pre> | python|python-2.7 | 2 |
8,480 | 57,922,249 | Python testing: How do I mock outside of the testing scope? | <p>Currently dealing with some legacy python code. I need to test one of the functions, <code>function foo</code> . Now to do that I need to mock the return value given by another function that's called by <code>foo</code> which is <code>function bar</code>.</p>
<p>However both of these are outside of my testing packa... | <p>A simple example:</p>
<p>foo_and_bar_package/foo_and_bar_module.py</p>
<pre><code>def bar():
return 5
def foo():
return 2 * bar()
</code></pre>
<p>test_foo_and_bar_module.py</p>
<pre><code>from unittest import TestCase
from unittest.mock import patch
from foo_and_bar_package.foo_and_bar_module import ... | python|python-mock | 2 |
8,481 | 57,859,659 | Removing similar items from 2 different lists | <p>Is there a more Pythonic way to execute this code?</p>
<pre><code>sim_inits = [1,100, 12, 3520, 1250]
prod_inits = [2, 101, 13, 14, 3521, 1500]
for t in range(len(sim_inits)-1):
sim_loop_done = False
for s in sim_inits[:]:
if sim_loop_done == True:
continue
prod_loop_done = Fal... | <p>You can skip one of the loops, and you can use <code>break</code> instead of <code>continue</code> to get out of the other one early without using the cumbersome flags you're currently using.</p>
<p>List slicing is pretty expensive - especially in the case of <code>prod_inits</code>, where you're duplicating the en... | python|list | 1 |
8,482 | 57,418,601 | What is the actual keysym for "<Control-->" in Tkinter | <p>I'm trying to make a text editor using Python 3.7 and Tkinter. I'm having trouble on my keyboard shortcuts. Here is the code for the keyboard shortcuts:</p>
<pre class="lang-py prettyprint-override"><code># Keyboard shortcuts
self.master.bind("<Control-o>", lambda key: self.open())
self.master.bind("<Contr... | <p>The error is in this line</p>
<pre><code>self.master.bind("<Control-->", lambda key: self.zoomIn())
</code></pre>
<p>It should be</p>
<pre><code>self.master.bind("<Control-minus>", lambda key: self.zoomIn())
</code></pre> | python|python-3.x|tkinter | 1 |
8,483 | 24,094,338 | SQLAlchemy how to sets key attribute of hybrid_property | <p>I'm using a hybrid_property to combine or manipulating column value. And i want to get a 'key' attribute of this hybrid_property columns. Here the code.</p>
<pre><code>class Foo(Base):
name = Column(String)
address = Column(String)
city = Column(String)
@hybrid_property
def full_address(self... | <p>Finally i've got the answer</p>
<p>@hybrid_property
def full_address(self):
if isinstance(self, Foo):
return '{}, {}'.format(self.address, self.city)
else:
return Column('full_address', String)</p> | python|sqlalchemy|hybrid | 0 |
8,484 | 15,027,555 | Make a listbox bigger than default? | <p>I'm just wondering how to make a listbox bigger than the original size it enters as. </p>
<p>It's probably simple but I cant find how to do it.</p>
<p>My code is below:</p>
<pre><code>frame_1 = Frame(myGUI)
frame_1.place(x=75, y=300)
scrollbar = Scrollbar(frame_1)
scrollbar.pack(side=RIGHT, fill=Y)
listbox_1 = Li... | <p>You should be able to change it just by setting the appropriate value for <code>listbox_1</code>, i.e.:</p>
<pre><code>listbox_1['height'] = something
listbox_1['width'] = something_else
</code></pre>
<p>Or, by using the <a href="http://effbot.org/tkinterbook/listbox.htm#Tkinter.Listbox.config-method" rel="nofollo... | python|tkinter | 2 |
8,485 | 54,809,447 | Saving values in a session | <p>I need your help.</p>
<p>Through the URL I get Data for the position and that value is getting passed to a python script.</p>
<p>The first time everything is fine, they value 200 comes in and the stepper make 200 steps and reaches the defined position. The next time, another value is requested like 100 or maybe -1... | <p>This might do the trick:</p>
<pre><code>session_start();
$valueThatYouFetch = $_GET["value"]; // Fetch your value
if (isset($_SESSION['test'])) { // If session exist
$_SESSION['test'] = $_SESSION['test'] + $valueThatYouFetch; // add old value to new one
} else { // if session does not exist
$_SESSION['test'] =... | php|python|session|web | 1 |
8,486 | 73,758,160 | Some Questions about QMediaPlayer() in PyQt6 | <p>I'm trying to play sound with <code>QMediaPlayer()</code></p>
<p><strong>Code 1</strong>: this work fine.</p>
<pre class="lang-py prettyprint-override"><code>import sys
from PyQt6.QtCore import QUrl
from PyQt6.QtMultimedia import QAudioOutput, QMediaPlayer
from PyQt6.QtWidgets import QApplication
app = QApplicatio... | <p>After the <code>player.play()</code> method is called it exits the function and the media player is garbage collected. You will need to keep a reference to the <code>player</code> by returning it if you would like it to live beyond the scope of the function call.</p>
<p>for example:</p>
<pre><code>import sys
from P... | python|pyqt | 1 |
8,487 | 24,919,240 | Use python to call a batch script that sets env variables and run another program that uses them | <p>I need to call a batch script from Python that sets environment variables and then use those environment variables to complete the execution of other programs. I am in a windows environment running python.</p>
<p>I cannot call <code>Popen("setupEnv.bat")</code> and then call <code>Popen("command args")</code> becau... | <p><strong>This may not be exactly what you're looking for</strong><BR>
You could get the value of the var's then store them in a file.
After that get the contents of the text file with the other program/language. Just do that :)<BR><BR><BR>
Hopefully that answered your question!</p> | python|windows|batch-file|cmd|subprocess | 0 |
8,488 | 38,463,194 | sqlite3 python 2.7 how to enable more detailed error reporting (exceptions) from sqlite3? | <p>I am trying to insert multiple rows with the <code>executemany</code> function. My complete code is given at the end.</p>
<p>The exception I get is </p>
<pre><code>sqlite3.IntegrityError: column carname is not unique
</code></pre>
<p>I wish I could a more detailed error report giving the offending values that cau... | <p>I would argue that since you have placed a unique constraint on one of the column names, unless you have pre-vetted the data you should not be using <code>executemany</code>.<br>
Instead, use a <code>for ... loop</code> to loop over the data and use an <code>execute</code> within a <code>try .. except</code> stateme... | python-2.7|exception|error-handling|sqlite | 1 |
8,489 | 31,058,504 | Spark 1.4 increase maxResultSize memory | <p>I am using Spark 1.4 for my research and struggling with the memory settings. My machine has 16GB of memory so no problem there since the size of my file is only 300MB. Although, when I try to convert Spark RDD to panda dataframe using <code>toPandas()</code> function I receive the following error:</p>
<pre><code>s... | <p>You can set <code>spark.driver.maxResultSize</code> parameter in the <code>SparkConf</code> object:</p>
<pre><code>from pyspark import SparkConf, SparkContext
# In Jupyter you have to stop the current context first
sc.stop()
# Create new config
conf = (SparkConf()
.set("spark.driver.maxResultSize", "2g"))
# ... | python|memory|apache-spark|pyspark|jupyter | 58 |
8,490 | 43,532,081 | Is there a way to get better antialiasing with scipy zoom | <p>I'm making a mouse tracking script, and I just tried writing my own resampling since I want the output to merge all recorded resolutions, but I couldn't iron out some bugs so gave up and tried out scipy for it.</p>
<p>It almost works perfectly, but it looks bad at the same time, especially if making an image smalle... | <p>It turns out that upscaling with scipy, combining then converting to RGB, then downscaling with PIL, is exactly what was needed.</p>
<p>The upscaling was done to 4k, though it still looked almost the same (just slightly more jagged) at 1080p. From the list of 4k arrays, I could then combine the results by getting t... | python|image|scipy | 1 |
8,491 | 54,482,088 | Using knn to predict values from another DataFrame (Python 3.6) | <p>I created a DataFrame with geological data from a well log, then I created a new column to label each row with a name according to its differents properties. That means: each row now has a rock name.</p>
<p>My question: I already trained my first DataFrame with all the data that I have and now I want to predict the... | <p>The error says that KNN expects arrays with a dimension lower or equal to 2. However in your script, your properties, like <code>gammaray</code> are <code>numpy</code> arrays.<br>
When you write <code>[[gammaray, neutron, density, swat, vshale]]</code>, in your <code>knn.predict</code> call, the double brackets add ... | python|pandas|machine-learning|knn|predict | 1 |
8,492 | 39,093,226 | PyQt5 QListView sluggish first drag/drop on windows - python 3.5/3.4 32bit, pyqt5 from sourceforge | <p>I have installed 32bit Python 3.4 and 3.5 and PyQt5 on our windows 7 work machine via the executable available from <a href="https://sourceforge.net/projects/pyqt/" rel="nofollow">https://sourceforge.net/projects/pyqt/</a>, however I now find that when I run my simple drag and drop test code it is very sluggish movi... | <p>Ran same code on another windows 7 computer with same packages installed. The issue is not seen there, so is obviously a problem with something specific to this machine rather than the code I've written/versions of python I'm using/version of pyqt.</p> | python|windows|drag-and-drop|pyqt5 | 1 |
8,493 | 34,363,186 | Getting sub directories list in a text file and append that txt file with new subdirectory name | <p>I am trying to write a script which will list down all subdirectories in a directory into a txt file. </p>
<p>this script will run every 1 hour through cron job so that i can append to the txt file already created in previous run and add new subdir names. </p>
<p>For eg:</p>
<pre><code>/Directory
/subdir1
/su... | <p>To get the immediate sub-directories in the parent directory use <code>os.walk('path/to/parent/dir').next()[1]</code>.</p>
<p><code>os.walk().next()</code> gives a list of lists as [current_dir, [sub-dirs], [files] ] so <code>next()[1]</code> gives sub-directories</p>
<p>opening the file with 'a+' will allow you t... | python|python-2.7|os.walk | 1 |
8,494 | 40,682,941 | installing fastkde library in Python | <p>I want to install fastkde library and I did actually everything on web but I am yet able to install this. I constantly get this error in terminal:</p>
<pre><code>Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-4ff4dzcb/fastkde/
</code></pre>
<p>Can anybody help me with this?</p> | <p>If you've <code>pip</code> installed which is true for all distributions downloaded from <a href="https://python.org/" rel="nofollow noreferrer">here</a>, then just key in the commands in your terminal given below.</p>
<pre><code>pip3 install fastkde
</code></pre> | python-3.x | 0 |
8,495 | 28,324,839 | Error importing statsmodel.api. cannot import specfun | <p>I've imported statsmodel.api for python 1000 times. Just started getting a random error upon import. Anyone had this error? Code is below. </p>
<p>I am using windows and my python is updated via the conda package. </p>
<p>Thanks all. </p>
<pre><code>`import statsmodels.api as sm`
</code></pre>
<hr>
<pre><code>I... | <p>I was getting the same issue related to a bad or missing <code>scipy.special.specfun</code> in scipy 0.15.1 . Reverting my version of scipy to 0.14.0 was a workaround and resolved my issue. Using conda, you can revert using
<code>conda install scipy=0.14.0</code> Installing from other packages on binstar will al... | python|scipy|statsmodels | 2 |
8,496 | 32,655,241 | Understanding numpy formatting | <p>I have been reading the numpy array formatting <a href="http://docs.scipy.org/doc/numpy/user/basics.rec.html#structured-arrays" rel="nofollow">documentation</a> and I cannot achieve what I want to do.</p>
<p>Given a matrix array where each column represents a different field, I want to format each column as integer... | <p>What, exactly, is the source of <code>Bus</code>? When I cut and paste your string </p>
<pre><code>In [50]: Bus = array([[1, 1, 97.6, 44.2, 0, 0, 2, 1.0393836, -13.536602, 345, 1, 1.06, 0.94],
</code></pre>
<p>...345, 1, 1.06, 0.94]])</p>
<p>I get an array that is all floats:</p>
<pre><code>In [51]: Bus
Out[51]... | python-3.x|numpy | 1 |
8,497 | 47,215,825 | is there a faster way to write similar test cases for Django views? | <p>Basically, I realize that I am writing the same test case (<code>test_update_with_only_1_field</code>) for a similar URL for multiple models</p>
<pre><code>from django.test import RequestFactory, TestCase
class BaseApiTest(TestCase):
def setUp(self):
superuser = User.objects.create_superuser('test', 'test@api.c... | <p>I guess what you want is "parameterized tests", standard <code>unittest</code> could do this with <a href="https://pypi.python.org/pypi/parameterized" rel="nofollow noreferrer">parameterized</a> package:</p>
<pre><code>import unittest
from parameterized import parameterized
class SomeModelApiTests(unittest.TestCas... | python|django|python-unittest|parameterized-tests | 5 |
8,498 | 46,998,700 | mwclient - browsebysubject - SMW | <p>I have been toying around with <a href="https://github.com/mwclient/mwclient" rel="nofollow noreferrer">mwclient</a> to query a wiki installations running the SMW extension.</p>
<p>It is quite convenient to have the "ask" method available to the mwclient.client.Site.
However I want to take my queries further and us... | <p>The <a href="http://mwclient.readthedocs.io/en/latest/reference/site.html#mwclient.client.Site.api" rel="nofollow noreferrer">generic API method</a> is the way to go:</p>
<p><code>site.api('browsebysubject', subject='Bogue_Banks')</code></p> | python|mediawiki-api|semantic-mediawiki | 1 |
8,499 | 46,766,662 | Python: compare items within two different tfidf matrices of different dimensions | <p>I want to use TfidfVectorizer() on a file that contains many lines, each a phrase. I then want to take a test file with a small subset of phrases, do TfidfVectorizer() and then take the cosine similarity between the original and the test file so that for a given phrase in the test file, I retrieve the top N matches ... | <p>Fit the <code>TfidfVectorizer</code> with data from corpus, then transform the test data with the already fitted vectorizer (i.e., do not call <code>fit_transform</code> twice):</p>
<pre><code>tfidf_matrix = tf.fit_transform(corpus)
tfidf_matrix2 = tf.transform(test)
</code></pre> | python|scikit-learn|tf-idf|cosine-similarity | 4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.