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 |
|---|---|---|---|---|---|---|
1,600 | 65,394,235 | How to compare last value to previous 6 values in pandas dataframe? | <p>Is there a way to find out if the last value is in the lower 50% range of the previous six days values? I want to add another column that shows yes or no. I tried sorting the previous six to get the middle value, but could not compare it to last and/or make it iterate to populate the new column. My data looks like ... | <p>Understanding your question as asking for the ratio of the previous day's closing price to the average of the previous six days, I created the following code. Sort the closing prices of the retrieved stocks in descending order. In a new column, use the rolling function to calculate the six-day average and add it. Th... | python|pandas|dataframe|finance|technical-indicator | 0 |
1,601 | 65,089,884 | Jupyter notebook kernel different from conda environment | <p>I'm encountering problems while trying to reproduce a conda environment in a jupyter notebook kernel.
I've created a conda environment, <code>mlflow</code>, and by activating it, I can import mlflow, as you can see below:</p>
<pre><code>[ 12:36:18 ] ~ base ❯ conda activate mlflow
[ 12:36:21 ] ~ mlflow ❯ python
Pytho... | <p>Try giving the full conda python path and see if that resolves it:</p>
<pre><code>C:\Users\<username>\anaconda\envs\<environment-name>\bin\python -m ipykernel install --name mlflow
</code></pre>
<p>The reason ipykernel was not found was because it was not installed in the right python environment. Using ... | python|anaconda|jupyter|conda | 1 |
1,602 | 65,246,005 | Best method to measure CPU time in Python3? | <p>I am curious what the current best method is for measuring CPU time in Python3. To be clear, the result I want is the total CPU clock time that the program has been running (i.e. not wall clock time).</p>
<p>I have used the <code>time</code> module for this in the past, but it is unclear to me if this is still the r... | <p>For cpu time <code>time.process_time()</code> or <code>time.thread_time()</code> is suitable - depending on what you are measuring and whether you are using multi-threading or not.</p>
<p><code>time.clock()</code> is deprecated</p>
<p>Be mindful of I/O. If you are doing blocking I/O, it will get counted in CPU time.... | python|python-3.x|timing|cpu-time | 1 |
1,603 | 71,758,555 | How to run some testcases in parallel and some serially in pytest? | <p>I have a few hundreds of tests and I want some of them to run in parallel, and some to run serially, within the same run.</p>
<p>I am aware how to run them all parallelly, or all serially, but not combined.</p>
<p>Is there any way to do this in pytest?</p> | <p>There are a few different ways to achieve this using the <code>pytest-xdist</code> plugin specifying <code>--dist</code> with <code>loadscope</code>, <code>loadfile</code>, or <code>loadgroup</code>.</p>
<p>Refer to the docs for details: <a href="https://pypi.org/project/pytest-xdist/#running-tests-across-multiple-c... | python|pytest | 1 |
1,604 | 10,321,036 | python numpy recarray join | <p>Is there no "join" function in numpy recarrays? I see matplotlib has something and there is a concatenate but this is not a solution. I want a fast join in numpy/scipy or understand why it is not there. </p> | <p>After some digging I found this slightly buried library. I think it might be doing what I need ... curious to hear other answers as well. If this is the best solution it is NOT very well documented. I'm not sure how to contribute docs:</p>
<pre><code>import numpy as np
import numpy.lib.recfunctions as rfn
import n... | python|numpy|join|recarray | 0 |
1,605 | 10,367,020 | compare two lists in python and return indices of matched values | <p>For two lists a and b, how can I get the indices of values that appear in both? For example,</p>
<pre><code>a = [1, 2, 3, 4, 5]
b = [9, 7, 6, 5, 1, 0]
return_indices_of_a(a, b)
</code></pre>
<p>would return <code>[0,4]</code>, with <code>(a[0],a[4]) = (1,5)</code>.</p> | <p>The best way to do this would be to make <code>b</code> a <code>set</code> since you are only checking for membership inside it.</p>
<pre><code>>>> a = [1, 2, 3, 4, 5]
>>> b = set([9, 7, 6, 5, 1, 0])
>>> [i for i, item in enumerate(a) if item in b]
[0, 4]
</code></pre> | python|list|match|indices | 28 |
1,606 | 62,854,320 | Pandas new dataframe based on combinations of all values in a column | <p>I have collected location data from buses over some time and want to build a model predicting when a bus will arrive at a certain stop.</p>
<p>In its most simple form, I have a DataFrame like this:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'station': ['Station 1', 'Station 2', 'Station 3', 'Station 4'],... | <p>Convert "station" to an ordered categorical column:</p>
<pre><code>df['station'] = pd.Categorical(df['station'], ordered=True).codes
</code></pre>
<p>You can now do a cross join and filter:</p>
<pre><code>tmp = df.assign(key=1)
(tmp.merge(tmp, on='key', suffixes=('_prev', '_next'))
.drop('key', 1)
... | python|pandas | 0 |
1,607 | 67,338,180 | Python Ray: Objects pinned in memory unable to evict | <p>I have created a custom NSGA2 algorithm and I'm using ray for my evaluator. I've noticed that the objects I retrieve from the ray task are being pinned and I've tried doing a couple things such as copying the returned objects and deleting the reference to the original, using garbage collector, or just deleting all r... | <p><code>PINNED_IN_MEMORY</code> means that somewhere, the code is holding a pointer to shared memory. A common case where this can happen is when the object's value is a numpy array, which are accessed with zero copies. So most likely, the problem is this line:</p>
<pre class="lang-py prettyprint-override"><code> ... | python|memory-management|genetic-algorithm|ray | 0 |
1,608 | 71,317,141 | optimizing multiple loss functions in pytorch | <p>I am training a model with different outputs in PyTorch, and I have four different losses for positions (in meter), rotations (in degree), and velocity, and a boolean value of 0 or 1 that the model has to predict.<br />
AFAIK, there are two ways to define a final loss function here:</p>
<p>one - the naive weighted s... | <p>This is not a question about programming but instead about optimization in a multi-objective setup. The two options you've described come down to the same approach which is a linear combination of the loss term. However, keep in mind there are many other approaches out there with dynamic loss weighting, uncertainty ... | python|optimization|pytorch|loss-function|loss | 2 |
1,609 | 71,274,501 | X,Y Coordinates Convert | <p>I have written a program in which I am using pyautogui for autoclicking</p>
<p>My code</p>
<pre><code>import pyautogui, time
time.sleep(5.5)
pyautogui.click(x=443, y=178)
time.sleep(0.5)
</code></pre>
<p>but the x, y coordinates which I am using are according to my monitor size which is 1920x1080</p>
<p>My Question... | <p>Hope this helps:</p>
<pre><code>import pyautogui, time
xCoef = 1280/1920
yCoef = 720/1080
def clickFunc(x,y):
pyautogui.click(x=int(xCoef*x), y=int(y*yCoef))
time.sleep(5.5)
clickFunc(443,178)
time.sleep(0.5)
</code></pre> | python|math | 0 |
1,610 | 11,024,089 | Python C extension with data file | <p>I'm trying to write and install a C Extension for Python which has to load a 120MB data file. Using distutils <code>package_data</code> argument I've got it installing the data file correctly to the same folder as the extension module. However, the C code doesn't know how to find the data file.</p>
<p>I can hard ... | <p>So I came up with a somewhat better solution on my own and thought I'd post it in case it helps anyone else.</p>
<p>My project consists of a package (<code>my_module</code>) with a C extension. The installation contains <code>_my_extension.so</code>, <code>__init__.py</code>, and <code>datafile.dat</code>. In rel... | python|c|distutils | 0 |
1,611 | 56,666,168 | How to filter one Many2one field based on value of another in odoo | <p>I have these fields in my model:</p>
<pre><code>seller = fields.Many2one('res.partner', string="Select Seller",domain="[('supplier','=',True)]")
products= fields.Many2one('product.template', string="Select Product" )
</code></pre>
<p>Now, i need to filter the second field as the user chooses a seller(first field)
... | <p>In your case you can't use a "dynamic" domain but more of a pre-defined domain on product IDs.</p>
<pre class="lang-py prettyprint-override"><code>@api.onchange('seller')
def onchange_field_seller(self):
if self.seller:
# filter products by seller
product_ids = self.seller.product_details.ids
... | python|odoo|odoo-12 | 5 |
1,612 | 69,709,320 | pyautogui unable to recognize app opened by subprocess.Popen | <p>I have a python-based GUI application running on Windows.
Pyautogui able to locate the button if I manually launch the application, for example, in CMD, run <code>python myapp.py</code></p>
<p>However, when I included the app opening operation in my script using <code>subprocess.Popen</code>, pyautogui is no longer ... | <p>You put the <em>time.sleep(5)</em> after the print you want. You need to <strong>put that command after the app opens and give it a time so that the script doesn't run before the app is visible on screen</strong>. It's just like <em>Jasonharper</em> said in his comment.</p>
<p>It should be something like:</p>
<pre><... | python|pyautogui | 0 |
1,613 | 17,734,383 | Using aggregators (Min, Max, Avg) inside South migrations | <p>I want to perform <code>annotate</code>/<code>aggregate</code> inside migration, because my data needs to be prepared before schema modifications. South does not permit import aggregators fro <code>django.db.models</code> - it throws an error on migration application stage. So is there some way to do this in South?<... | <p>This is kind of a worst case scenario, but one option would be to make South just exec the SQL directly for you.</p>
<p>From their docs: <a href="https://south.readthedocs.org/en/latest/databaseapi.html#db-execute" rel="nofollow">https://south.readthedocs.org/en/latest/databaseapi.html#db-execute</a></p>
<p>Gettin... | python|django|django-south|database-migration | 0 |
1,614 | 60,975,877 | Implementing Heap's Algorithm for Permutations in Python | <p>I'm trying to implement Heap's algorithm in python, but having trouble with it repeating some of the solutions. I'm stumped with where the bug is at. Here is the implementation:</p>
<pre><code>import copy
def _permute(l, n):
if n == 1:
print(l)
else:
for i in range(n - 1):
# not... | <p>You were placing your recursive call in the wrong place, this should do the trick (and you shouldn't use the copy):</p>
<pre><code>def _permute(l, n):
if n == 1:
print(l)
else:
_permute(l, n - 1)
for i in range(n - 1):
if n % 2 == 0:
l[i], l[n - 1] = l[n -... | python|algorithm|permutation|heaps-algorithm | 2 |
1,615 | 66,173,260 | Fill tables in a template Word with Python (DocxTemplate, Jinja2) | <p>I am trying to fill with Python a table in Word with DocxTemplate and I have some issues to do it properly. I want to use 2 dictionnaries to fill the data in 1 table, in the figure below.</p>
<p><a href="https://i.stack.imgur.com/E4FCV.png" rel="nofollow noreferrer">Table to fill</a></p>
<p>The 2 dictionnaries are f... | <p>Finally I found a solution for this problem. Here it is.
Instead of using 2 dictionnaries I created 1 dictionnary with this strucuture :</p>
<pre><code>Dico = { Champ : [Occu , Tables] }
</code></pre>
<p>The full code for creating the table is detailed below :</p>
<pre><code>from docxtpl import DocxTemplate
documen... | python|ms-word|jinja2|word-template | 0 |
1,616 | 66,255,643 | How to overlay an image in a for loop in Django | <p>I'm trying to create an event page where admin can post events which will be edited or deleted from time to time. The idea is there are in cards and when the user click on the cards an image overlay will show up.<br>
While in the past I have used HTML and JavaScript to create this overlay my problem now using a for... | <p>Got to realised the error was i had the ID inside a loop creating more than one div with the same ID plus i was trying to use JavaScript within python loop.
So the solution I thought is to create a separate page for each card every time I click in the image and have a plain overlay outside the loop with the image cl... | javascript|python|onclick|overlay | 0 |
1,617 | 68,885,629 | how to see ssl certificate of peer in python | <p>hello i would like to know what are the steps of ssl certificate verification that i receive from the server,
i opened certifi module and found fingerprints and md5 and base64 encoded key i know the finger prints are generated from the key but what are the steps of the verification itself does it use the sha256 or ... | <p>The reason why <code>getpeercert</code> returns an empty dict is descibed in the help:</p>
<blockquote>
<p>If the binary_form parameter is False, and a certificate was received from the peer, this method returns a dict instance. <strong>If the certificate was not validated, the dict is empty.</strong></p>
</blockquo... | python|sockets|security|ssl|certificate | 1 |
1,618 | 69,238,716 | Checking which key has the most letters in its dictionary in Python | <p>I have a dictionary in a Python code like this:</p>
<pre><code>S = {(x0): 'omicron', (x1): 'a', (x2): 'ab', (x3): 'abbr', (x4): 'abr', (x5): 'abrf', (x6): 'abrfa', (x7): 'af', '(x8)': 'afc'}
</code></pre>
<p>I would like to check which key has its corresponding dictionary with the highest numer of letters, except fo... | <p>You could use the key parameter of <a href="https://docs.python.org/3/library/functions.html#max" rel="nofollow noreferrer">max</a>:</p>
<pre><code>res = max(S, key=lambda x: (S[x] != 'omicron', len(S[x])))
print(res)
</code></pre>
<p><strong>Output</strong></p>
<pre><code>(x6)
</code></pre>
<p>This will make the ke... | python|dictionary|key | 1 |
1,619 | 72,758,727 | Unable to click inside of a game window with pyautogui/win32api/pydirectinput | <p>I can click on the window, but it doesn't move my character, or interact with anything in game. I've tried moving the mouse around, i've tried doing keyboard inputs, full screen, windowed, etc. I've also tried using screenshots with pyautogui, but no luck. The game i'm trying to use it with was initially released in... | <p>First, make sure you are running your script as admin, sometimes if you don't Windows will prevent mouse movement.
Also, try doing this:</p>
<pre><code>def click(x,y):
win32api.SetCursorPos((x, y))
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0)
time.sleep(.01)
win32api.mouse_event(win32con... | python|pywin32|pyautogui | 1 |
1,620 | 72,756,675 | Extract tag information from sentence (Regex) based on tag data | <p>I have an input corpus which could be of the following formats:</p>
<p><code>Name: ABC Def Date: 8-01-09 Age: 5</code> (First Name + Last Name) //Expected Output: ABC Def</p>
<p><code>Name: Abc Date: 8-01-09 Age: 5</code> (Only first name present) //Expected Output: Abc</p>
<p><code>Name ABC Date 8-01-09 Age 5</code... | <p>Try (<a href="https://regex101.com/r/Kqd4pw/1" rel="nofollow noreferrer">regex101</a>):</p>
<pre class="lang-py prettyprint-override"><code>import re
test_cases = [
"Name: ABC Def Date: 8-01-09 Age: 5",
"Name: Abc Date: 8-01-09 Age: 5",
"Name ABC Date 8-01-09 Age 5",
&q... | python-3.x|regex|match|extract | 0 |
1,621 | 68,152,179 | Using SciPy to Fit a Levy-Stable Distribution with positive vs negative skew | <p>I don't understand the parameters returned by the _fitstart() method of <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.levy_stable.html" rel="nofollow noreferrer">scipy.stats.levy_stable</a> for distributions with positive versus negative beta parameters. Intuitively, changing the sign of... | <p>levy_stable._fitstart() is not handling negatively skewed data correctly, but we can work around it by reflecting the sample about the origin. _fitstart() will then return sensible estimates for the stability and scale parameters, which are not affected by reflection. The estimates of skewness and loc parameters a... | python|statistics|scipy.stats | 0 |
1,622 | 59,050,251 | Reshaping array using array.reshape(-1, 1) | <p>I have a dataframe called <code>data</code> from which I am trying to identify any outlier prices.</p>
<p>The data frame head looks like:</p>
<pre><code> Date Last Price
0 29/12/2017 487.74
1 28/12/2017 422.85
2 27/12/2017 420.64
3 22/12/2017 492.76
4 21/12/2017 403.95
</code></pr... | <p>You should be able to fix the error by changing this line:</p>
<pre><code>np_scaled = scaler.fit_transform(data)
</code></pre>
<p>with this:</p>
<pre><code>np_scaled = scaler.fit_transform(data.values.reshape(-1,1))
</code></pre> | python|pandas|numpy|scikit-learn | 4 |
1,623 | 63,093,989 | tkinter- subclass of button not placing on screen from inside another class | <p>I'm making a ide for brainf*ck in python using tkinter and I'm adding a recent projects section but when I'm placing the buttons they do not appear on the screen.</p>
<p>Here is the code for the <code>Scene</code>:</p>
<pre><code>from tkinter import *
from tkinter import filedialog as File
import tkinter as tk
cla... | <p>Try to insert values for relx, rely, relwidth, relheight as attributes in "place" or you can as well insert height, width as attributes for place.
Check out the documentation: <a href="https://www.tutorialspoint.com/python/tk_place.htm" rel="nofollow noreferrer">https://www.tutorialspoint.com/python/tk_pla... | python|button|tkinter|subclass | 0 |
1,624 | 58,731,643 | Find number of rows in a given week in PySpark | <p>I have a PySpark dataframe, a small portion of which is given below:</p>
<pre><code>+------+-----+-------------------+-----+
| name| type| timestamp|score|
+------+-----+-------------------+-----+
| name1|type1|2012-01-10 00:00:00| 11|
| name1|type1|2012-01-10 00:00:10| 14|
| name1|type1|2012-01-10 00... | <p>Something like this:</p>
<pre><code>from pyspark.sql.functions import weekofyear, count
df = df.withColumn( "week_nr", weekofyear(df.timestamp) ) # create the week number first
result = df.groupBy(["week_nr","name"]).agg(count("score")) # for every week see how many rows there are
</code></pre> | python|pandas|pyspark|pyspark-sql|pyspark-dataframes | 1 |
1,625 | 31,536,195 | django. Error: ('IM002', '[IM002] [unixODBC][Driver Manager]Data source name not found, and no default driver specified (0) (SQLDriverConnect)') | <p>Recieving this error when connecting to MSSQL server</p>
<p>My linux machines details:- </p>
<pre><code>Distributor ID: Ubuntu
Description: Ubuntu 14.04.2 LTS
Release: 14.04
</code></pre>
<p>MSSQL Server DB details: </p>
<pre><code>version : 2012
</code></pre>
<p>Error: </p>
<pre><code> django.db.uti... | <p>First, make sure you have the required packages installed (it looks like you may):</p>
<pre><code># Install pre-requesite packages
sudo apt-get install unixodbc unixodbc-dev freetds-dev freetds-bin tdsodbc
</code></pre>
<p>Then, make sure you have /etc/freetds/freetds.conf configured properly:</p>
<pre><code>[glo... | python-2.7|sql-server-2012|ubuntu-14.04|pyodbc|django-1.8 | 2 |
1,626 | 31,261,664 | Retrieve the file download triggered by a python request | <p>I want to capture a file that is downloaded when a certain url is passed in python. The problem is that the downloaded file is NOT returned by the server. The file gets downloaded when I pass the same url in a browser, but not when I do so via <code>urllib2.urlopen()</code>. Is there a way to capture this seemingly ... | <p>We can't really diagnose this if you don't tell us what it <em>does</em> return. If you need any sort of login to access it, it won't work because Python doesn't have your browser cookies. Python also won't automatically follow some types of redirects and anything Javascript-dependant is right out of the question. T... | python|urllib2 | 0 |
1,627 | 15,518,814 | Version 1.7.6 Import Error in line 890 of sanbox.py when running dev_appserver | <p>I'm having some dificulty gettung 1.7.6 running. Getting the following error:</p>
<pre><code>INFO 2013-03-20 08:39:10,233 admin_server.py:117] Starting admin server at: http://localhost:8086
ERROR 2013-03-20 08:39:13,768 wsgi.py:219]
Traceback (most recent call last):
File "/Applications/GoogleAppEngineLa... | <p>I had the same problem. I raised an issue in the appengine issue tracker:</p>
<p><a href="https://code.google.com/p/googleappengine/issues/detail?id=9008&sort=-id&colspec=ID%20Type%20Component%20Status%20Stars%20Summary%20Language%20Priority%20Owner%20Log" rel="nofollow">https://code.google.com/p/googleappe... | python|google-app-engine | 5 |
1,628 | 59,634,315 | running pycharm Python Code in command line headless | <pre><code>running pycharm Python Code in command line headless
I have code in following folder structure
</code></pre>
<p>#Main_Folder
## -Folder1
###--first.py<br>
###--second.py (imports methods from first.py) also has its own class Second<br>
###--main.py (calls both first.py and second.py to run... | <p>It would be interesting to have at least part of your code that exhibits the issue.</p>
<p>From the error message <code>No module named 'folder1'</code>, I suppose that you are doing something wrong with your <code>import</code> statements.</p>
<p>PyCharm has a tendency to mess with your PYTHONPATH, especially whe... | python|selenium | 0 |
1,629 | 49,142,561 | Change contrast in Numpy | <p>I want to write a pure Numpy function to change the contrast of an RGB image (that is represented as a Numpy uint8 array), however, the function I wrote doesn't work and I don't understand why.</p>
<p>Here is an example image:</p>
<p><a href="https://i.stack.imgur.com/Ceppy.png" rel="nofollow noreferrer"><img src=... | <p>What you are seeing is underflow of unsigned integers:</p>
<pre><code>>>> a = np.array((64, 128, 192), dtype=np.uint8)
>>> a
array([ 64, 128, 192], dtype=uint8)
>>> a-128
array([192, 0, 64], dtype=uint8) # note the "wrong" value at pos 0
</code></pre>
<p>One way of avoiding this is co... | python|numpy | 5 |
1,630 | 49,090,127 | why is this not working writing ValueError (though i used Tango_with_django book 1.9)? | <p>Am using Django 2.0.2 for Django 1.9 Tutorial and couldn't figure out what the problem was after reconstruct my URL. Error Display (The view rango.views.category didn't return an HttpResponse object. It returned None instead.)</p>
<pre><code>from django.template import RequestContext
from django.shortcuts import re... | <p>Put more faith into error messages. It says your <code>category()</code> function did not return a value, because it did not return a value. Its <code>return</code> is indented to the same level as <code>pass</code> and thus it belongs to the exception handler. Indent it to the level of the <code>except</code> keywo... | python|django | 0 |
1,631 | 25,182,421 | Overlay two numpy arrays treating fourth plane as alpha level | <p>I have two numpy arrays of shape (256, 256, 4). I would like to treat the fourth 256 x 256 plane as an alpha level, and export an image where these arrays have been overlayed.</p>
<p>Code example:</p>
<pre><code>import numpy as np
from skimage import io
fg = np.ndarray((256, 256, 4), dtype=np.uint8)
one_plane = n... | <p><a href="http://en.wikipedia.org/wiki/Alpha_compositing#Alpha_blending" rel="noreferrer">Alpha blending</a> is usually done using the Porter & Duff equations:</p>
<p><img src="https://i.stack.imgur.com/iCSV2.png" alt="enter image description here"></p>
<p>where <em>src</em> and <em>dst</em> would correspond to... | python|image|numpy|alphablending|scikit-image | 10 |
1,632 | 25,087,769 | RuntimeWarning: Divide by Zero error: How to avoid? PYTHON, NUMPY | <p>I am running in to RuntimeWarning: Invalid value encountered in divide</p>
<pre><code> import numpy
a = numpy.random.rand((1000000, 100))
b = numpy.random.rand((1,100))
dots = numpy.dot(b,a.T)/numpy.dot(b,b)
norms = numpy.linalg.norm(a, axis =1)
angles = dots/norms ### Basically I am calculating angle between ... | <p>you can ignore warings with the <code>np.errstate</code> context manager and later replace nans with what you want:</p>
<pre><code>import numpy as np
angle = np.arange(-5., 5.)
norm = np.arange(10.)
with np.errstate(divide='ignore'):
print np.where(norm != 0., angle / norm, -2)
# or:
with np.errstate(divide='i... | python|numpy | 15 |
1,633 | 2,458,585 | Concatenate multi value into one record | <p>I joined two tables together and what I like to do is concatenate multi vaule in one records without duplicated value.</p>
<ol>
<li><p>Input Table<br/><br/>
Table name: TAXLOT_ZONE<br/>
TID ZONE<br/>
1 A<br/>
1 A<br/>
1 B<br/>
1 C<br/>
2 D<br/>
2 D <br/>
2 E<br/>
3 A<br/>
3 B<b... | <p>Assuming your table is in sorted order and is iterable, you can use <a href="http://docs.python.org/library/itertools.html" rel="nofollow noreferrer"><code>itertools.groupby</code></a> to group rows with the same first element.</p>
<pre><code>l = [(1, 'A'), (1, 'A'), (1, 'B'), (1, 'C'),
(2, 'D'), (2, 'D'), (2,... | python | 1 |
1,634 | 2,456,828 | Reading object tree from file into Python | <p>I have a Python app that contains an object structure that the user can manipulate. What I want to do is allow the user to create a file declaring how the object structure should be created.</p>
<p>For example, I would like the user to be able to create the following file:</p>
<pre><code>foo.bar.baz = true
x.y.z =... | <p>Typically problems like this one are solved with XML. However in your case you can do something even easier.</p>
<p>Assuming the dots represent hierarchy delimiters, you could read in the left hand side of the <code>=</code> sign (<code>input.split('=')[0]</code>), and then perform a <code>split('.')</code> on the ... | python | 1 |
1,635 | 3,089,413 | Increasing throughput in a python script | <p>I'm processing a list of thousands of domain names from a DNSBL through dig, creating a CSV of URLs and IPs. This is a very time-consuming process that can take several hours. My server's DNSBL updates every fifteen minutes. Is there a way I can increase throughput in my Python script to keep pace with the server's ... | <p>The vast majority of the time here is spent in the external calls to <code>dig</code>, so to improve that speed, you'll need to multithread. This will allow you to run multiple calls to <code>dig</code> at the same time. See for example: <a href="https://stackoverflow.com/questions/984941/python-subprocess-popen-f... | python|unix|python-multithreading | 2 |
1,636 | 6,172,351 | Memory management of large lists in Python | <p>Today I wrote a program using an array/list with 64000000 entries. However, when writing <code>sigma=[1]*64000000</code> using Python it runs fine, but later on, as the program computes, my Ubuntu freezes - without any reaction to inputs, not even mouse movement. I tried twice and the results are the same.</p>
<p>W... | <p>Python lists are lists of <em>objects</em>. A number in Python is an object in itself, and takes up somewhat more storage than the 64 bits needed to represent a <code>long long</code> in C++. In particular, Python transparently handles numbers larger than 32 bits, which end up taking a <em>lot</em> more space than a... | python|list|memory-management | 7 |
1,637 | 66,816,247 | displaying image in flask from requests? | <p>I want to display an image in a url after sent POST requests with picture to my server, and it will change picture everytime there is a new request comes.</p>
<p>my server:</p>
<pre><code>app = Flask(__name__)
APP_ROOT = os.path.dirname(os.path.abspath(__file__))
UPLOAD_FOLDER = os.path.join(APP_ROOT, 'static/upload... | <p>There is a way to render image files on flask without actually saving them on your machine.</p>
<p>Try using <a href="https://en.wikipedia.org/wiki/Data_URI_scheme" rel="nofollow noreferrer">data uri</a>.</p>
<p>More information on this can be found on <a href="https://stackoverflow.com/questions/24219446/render-ima... | python|flask|python-requests | 1 |
1,638 | 43,014,681 | create a list of all the subsets of a given list in python 3.x | <p>how can I create a list of all the subsets of a given list in python 3.x?
the list given be like <code>[1,2,3]</code> and i want an output like</p>
<pre><code>[[1],[2],[3],[1,2],[2,3],[1,3],[1,2,3],[]]
</code></pre> | <p>You can use <a href="https://docs.python.org/3/library/itertools.html#itertools.combinations" rel="noreferrer"><code>itertools.combinations</code></a> to get the combinations:</p>
<pre><code>>>> import itertools
>>> xs = [1, 2, 3]
>>> itertools.combinations(xs, 2) # returns an iterator
... | python|list|python-3.x | 7 |
1,639 | 66,694,452 | Wanting to update a list attribute in a class without having to call an update function for every change | <p>This is what I'm working with:</p>
<pre><code>class Vector:
def __init__(self):
self.x = 0
self.y = 0
self.z = 0
self.w = 0
self.data = [
[self.x],
[self.y],
[self.z],
[self.w]
]
</code></pre>
<p>Is it possible to upd... | <p>You can create your own objects for <code>x</code>, <code>y</code>, <code>z</code>, and <code>w</code> that have a custom update method. That way, when ever those attributes are updated, the change will be reflected via reference in <code>data</code>:</p>
<pre><code>class Component:
def __init__(self, val = 0, na... | python|list|class|attributes | 0 |
1,640 | 72,249,904 | Pandas data manipulation from column to row elements | <p>I have dataset with millions of rows, here is an example of what it looks like and what I intend to output:</p>
<pre><code>data = [[1, 100, 8], [1, 100, 4],
[1, 100,6], [2, 100, 0],
[2, 200, 1], [3, 300, 7],
[4, 400, 2], [5, 100, 6],
[5, 100, 3], [5, 600, 1]]
df= pd.DataFrame(data... | <p>Use <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.astype.html" rel="nofollow noreferrer"><code>df.astype</code></a> with <a href="https://pandas.pydata.org/pandas-docs/version/0.22/generated/pandas.core.groupby.DataFrameGroupBy.agg.html" rel="nofollow noreferrer"><code>Groupby.agg</code></a>... | pandas|numpy|data-manipulation | 1 |
1,641 | 65,577,458 | SSL validation failure resulting in failure to visualise data generated on aws | <p>I am experiencing an issue with the following script, I am following the present AWS tutorial</p>
<p><a href="https://aws.amazon.com/pt/blogs/big-data/build-a-visualization-and-monitoring-dashboard-for-iot-data-with-amazon-kinesis-analytics-and-amazon-quicksight/" rel="nofollow noreferrer">https://aws.amazon.com/pt/... | <p>I solved it.</p>
<p>For those interested, simply insert this at the beginning of your code:`</p>
<p><code>from botocore.exceptions import ClientError</code></p>
<p>It should work.</p>
<p>Best.</p> | python|ssl-certificate|iot|aws-iot|aws-iot-analytics | 0 |
1,642 | 50,867,435 | Get subnet from IP address | <p>I am trying to get subnet for IP address I have.</p>
<p>Eg :</p>
<p><strong>1</strong></p>
<p>Subnet mask : <code>255.255.255.0</code></p>
<p>Input : <code>192.178.2.55</code></p>
<p>Output : <code>192.178.2.0</code></p>
<p><strong>2</strong></p>
<p>Subnet mask : <code>255.255.0.0</code></p>
<p>Input : <code... | <p>The <a href="https://docs.python.org/3/library/ipaddress.html#ipaddress.ip_network" rel="noreferrer"><code>ipaddress.ip_network</code></a> function can take any of the string formats that <code>IPv4Network</code> and <code>IPv6Network</code> can take, including the <code>address/mask</code> format.</p>
<p>Since you... | python|python-3.x|ip-address | 17 |
1,643 | 50,451,793 | Pandas pivot table selecting rows with maximum values | <p>I have pandas dataframe as:</p>
<pre><code>df
Id Name CaseId Value
82 A1 case1.01 37.71
1558 A3 case1.01 27.71
82 A1 case1.06 29.54
1558 A3 case1.06 29.54
82 A1 case1.11 12.09
1558 A3 case1.11 ... | <p><code>sort_values</code> + <code>drop_duplicates</code></p>
<pre><code>df.sort_values('Value').drop_duplicates(['Id'],keep='last')
Out[93]:
Id Name CaseId Value
7 1558 A3 case1.16 33.35
0 82 A1 case1.01 37.71
</code></pre>
<p>Since we post same time , adding more method </p>
<pre><code>df.so... | pandas|python-3.5 | 5 |
1,644 | 35,061,133 | Making multiple search and replace more precise in Python for lemmatizer | <p>I am trying to make my own lemmatizer for Spanish in <code>Python2.7</code> using a lemmatization dictionary.</p>
<p>I would like to replace all of the words in a certain text with their lemma form. This is the code that I have been working on so far.</p>
<pre><code>def replace_all(text, dic):
for i, j in dic.... | <p>Because you use text.replace there's a chance that you'll still be matching a sub-string, and the text will get processed again. It's better to process one input word at a time and build the output string word-by-word.</p>
<p>I've switched your key-value the other way around (because you want to look up the right ... | python|regex|search|dictionary|replace | 1 |
1,645 | 35,122,774 | Notepad++ Folding Lines using Python | <p>I'm using Notepad++ to write Python 2.7 code. I just want to create my own block indicator and fold the block so it is hidden. Something like:</p>
<pre><code>#//begin
#//end
</code></pre>
<p>I'm going to use the comment # as the front character so as not to upset the code. All the questions and answers I've found ... | <p>Adding a user defined language using Notepad++ to just add folding can be done as follows:</p>
<ol>
<li><p>Click on <code>Language > Define your language</code></p></li>
<li><p>Click on <code>Create New...</code> and enter a name for it e.g. <code>Twegner</code></p></li>
<li><p>In the section on the right add yo... | python|notepad++|fold | 1 |
1,646 | 26,632,784 | Django - Update model field based on another field | <p>I am new to Django and Python and I want to do something I used to do very often in Java EE.</p>
<p>Consider the following model (only relevant classes):</p>
<pre><code>class Item(models.Model):
name = models.CharField(max_length=40)
default_price = models.DecimalField(max_digits=6, decimal_places=2, defau... | <p>The "unit price" is a literally a function of two different fields. As such I would tend to write it like this:</p>
<pre><code>class Item(models.Model):
name = models.CharField(max_length=40)
default_price = models.DecimalField(max_digits=6, decimal_places=2, default=50)
def __unicode__(self):
... | python|django|orm|model|field | 4 |
1,647 | 26,615,261 | Python: checking for executable | <pre><code>is_exec = lambda x: subprocess.call("type " + x, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) == 0 and (os.path.isfile(x) and os.access(x, os.X_OK))
</code></pre>
<p>I came across this code and it works fine but is it redundant?</p>
<p>Isnt <code>is_exec = lambda x: os.access(x, os.X_OK)</co... | <p>Both require <code>os.access(x, os.X_OK)</code> to return True. However, in addition to performing some unnecessary tests before calling <code>os.access</code>, the first opens you up to a shell injection attack unless you carefully screen the value of <code>x</code> before using it. Using <code>shell=True</code> wi... | python | 1 |
1,648 | 45,197,777 | How do I update Anaconda? | <p>I have Anaconda installed on my computer and I'd like to update it. In Navigator I can see that there are several individual packages that can be updated, but also an <code>anaconda</code> package that sometimes has a version number and sometimes says <code>custom</code>. How do I proceed?</p>
<p><a href="https:/... | <blockquote class="spoiler">
<p> <code>root</code> is the old (pre-conda 4.4) name for the main environment; after conda 4.4, it was renamed to be <code>base</code>. <a href="https://stackoverflow.com/a/52592177/8828460">source</a></p>
</blockquote>
<h2>What 95% of people actually want</h2>
<p>In most cases what you w... | python|anaconda|conda | 517 |
1,649 | 45,048,615 | Custom pipeline for different data type in scikit learn | <p>I am currently trying to predict whether a kickstarter project will be successful or no depending on a bunch of integer and some text features. I was looking at building a pipeline which would look something like this</p>
<p>Reference : <a href="http://scikit-learn.org/stable/auto_examples/hetero_feature_union.html... | <p>The ItemSelector is returning a Dataframe, not an array. Thats why the <code>scipy.hstack</code> is throwing up error. Change the ItemSelector as below:</p>
<pre><code>class ItemSelector(BaseEstimator, TransformerMixin):
....
....
....
def transform(self, data_dict):
return data_dict[se... | python|pandas|numpy|machine-learning|scikit-learn | 1 |
1,650 | 64,989,768 | duplicate a row and change a value of a column to the duplicate row | <p>I need your help What I am looking for is to obtain the table below starting from the table above.</p>
<pre><code>Date ID Typol1 Facial#1 Facial#2 Typol2
april 426 COR 1000 500 LAR
may 419 LAR 5000 100 COR
</code></pre>
<pre><code>Date ID Typol Facial
abr... | <p>DataFrame</p>
<pre><code>df=pd.DataFrame({'Date':['april','may'],
'id':[426,419],
'typol1':['COR','LOR'],
'facial1':[1000,5000],
'facial2':[500,100],
'typol2':["LAR",'COR']})
</code></pre>
<p>change columns names</p>
<pre><code... | python|dataframe | 1 |
1,651 | 51,109,420 | How to know file path from binary python file? | <p>I am noobie in python.</p>
<p>I have seen a file in my /usr/bin/xyz.py. Whenever I execute it, It get some work done(not related to the question.)</p>
<p>My question is I want to find where the code of this file (which is generating this python file. I am saying so whenever I write name of file in my terminal and ... | <p>These are Python's file types:</p>
<p><code>.py</code> files are not binary files, they are pure Python code.</p>
<p><code>.pyc</code> and <code>.pyo</code> are Python compiled files (which are not fully binary either). The only difference is that the latter is optimized.</p>
<p><code>.pyw</code> does not say any... | python|python-2.7 | 3 |
1,652 | 51,051,619 | Decode a str with hex sequences to a string | <p>I am getting a str from BeautifulSoup that contains escaped characters using <code>\xXX</code> notation that needs to be decoded into a regular str. </p>
<p>Example:</p>
<pre><code>next_url = r'\x26hl\x3den'
</code></pre>
<p>After conversion, I want:</p>
<pre><code>next_url = '&hl=en'
</code></pre>
<p>It ap... | <p>You have a str with byte literals. Use codecs module with <code>unicode-escape</code> codec to unescape them.</p>
<pre><code>import codecs
codecs.decode(r'\x26hl\x3den', 'unicode-escape')
</code></pre> | python|string|python-3.x | 2 |
1,653 | 61,251,896 | insert_many or insert_one not working in a MongoDB in PyMongo | <p>I am trying to use the insert_one function or the insert_many function to Add a Document to my Collection in the MongoDB , I keep seeing the below error , I am trying the Dictionary approach for the same , here's my Code attached below alongwith the Error , can anyone please throw some light on the same , I am new t... | <p>Thanks Mehta, I got it working after replicating the same program to a Windows Box which was able to reach the mongoDB through mongo Shell.</p> | python|mongodb|mongodb-query|pymongo|pymongo-3.x | 0 |
1,654 | 61,247,362 | Why doesn't my speech recognition platform open up Wikipedia via the query? | <p>I'm building weak AI platform like Siri, however, every time I run the code I receive "if 'wikipedia' in query():
TypeError: 'NoneType' object is not callable" instead of it opening up Wikipedia.Can someone please walk me through fixing this. Thanks</p>
<pre><code>import pyttsx3
import speech_recognition as sr
impo... | <p>Your function <code>takeCommand</code> doesn't return anything, which means that it explicitly returns <code>None</code>. Hence, the line</p>
<pre><code>if 'wikipedia' in query:
</code></pre>
<p>is equivalent to</p>
<pre><code>if 'wikipedia' in None:
</code></pre>
<p>which is not valid and will raise <code>TypeE... | python|python-3.x|speech-recognition|speech-to-text | 2 |
1,655 | 61,536,469 | How to use a decorator of class method | <p>When I design a class, I wrote a class member function as a decorator </p>
<pre><code> def switchWindow(self, win: str):
def actual_decorator(func):
self.browser.switch_to.window(self.windowsHandles[win])
def inner():
func()
return inner
return... | <p>I move the decorator function out of the class, and make some changes like this:</p>
<pre><code>def switchWindow(win: str):
def actual_decorator(func):
print(win)
def inner(self):
self.browser.switch_to.window(self.windowsHandles[win])
func(self)
return inner
... | python|python-decorators | 0 |
1,656 | 60,338,266 | Python: distance from index to 1s in binary mask | <p>I have a binary mask like this:</p>
<pre><code>X = [[0, 0, 0, 0, 0, 1],
[0, 0, 0, 0, 1, 1],
[0, 0, 0, 1, 1, 1],
[0, 0, 1, 1, 1, 1],
[0, 0, 1, 1, 1, 1],
[0, 0, 0, 1, 1, 1]]
</code></pre>
<p>I have a certain index in this array and want to compute the distance from that index to the closest ... | <p>You can use <a href="https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.morphology.distance_transform_cdt.html" rel="nofollow noreferrer"><code>scipy.ndimage.morphology.distance_transform_cdt</code></a> to compute the "taxicab" (Manhattan) distance transform:</p>
<pre class="lang-py prettypri... | python|numpy|scipy | 3 |
1,657 | 60,743,732 | Django custom user model meta overlaps when importing from another project | <p>I'm remaking a script to sync data from an old python2 project to a new with python3. The way the last programmer made it work appears to be by importing both, the new and old models into a script in the old project using:</p>
<pre><code>sys.path.append("route to the new project")
</code></pre>
<p>It works for imp... | <p>Finally I found a way to correct the app_label and db_table from the user and the companies relation.</p>
<p>First import the model, and then overwrite the _meta atributes.</p>
<pre><code>from user_models.models import UserProfile
UserProfile._meta.db_table="user_models_userprofile"
UserProfile._meta.app_label="u... | python|django | 0 |
1,658 | 58,082,023 | How exactly does Ray share data to workers? | <p>There are many simple tutorials and also SO questions and answers out there which claim that Ray somehow shares data with the workers, but none of these go into the exact details of what gets shared how on which OS.</p>
<p>For example in this SO answer: <a href="https://stackoverflow.com/a/56287012/1382437">https://... | <p>This is a great question, and one of the cool features that Ray has. Ray provides a way to <strong>schedule functions in a distributed environment</strong>, but it also provides a <strong>cluster store</strong> that manages data sharing between these tasks.</p>
<p>Here are the kind of objects that ray</p>
<ul>
<li>O... | python|numpy|serialization|shared-memory|ray | 3 |
1,659 | 57,871,578 | I don't understand this code - Python exercise odd or even | <p>I'm a beginner coder and I'm studying Python. I'm doing some exercise to improve my code.
I don't understand the logic that there is behind in these codes.</p>
<p>The code above is my code (forgive me if it is not performing with the standards that are around).</p>
<p>And this is the solution but again I don't und... | <p>An odd number is equal to 1 modulo 2.</p>
<p>In this code, <code>mod</code> is either equal to <code>0</code> or <code>1</code> (because modulo <code>2</code> implies it). Therefore, the condition <code>mod>0</code> is equivalent to <code>mod==1</code>, which is exactly what you are looking for if you want to kn... | python | 2 |
1,660 | 55,289,901 | Drop columns with no header on csv import with pandas | <p>Here is a sample csv:</p>
<pre><code>| Header A | | Unnamed: 1 | Header D |
|-----------|------|------------|-----------|
| a1 | b1 | c1 | d1 |
| a2 | b2 | c2 | d2 |
</code></pre>
<p>If I import it with <code>pandas.read_csv</code>, it turns into this:</p>
<p... | <p>The only way I can think of is to "peek" at the headers beforehand and get the indices of non-empty headers. Then it's not a case of dropping them, but not including them in the original df.</p>
<pre><code>import csv
import pandas as pd
with open('test.csv') as infile:
reader = csv.reader(infile)
headers ... | python|pandas|csv | 2 |
1,661 | 55,361,055 | Why can't I use a variable in an for x in df.itertuples loop created prior to that loop? | <p>This is probably a basic Pandas question but I can't figure it out?</p>
<p>I have this loop : </p>
<pre><code>n=0
for lum in lum_df.itertuples():
print(lum.X)
print(lum.Y)
lum_x = float(lum.X)
lum_y = float(lum.Y)
for point in street_df.itertuples():
print(point.X)
print(point.Y... | <p>here's the data structure of lum_df : </p>
<pre><code> X Y Name
624 617053.712042883 5027348.30038856 AvenuedAnjou
664 617039.606222975 5027394.710913 AvenuedAnjou
692 617033.143825697 5027442.18526991 AvenuedAnjou
723 617024.347605215 5027483.05113423 Avenu... | python|pandas|for-loop | 0 |
1,662 | 57,530,162 | why does my for loop not edit the global list I and looping through and editing? | <p>There is probably a matching question out there. I have a globally defined list and I am trying to iterate through the list and edit certain elements by using specific if statements. My problem is that when I print the list before the loop and when I print the list afterwards they are still the same.</p>
<p>I've co... | <p>As Derek Langley suggested, you can do it by indexing the list. Rather than <code>range(len(list))</code>, it's a good habit to use <code>enumerate(list)</code></p>
<pre><code>print(list)
for index, value in enumerate(list):
print(value)
if value < 1:
list[index] = 0
elif value > 1:
... | python|for-loop|if-statement | 2 |
1,663 | 42,445,021 | printing during loop in Jupyter | <p>I am running a loop over a list (a parameter grid) and trying to simply print the progress of the loop. I have found that it is an issue with my Jupyter notebook.</p>
<p>I have the following code to extract just the problem:</p>
<pre><code>hiddens = [2, 3]
iters = [5, 10]
para_grid = [(hidden, it)
f... | <p>I'm assuming your jupyter notebook is running python2.x.</p>
<p>By default, python 2 returns <code>0</code> if you divide two integers and the result is < 1.</p>
<p>A workaround is to add <code>from __future__ import division</code> to your code.</p>
<p>Another workaround, as titipat suggested in his comment, ... | python|printing|jupyter-notebook | 1 |
1,664 | 54,014,341 | unable to change dtype pandas python | <p>I'm working with a dataframe in <code>pandas</code> and I have a column with an <code>int64</code> data type. I need to convert this data type to a string so that I can slice the characters, taking the first 3 chars of the 5 character column. The code is as follows: </p>
<pre><code>trainer_pairs[:, 'zip5'] = trai... | <p>Here you should using <code>astype(str)</code></p>
<pre><code>trainer_pairs['zip5'] = trainer_pairs.zip5.astype(str)
</code></pre>
<hr>
<p>About your errors </p>
<pre><code>df=pd.DataFrame({'zip':[1,2,3,4,5]})
df.zip.astype(object)
Out[4]:
0 1
1 2
2 3
3 4
4 5
Name: zip, dtype: object
</code></pre... | string|pandas|slice | 1 |
1,665 | 58,466,842 | Cannot import `gi`in Python to satisfactorily execute `ibus-setup` | <p>My issue is similar to what was described <a href="https://stackoverflow.com/questions/37526026/how-to-install-gi-module-for-anaconda-python3">here</a> 3 years ago, but in my case on Arch Linux 5.3.7. Not certain this is the right place to ask though.</p>
<p>Motivation: I want to run <code>ibus-setup</code> to cor... | <p>Assuming your system has python2 installed, a possible solution is perhaps <code>alias python=python2</code> in your shell, then try <code>ibus-setup</code> again.</p>
<p>I encountered the same issue today on Ubuntu 18.04. I was in a conda environment (py3.6). After deactivating the environment, it works. Using <co... | python|import|module | 0 |
1,666 | 58,582,960 | Python- trying to understand plural vs singular in code. For example: for i, square in enumerate(squares): | <p>I'm trying to clarify my understanding regarding situations in the code in which the singular <em>seems to</em> extract from the plural. I'm not sure if this is standard among different languages, or, unique to specific situations in python. Regardless, in the example below I refer to square within the squares lis... | <p>The variables <code>square</code> and <code>squares</code> are completely unrelated. In this case, the use of the variable <code>square</code> (singular) is an arbitrary decision by the coder. I.e.</p>
<pre><code>squares=['white', 'black', 'red', 'blue', 'green']
for i, square in enumerate(squares): print(i, square... | python|enumerate|plural|singular | 3 |
1,667 | 65,183,287 | Writing List to CSV in Python | <p>I'm writing data from a PDF to a CSV. The CSV needs to have one column, with each word on a separate row.</p>
<p>The code below writes each word on a separate row, but also puts each letter in a separate cell.</p>
<pre><code>with open('annualreport.csv', 'w', encoding='utf-8') as f:
write = csv.writer(f)
for... | <p>As far as I know, <a href="https://docs.python.org/3/library/csv.html#csv.csvwriter.writerow" rel="nofollow noreferrer"><code>writerow</code></a> expects an array. Thus a word is treated as an array with the individual letters <strong>-> each letter is written into a new cell.</strong></p>
<p>Putting the value in... | python|export-to-csv | 3 |
1,668 | 22,786,748 | Celery scheduled tasks problems with Timezone | <p>I'm using celery in a server where server time is now <strong>BST</strong>, and suddenly my scheduled tasks are executing <strong>one hour before!</strong> Previously, server time was Europe/London which was GMT but now due to day light saving it has become BST (GMT + 1)</p>
<p>I've configured celery to use the tim... | <p>You might find it easier to set your <code>CELERY_TIMEZONE</code> to be <code>'UTC'</code>. Then, if you want to use Local times to schedule events, you can do the following:</p>
<pre><code>london_tz = pytz.timezone('Europe/London')
london_dt = london_tz.localize(datetime.datetime(year, month, day, hour, min))
give... | python|celery | 14 |
1,669 | 45,427,755 | Python Peewee MySQL bulk update | <p>I am using Python 2.7, Peewee and MySQL. My Program reads from a csv file and update the field if order number exists in the csv. There can be 2000-3000 updates and I'm using naive approach to update the record one by one, which is dead slow. I have moved from using Peewee update to Raw query, which is a bit faster.... | <p>The new best answer is to use <a href="http://docs.peewee-orm.com/en/latest/peewee/api.html#Model.bulk_update" rel="nofollow noreferrer">Model.bulk_update</a> with a transaction. The <code>batch_size</code> argument can be changed to tune performance.</p>
<pre><code># CSV generator for efficient memory usage
def gen... | python|peewee | 0 |
1,670 | 45,322,207 | Python printing Deepdiff value | <p>I am using the <code>deepdiff</code> function to find the difference between 2 dictionaries, which gives the output as: <code>A = {'dictionary_item_added': set(["root['mismatched_element']"])}</code>. How to print just <code>'mismatched_element'</code>?</p> | <p>Try this:</p>
<pre><code>set_item = A['dictionary_item_added'].pop()
print set_item[set_item.find("['")+2 : set_item.find("']")]
</code></pre>
<p>The first line gets the element from the set, the second removes the <code>[]</code> and everything around them, and prints.</p>
<p>This code does the specific task you... | python-2.7 | 0 |
1,671 | 45,478,386 | Python class order | <p>I was just trying some things with the python classes and wondered about the order of them. Does python offer a solution to put the class C before class A and B and still inherit things from them?</p>
<pre><code>class A:
def input_name(self):
user_input_name = input("Name please\n")
A.user_input... | <p>No, you can't. <code>class</code> is an executable statement that creates the class object at runtime and bind it to the class name in the current scope. Until this statement is executed, the class object doesn't exist <em>and</em> the name is not defined either, so you cannot reference it.</p> | python|python-3.x|oop | 0 |
1,672 | 28,716,832 | How to test function is called with correct arguments with pytest? | <p>I'm learning how testing is done in Python using <code>py.test</code>. I am trying to test a specific situation that is quite common when using other libraries like <code>mock</code>. Specifically, testing that a function or method invokes another callable with the correct arguments. No return value is needed, just ... | <p>Well. I've come up with something that seems to work, but I suppose its similar to mock:</p>
<pre><code>@pytest.fixture
def argtest():
class TestArgs(object):
def __call__(self, *args):
self.args = list(args)
return TestArgs()
class ProductionClass:
def method(self):
self.s... | python|unit-testing|pytest | 6 |
1,673 | 28,833,074 | Aggregate group with multi-level columns | <p>I have a grouped DataFrame which i want to aggregate with a dictionary of functions which should map to certain columns. For single-level columns this is straightforward with <code>groups.agg({'colname': <function>})</code>. I am struggling however to get this working with multi-level columns, from which i onl... | <p>I don't think there is a short-cut for this. Fortunately, it is not too hard to build the desired dict explicitly:</p>
<pre><code>result = groups.agg(
{(k1, k2): funcs[k1] for k1, k2 in itertools.product(lev1,lev2)})
</code></pre>
<hr>
<pre><code>import itertools
import numpy as np
import pandas as pd
lev1 =... | python|pandas | 4 |
1,674 | 14,513,717 | Tracking the number of recursive calls without using global variables in Python | <p>How to track the number of recursive calls without using global variables in Python. For example, how to modify the following function to keep track the number of calls?</p>
<pre><code>def f(n):
if n == 1:
return 1
else:
return n * f(n-1)
print f(5)
</code></pre> | <p>Here's a neat trick that doesn't use a global: you can stash the counter in the function itself.</p>
<pre><code>def f(n):
f.count += 1
if n == 1:
return 1
else:
return n * f(n-1)
</code></pre>
<p>After which:</p>
<pre><code>>>> f.count = 0 # initialize the counter
>>>... | python|recursion | 10 |
1,675 | 68,594,134 | Convert dict to list with same keys, values and layout | <p>I´m trying to extract several keys/values out of a List.</p>
<p>My List:</p>
<pre><code>a = [
{
"id": "1",
"system": "2",
},
{
"id": "3",
"system": "4",
}
]
</code></pre>
<p>No... | <p>Is this your your expected output:</p>
<pre class="lang-py prettyprint-override"><code>a = [
{
"id": "1",
"system": "2",
},
{
"id": "3",
"system": "4",
}
]
c = list()
for ... | python|list|dictionary|extract | 1 |
1,676 | 57,260,056 | How can I get 2 target values? | <p>so I am currently writing a program that can make predictions of longitude and latitude values. So far, my program can make predictions for 1 target value, but I need it to make 2. How should I go about doing that.</p>
<pre><code>column_names = ['longitude', 'Latitude']
raw_dataset = pd.read_csv('loglat.csv', names... | <p>I would suggest using Model API instead of Sequential API.</p>
<pre><code>from tf.keras.layers import Input, Dense
from tf.keras.models import Model
def build_model():
X = Input(shape=[len(train_dataset.keys())])
hidden_1 = Dense(64, activation=tf.nn.relu)(X)
hidden_2 = Dense(64, activation=tf.nn.relu... | python|tensorflow|keras | 0 |
1,677 | 54,092,650 | Retrieve a word from file name in python | <p>I have list of 5 excel files in a specific path as mentioned below : <code>'Z:\\Ruchika\\Citymax_Dec06\\SVCDs\\**\\*Claypot*.csv'.</code>
The list of 5 excel files and the paths are as per below</p>
<pre><code>['Z:\\Ruchika\\Citymax_Dec06\\SVCDs\\December - SVCD\\UAE _ Citymax _Claypot_ Burdubai_fullcampaignfile.c... | <p>I'm guessing it can be any month, so why not just check for months:</p>
<pre><code>filename = r'Z:\Ruchika\Citymax_Dec06\SVCDs\December - SVCD\UAE _ Citymax Claypot Burdubai_fullcampaignfile.csv'
for month in ['October', 'November', 'December']: # List of months
if month in filename:
print('Month is:',... | python|string|pandas|filenames|series | 1 |
1,678 | 44,727,726 | Nested list to a dictionary of index counts | <p>I'm very new to Python 3 and I'm working with Keras sigmoid activations which produce a nested list of probabilities.</p>
<p>I have a nested list that looks something like this:</p>
<pre><code>[[0.1, 0.2, 0.3, 0.2, 0.4, 0.5]
[0.2, 0.3, 0.3, 0.3, 0.2, 0.1]
...
[0.1, 0.1, 0.4, 0.5, 0.1, 0.2]]
</code></pre>
<p>Wh... | <p>With <code>a</code> as the list of lists of same lengths, we could convert to an array, giving us a <code>2D</code> array. Then, compare against <code>2</code> and then sum the <code>True</code> matches along each column, as the counts. Finally setup the output dictionary from it.</p>
<p>Thus, one implementation ... | python|list|numpy|dictionary|keras | 4 |
1,679 | 29,782,854 | SQLAlchemy + MSSQL - Possible to tell using reflection if table column is a computed column? | <p>I have a table in MSSQL that uses a number of "computed" columns. Using reflection, is it possible to tell when inspecting one of these columns that they're computed rather than typical columns?</p> | <p>Yes you use the sys.columns table:</p>
<pre><code> -- object_id - tablename
-- name - column name
select case when is_computed=0 then 'Not Computed'
else 'Computed'end [Is Computed]
from sys.columns
where object_id=object_id('dbo.x1') and name ='i1'
</code></pre> | python|sql-server|sqlalchemy | 1 |
1,680 | 46,545,404 | Installing python-igraph for python 3.6 on Windows | <p>I want to install the python-igraph package, but I am currently using python 3.6.1 and I don't find any installer for this new version of python. Do you know how can I install python-igraph for this version?</p>
<p>I have tried to install python-igraph for older versions from anaconda cloud but a version problem oc... | <p>Now, you can download <a href="https://www.lfd.uci.edu/~gohlke/pythonlibs/#python-igraph" rel="nofollow noreferrer">'python_geohash‑0.8.5‑cp36‑cp36m‑win_amd64.whl'</a>.</p>
<p>Use the following command to install:</p>
<pre><code>pip install python_geohash‑0.8.5‑cp36‑cp36m‑win_amd64.whl
</code></pre>
<p>Then you c... | installation|anaconda|igraph|python-3.6 | 0 |
1,681 | 49,676,630 | Python: Pearson's r | <p>So this is my code for calculating the correlation between two variables using pearson's r. </p>
<pre><code>def correlation(x, y):
std_x = (x - x.mean()) / x.std(ddof=0)
std_y = (y - y.mean()) / y.std(ddof=0)
return (std_x * std_y).mean()
</code></pre>
<p>I understand that in order to do so, one needs... | <p>I think you get confused on the formula of Pearson's coefficient. Say you have two random variables X and Y. Then Pearson's coefficient is defined as</p>
<p><code>r = Cov(X, Y)/(s_X*s_Y)</code></p>
<p>Where <code>Cov(X, Y)</code> is the covariance between X and Y, and <code>s_Y</code> and <code>s_Y</code> their st... | python|correlation|data-analysis|pearson | 0 |
1,682 | 49,617,465 | weird behavior when importing os.path | <p>I'm not quite sure this question belong to StackOverflow and not other SE website, but since it's python related I thought it might fit.</p>
<p>Recently, I started getting error in my IDE (details on my IDE below) - I get an error "cannot find reference 'path' in 'os.py'"
Looking into os.py, I realize that os.path ... | <p>It's a bug that was fixed in 2018.1.1 <a href="https://youtrack.jetbrains.com/issue/PY-28764" rel="noreferrer">https://youtrack.jetbrains.com/issue/PY-28764</a></p> | python|linux|pycharm | 11 |
1,683 | 49,496,650 | Map already designed mysql tables to sqlachemy | <p>I am coming from a place where the database designer/administrator gives you a MySQL database already designed with all the tables together with the functions, triggers etc and all you have to do is perform CRUD on the tables.</p>
<p>So i was wondering if there was a way to use sqlachemy to map to the already desig... | <p>Hi have you take a look at the <a href="http://docs.sqlalchemy.org/en/latest/orm/extensions/automap.html" rel="nofollow noreferrer">Automap</a> of <code>SQLAlchemy</code>. It might do the trick</p>
<p>Apparently, it seems that it is not enough so :</p>
<pre><code>from sqlalchemy.ext.automap import automap_base
fro... | python|sqlalchemy | 2 |
1,684 | 49,772,706 | How to initialize a tuple of lists to columns of an existing DataFrame in python pandas | <p>I have a function which takes the text as input and returns a tuple of lists. I want to convert the tuple into columns of an existing DataFrame.</p>
<pre><code>def func(text):
// some code //
return (tuple)
</code></pre>
<p>The tuple is in this format:</p>
<pre><code>(['1','2','3'],['abc','def','efg'])
</... | <p>I believe you need convert output to <code>Series</code> if need columns of <code>list</code>s:</p>
<pre><code>df = pd.DataFrame({'col_text':range(5)})
def func(text):
a = (['1','2','3'],['abc','def','efg'])
return pd.Series(a)
df[['col1','col2']] = df.col_text.apply(func)
print (df)
col_text col... | python|pandas|tuples | 1 |
1,685 | 21,058,406 | Multiple User extended objects in django | <p>Can we use multiple user extended objects in the same app for eg I have a model Teachers and other students in my app with both of them related to User by oneToone field but with some different extended properties so can anyone plz tell me how to configure this using User property and declaring both as AUTH_PROFILE_... | <p>The answer to <code>Can we use multiple user extended objects in the same app?</code> is <strong>No</strong></p>
<p>The answer to <code>So can anyone please tell me how to configure this using User property?</code></p>
<p>Maybe this can Work</p>
<pre><code>................. #User Code
## this function mus be i... | python|django|models | 0 |
1,686 | 53,582,471 | What list functions are true functions in python? | <p>By 'true function' I mean a function that cannot be recreated with ordinary python logic. For example the append function could simply be done by creating a list one larger (through lens if you dont define that as a function) than that of the original, and then transfering the contents plus that one from a user inp... | <p>If I understand your question correctly, the answer is none. You can implement the entire specification of python, in python. It is self-hosting, as are many other languages.</p> | python|list | 0 |
1,687 | 46,091,924 | Python: How to drop a row whose particular column is empty/NaN? | <p>I have a csv file. I read it:</p>
<pre><code>import pandas as pd
data = pd.read_csv('my_data.csv', sep=',')
data.head()
</code></pre>
<p>It has output like:</p>
<pre><code>id city department sms category
01 khi revenue NaN 0
02 lhr revenue good 1
03 lhr rev... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.dropna.html" rel="noreferrer"><code>dropna</code></a> with parameter <code>subset</code> for specify column for check <code>NaN</code>s:</p>
<pre><code>data = data.dropna(subset=['sms'])
print (data)
id city department sms cat... | python|pandas|dataframe | 72 |
1,688 | 46,173,312 | form_valid cannot be called in Django | <p>I followed an excellent guide (<a href="https://matthewdaly.co.uk/blog/2016/03/26/building-a-location-aware-web-app-with-geodjango/" rel="nofollow noreferrer">https://matthewdaly.co.uk/blog/2016/03/26/building-a-location-aware-web-app-with-geodjango/</a> ) and developed an application in Django 1.9 / Python 3 which ... | <p>In template lookup.html you have set:</p>
<p><code><form role="form" action="/gigs/" method="post"></code></p>
<p>Try changing it to:</p>
<p><code><form role="form" method="post"></code></p> | python|django|geodjango|formview | 0 |
1,689 | 55,027,075 | Generate all possible permutations for 'n' boolean elements that have at most 'm' elements that are 1 or True | <p>I want to generate a full list of permutations of 4 elements that have at most two '1'.</p>
<p>For example I have n= 4 and m = 2:</p>
<p>I want all the permutations that have at most two '1' in it:</p>
<p>[1,0,0,0], [0,1,0,0],[0,0,1,0],[0,0,0,1],
[1,0,1,0], [0,0,1,1], [1,1,0,0], [1,1,0,0], [1,0,0,1]... you get t... | <p>The set of permutations of a boolean array of length <code>n</code> with exactly <code>m</code> true values is essentially the same as the set of <code>m</code>-combinations of the a set of <code>n</code> things, which is what is returned by <code>itertools.combinations</code>. (The <code>n</code> things, in this ca... | python|algorithm|permutation | 3 |
1,690 | 73,770,412 | Need to use the "Google-cloud-ndb" library in Python 2.7 version | <p>We are currently using the Python 2.7 and Google App Engine NDB client.
Planning to migration from Google App Engine to Google Cloud NDB</p>
<p>As per docs, "google-cloud-ndb" library officially supports for Python 2.7 and Python 3.x as well.
So, we are trying to access the datastore through google-cloud-n... | <p>In Google App Engine, Python 2.7 doesn't support the use of <code>requirements.txt</code> file. This means you have to install all the modules/libraries you need for your App and deploy it together with your App to production. In your specific case, it means you have to install <code>google-cloud-ndb</code>library.<... | google-cloud-datastore|google-app-engine-python | 0 |
1,691 | 73,637,365 | How to convert a json object into a dataframe when arrays are of different lengths? | <p>I am trying to convert a json format into a dataframe but getting an error saying "All arrays must be of the same length".
Below is the code. Any advice are highly appreciated.</p>
<p>I have the following codes</p>
<pre><code>import pandas as pd
import requests
import json
from pandas import json_normalize... | <p>Here is how to convert the entire json using Pandas <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.from_dict.html" rel="nofollow noreferrer">from_dict</a> and <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.transpose.html" rel="nofollow noreferrer">transpose</a> (T) met... | python-3.x|pandas|dataframe|python-requests | 1 |
1,692 | 13,117,050 | Extracting email body in python | <p>When an email is being sent to a computer, the DATA section of the message always ends with the character sequence <code><CRLF>.<CRLF></code> (see <a href="https://www.rfc-editor.org/rfc/rfc2821#page-33" rel="nofollow noreferrer">RFC 2821</a> and a <a href="https://stackoverflow.com/questions/13108615/my... | <p>How about just doing this (assuming it isn't a multipart message):</p>
<pre><code>Message.get_payload().rsplit('\r\n', 2)[0]
</code></pre>
<p>In an example:</p>
<pre><code>>>> s = 'Hi,\r\n\r\nThis is my email.\r\n.\r\n'
>>> print s.rsplit('\r\n', 2)[0]
Hi,
This is my email.
>>>
</code>... | python|email|smtp | 1 |
1,693 | 12,716,608 | Can pymongo detect if a collection is capped? | <p>I'm writing functionality in Python to ensure the existence, type, and size of mongodb collections. Most of these collections are capped. I know that the mongo shell includes <code>mycollection.iscapped()</code>, but pymongo does not seem to support this functionality.</p>
<p>Within the context of pymongo, what i... | <p>Calling <code>mycollection.options()</code> returns a dict with <code>'capped': True</code> if it's a capped collection.</p> | python|mongodb|pymongo | 7 |
1,694 | 13,188,036 | Loading dictionary object causing memory spike | <p>I have a dictionary object with about 60,000 keys that I cache and access in my Django view. The view provides basic search functionality where I look for a search term in the dictionary like so:</p>
<pre><code>projects_map = cache.get('projects_map')
projects_map.get('search term')
</code></pre>
<p>However, just ... | <p>..what about using some appropriate service for caching, such as <a href="http://redis.io/" rel="nofollow">redis</a> or <a href="http://memcached.org/" rel="nofollow">memcached</a> instead of loading the huge object in memory python-side? This way, you'll even have the ability to scale on extra machines, should the ... | python|django | 4 |
1,695 | 41,117,813 | I have a function within a function, how do I break out of them both at once? | <p>probably a simple fix but i just cant work it out,</p>
<p>Basically this is a little program I made to calculate the hours I've worked in a day in decimal format, (becasuse I have to do it like that for my timesheet for work) works perfectly fine, but I decided to add in a feature where if I enter restart at anytim... | <p>You can use your own <code>Exception</code>s for this purpose. Just make sure, that you don't leave them uncaught.</p>
<p>Have a look at this exemplary implementation:</p>
<pre><code>import datetime
class RestartTimeException(Exception): pass # If user requests restart
class StopTimeException(Exception): pass ... | python|function|python-3.x | 1 |
1,696 | 38,353,089 | Django SMTPServerDisconnected: Connection unexpectedly closed using Postfix on Centos | <p>I have installed Postfix on Centos 7 and have successfully configured it to send mail (tested with command line program MailX).</p>
<p>However, when trying to send mail through Django shell or my Django website I am getting:</p>
<pre><code>File "/usr/lib64/python2.7/smtplib.py", line 367, in getreply
raise SMT... | <p>Maillog highlighted:</p>
<blockquote>
<p>fatal: no SASL authentication mechanisms</p>
</blockquote>
<p>Resolved with:</p>
<pre><code>yum install cyrus-sasl-plain
</code></pre> | python|django|centos|sendmail|postfix | 1 |
1,697 | 30,818,410 | Can not connect to an abstract unix socket in python | <p>I have a server written in c++ which creates and binds to an abstract unix socket with a namespace address of <code>"\0hidden"</code>. I also have a client which is written in c++ also and this client can <strong>successfully</strong> connect to my server. BTW, I do not have the source code of this client. Now I am ... | <p>Your C++ doesn't do quite what you think it does. This line:</p>
<pre><code>strncpy(addr.sun_path, UD_SOCKET_PATH, sizeof(addr.sun_path)-1);
</code></pre>
<p>Copies a single null character <code>'\0'</code> into <code>addr.sun_path</code>. Note this line in the manpage for <code>strncpy()</code>:</p>
<blockquote>... | python|c++|sockets|unix|unix-socket | 3 |
1,698 | 40,300,782 | Unhashable type : 'list' Error | <p>I'm getting this error for the following code </p>
<pre><code>def cleaning(CURRENT,STRING,NEXT):
data.ix[data[NEXT].str.contains(STRING,na=False),CURRENT] =...
data[NEXT][data[NEXT].str.contains(STRING,na=False)]
d = ['lower','Less']
c = a[5:]
for x,y in zip(range(len(c)),d):
cleaning(c[x],d,c[x+1])
... | <p>You are passing in <code>d</code>, a list, as the <code>STRING</code> argument:</p>
<pre><code>d = ['lower','Less']
# ...
cleaning(c[x],d,c[x+1])
# ^
</code></pre>
<p>Your second example works, you pass in <code>y</code> instead, which is a single element from the <code>b</code> list:</p>
<pre... | python|pandas|for-loop|dictionary | 1 |
1,699 | 29,233,801 | How to break a while loop by not entering a value? | <p>I'm trying to write a very simple program that uses a <code>while</code> loop to read in a series of <code>float</code> values and calculate their mean, terminating the loop when the user simply presses <kbd>Enter</kbd> without supplying a value.</p>
<p>This is what I have so far, but obviously it produces an error... | <p>You need to test for an <em>empty string</em>, and do so <em>before</em> converting to a float:</p>
<pre><code>while True:
a = raw_input("Number: ")
if not a:
break
total = total + float(a)
num_values = num_values + 1
</code></pre>
<p>This loop is simply endless, and a <code>break</code> is... | python|loops|while-loop|break | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.