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 |
|---|---|---|---|---|---|---|
10,100 | 62,970,007 | How can I extract out the value of X, Y, Z in a list of dataset in Python? | <p>I was given a set of dataset as show below,</p>
<p>How can I extracted out the value of X, Y, Z of each series in Python?</p>
<p>I actually later need to calculate the standard deviation of each series. (x, y, z standard deviation)</p>
<pre><code>{'deviceTimestamp': 166230, 'x': 3.5538, 'y': -9.7006, 'z': 3.3077}, {... | <p>You can use a list comprehension to construct a list with x, y, z.</p>
<pre><code>data = [
{'deviceTimestamp': 166230, 'x': 3.5538, 'y': -9.7006, 'z': 3.3077},
{'deviceTimestamp': 166250, 'x': -1.4629, 'y': -7.0692, 'z': 2.2308},
{'deviceTimestamp': 166260, 'x': -6.7571, 'y': -5.0299, 'z': -0.076923}, ... | python | 1 |
10,101 | 62,950,000 | Syntax error trying to pass arguments to postgreSQL command with poscopg2 | <p>The line of code below gives this error:</p>
<p>""'test_1'"
syntax error at or near "'test_1'"
LINE 1: select exists(select 1 from 'test_1' where ID = 'd5b3e5f6-45...</p>
<p>I'm trying to pass the arguments "test_1" (table name) and a certain ID 'd5b...', however I think they're be... | <p>You can use f-strings for string interpolation like this:</p>
<pre><code>cursor.execute(f"select exists(select 1 from {sub_root} where ID = {ID})")
</code></pre>
<p>Note: If <strong>ID</strong> variable is of type string then place it in between the single quotes like this <strong>'{ID}'</strong></p> | python|python-3.x|postgresql|psycopg2 | -2 |
10,102 | 32,559,792 | How to get redis server working under virtualenv for mac users? | <p>I have installed <code>celery</code> and <code>redis</code> using <code>pip install redis celery</code> within my virutalenv <code>'djangoscrape'</code> . Typing <code>redis-server</code> <code>-bash: redis-server: command not found.</code> Please what am i doing wrong?</p>
<p>Also typing: </p>
<blockquote>
<p>/... | <p><code>pip</code> will only install the Python libraries for connecting to a redis database. You need to install the redis server itself: probably the easiest way to do that on a Mac is to use Homebrew.</p> | python|django|redis|celery|django-celery | 7 |
10,103 | 44,040,297 | ubuntu : Schedule python scripts using Fork | <p>I am trying to use <code>fork()</code> in Ubuntu 16.04 to execute a python script at some scheduled time. As I read through the docs, I did not come across the scheduling option in <code>fork()</code>.<br></p>
<blockquote>
<p>Is fork() having an option to schedule?<br></p>
</blockquote>
<p>Presently, I am using ... | <p>Advanced Python Scheduler can help: <a href="http://apscheduler.readthedocs.io/en/latest/" rel="nofollow noreferrer">http://apscheduler.readthedocs.io/en/latest/</a></p>
<p>Here is a sample code for using it:</p>
<pre><code>from apscheduler.schedulers.blocking import BlockingScheduler
def some_job():
print "D... | python|linux|ubuntu|cron|fork | 0 |
10,104 | 43,977,236 | Retrieving data from JSON in python, and if object name matches, then store the key of that object | <p>I am making REST calls on a server. The first REST call gets all the projects and from that I store the project's IDs in an array.
Below is the JSON.
For e.g. it would return something like this:</p>
<pre><code>[
{
"expand": "description,lead,url,projectKeys",
"self": "http://localhost:8080/re... | <pre><code>projectNames = []
for id in ids:
url = 'http://localhost:8080/rest/api/2/project/'+id+'/role/10100'
response = requests.get(url,
auth = ('*', '*'))
data = response.json()
for actor in data["actors"]:
if actor["displayName"] and actor["displayName"] == "group2... | python|json|rest | 1 |
10,105 | 54,625,377 | why MSE on test set is very low and doesn't seem to evolve (not increasing after increasing epochs) | <p>I am working on a problem of predicting stock values using LSTMs. </p>
<p>My work is based on the following <a href="https://www.datacamp.com/community/tutorials/lstm-python-stock-market" rel="nofollow noreferrer">project</a> .
I use a data set (time series of stock prices) of total length 12075 that I split into t... | <p>The reason behind above difference in MSE between training and test is that we are not computing the same thing. During training, the MSE is the average of the sum of errors over time steps for every sample in the training data and so it is big. During test, we are making N=50 predictions and computing the average e... | tensorflow|machine-learning|lstm|recurrent-neural-network|mse | 0 |
10,106 | 34,772,449 | Heroku: Celery not found | <p>I am trying to port an application over to run on Heroku but ran into a snag. It's a Python3/Django application, and the web app (using gunicorn) runs properly. When I add a worker into my Procfile, it crashes with the message:</p>
<pre><code>2016-01-13T16:40:07.985725+00:00 heroku[worker.1]: Starting process with ... | <p>Switching to heroku-buildpack-multi.git caused the issue because I didn't fully grok buildpacks yet. I needed to add the python buildpack into .buildpacks</p> | django|python-3.x|heroku|celery | 0 |
10,107 | 34,714,092 | How to compute gradients to fool an image classifier? | <p>I am trying to get the standard trick-an-image-classifier example working in <code>TensorFlow</code>. </p>
<p>(That is, adjust the input image by following the gradient so it is misclassified, e.g., <a href="https://codewords.recurse.com/issues/five/why-do-neural-networks-think-a-panda-is-a-vulture" rel="nofollow"... | <p>The reason that <code>tf.gradients()</code> returns <code>[None]</code> is that <code>input_tensor</code> is subjected to a non-differentiable transformation (i.e., JPEG decoding and a cast) before it is fed into the Inception network. Instead, you should operate on the <strong>result</strong> of the JPEG decoding ... | python|computer-vision|tensorflow | 2 |
10,108 | 12,311,128 | Combine sqlite database files (multiple tables per file) into one file | <p>I am using sqlite3 in python and I have multiple database files which I now want to combine into one big file. Each database is associated with a specific topic but they all share the same structure. I'll be querying them separately -- I just want to combine them into one file so that it's easier to move them around... | <p>If you want to move whole tables (as in, not merge them but bring in tables from a different file), you can do so in unix like so:</p>
<pre><code> sqlite3 'from_this_db.db' '.dump' | sqlite3 -batch 'to_this_db.db'
</code></pre> | python|sqlite | 1 |
10,109 | 41,769,372 | Identify Visually Similar Strings in Python | <p>I am working on a python project in which I need to filter profane words, and I already have a filter in place. The only problem is that if a user switches a character with a visually similar character (e.g. <code>hello</code> and <code>h311o</code>), the filter does not pick it up. Is there some way that I could fi... | <p>What about translating <code>l331sp33ch</code> to <code>leetspeech</code> and applying a simple levensthein distance? (you need to <code>pip install editdistance</code> first)</p>
<pre><code>import editdistance
try:
from string import maketrans # python 2
except:
maketrans = str.maketrans # python 3
t = ma... | python|filter | 1 |
10,110 | 47,121,960 | python - project text to screen on transparent unobtrusive overlay box | <p>I've found <a href="https://stackoverflow.com/questions/45427411/simple-way-to-display-text-on-screen-in-python">some answers</a> regarding displaying text on screen with Python. There's a lot about <a href="https://stackoverflow.com/questions/4485610/python-message-box-without-huge-library-dependancy">pop up messag... | <p><strong>In your Case QT Or PYQT is the best!</strong></p>
<p><strong>why?!</strong></p>
<p>Since you are on windows and you are a web developer, I highly recommend that you install ANACONDA. This way the environment variables are set automatically and you don't need to worry about anything else. There are many use... | python|windows | 2 |
10,111 | 70,999,063 | I'm making a temperature converter app, but there's something I don't understand | <p>I am making a temperature translation application, but there are some points that I do not understand. What operator do I need to use when converting kelvin to fahrenheit?</p>
<p><a href="https://i.stack.imgur.com/vR3uu.png" rel="nofollow noreferrer">code</a></p>
<p>I set the kelvin value to 273.15 and the degree va... | <blockquote>
<p>What operator do I need to use when converting kelvin to fahrenheit</p>
</blockquote>
<p>This is the formula</p>
<blockquote>
<p>°F =(K - 273.15)* 1.8000+ 32.00</p>
</blockquote>
<p>You already have <code>K</code>. Those operators shown are the same in Python</p> | python|math | 0 |
10,112 | 11,613,941 | twisted wait for another client | <p>This is my render_GET function in class inherited from resource.Resource in twisted HTTP server:</p>
<pre><code> def render_GET(self, request):
file = request.args['file'][0]
altitude, azimuth, distance = request.args['position'][0].split(",")
self.update_render(file, altitude, a... | <p>You never want to write a while loop like that in a Twisted-using application.</p>
<p>Ideally, you want a better API than <code>update_render</code> - one that returns a Deferred. A Deferred gives you a uniform, composable, convenient API for managing callbacks. Callbacks are fairly central to programming with Tw... | python|twisted | 1 |
10,113 | 58,478,516 | iterate a string based on another string | <p>I need to iterate variable Y, compare each iteration with variable
sublist Variable X and create a new string with results.</p>
<pre><code>Y = 'ABCEF'
X =[('A', 1),('B', 4),('C', 6),('D', 7),('E', 8),('F', 9),('G', 10),('H', 11),('I', 12),('J', 13),('K', 14),('L', 15),('M', 16)]
</code></pre>
<p>The result is b... | <p>You can creating a mapping dict from <code>X</code> so that you can iterate through <code>Y</code> to map each character to its value before joining them into a new string:</p>
<pre><code>mapping = dict(X)
Z = ''.join(str(mapping[c]) for c in Y)
</code></pre>
<p><code>Z</code> becomes: <code>'14689'</code></p> | python|string | 2 |
10,114 | 46,724,984 | Align is not in correct format in python openpyxl | <p>I tried a program in python to read data from excel when I retrieve data from Excel its not displaying in correct format.</p>
<p>Here is my sample excel data:</p>
<p><a href="https://i.stack.imgur.com/BJ9Rh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BJ9Rh.png" alt="enter image description h... | <p>The issue is with the second <code>print('')</code>, which induces an unnecessary line break after displaying your data.</p>
<pre><code>for r in range(1,rows+1):
for c in range(1,columns+1):
d=sheet.cell(row=r,column=c)
print('%-8s'%d.value , end='')
print('') <... | python|python-3.x|openpyxl | 0 |
10,115 | 37,826,647 | Clearing Python Flask cache does not work | <p>I have the following three files.</p>
<p>app.py</p>
<pre><code>from flask_restful import Api
from lib import globals
from flask import Flask
from flask.ext.cache import Cache
globals.algos_app = Flask(__name__)
#cache in file system
globals.cache = Cache(globals.algos_app, config={'CACHE_TYPE': 'filesystem', 'C... | <p>I am not sure if it is the best way, but I did it using the following way.</p>
<pre><code>class Test(Resource):
def get(self):
return globals.cache.get('curr_time')
def post(self):
result = self.someMethod()
globals.cache.set('curr_time', result, timeout=3600)
def someMethod(s... | python-2.7|flask-cache | 0 |
10,116 | 37,794,352 | How to get rows of a tsv file with common values in one of the columns using pandas? | <p>I have a tsv (tab separated) file with data like this:</p>
<pre><code>1 102 apple
2 102 orange
3 103 grapes
4 103 banana
5 103 carrot
</code></pre>
<p>I want to get the rows of the file which have common values in the second field. And, then I want to perform operations on individual elements of each group. So I a... | <p>Would be helpful to see the output of <code>df.info()</code> after <code>pd.read_csv()</code>. In any case, you should probably do </p>
<pre><code>pd.read_csv(file, sep='\t', header=None)
</code></pre>
<p>and then set the columns using </p>
<pre><code>df.columns = ['A', 'B', 'C']
</code></pre>
<p>or do the same ... | python|python-2.7|csv|pandas | 2 |
10,117 | 37,615,003 | Python3 regex issue | <p>I'm writing a solution to a problem in which I need to parse the command line arguments. Before parsing, I first did the validation.</p>
<p>Permissible arguments are:</p>
<pre><code>someKey=(apps IN (app1))
someKey=(apps IN (app1,app2))
someKey=(apps IN (app1,app2, app3))
</code></pre>
<p>But if comma is at the e... | <p>You can use <code>\(apps\sIN\s\((app\d+)(,\s*app\d+)*\)\)</code></p>
<p>This will ensure that at least one occurrence of <code>app\d+</code> exists, and every subsequent occurrence has to be preceded by a comma (and optional whitespace).</p>
<p><a href="https://regex101.com/r/yG9aF3/3" rel="nofollow">Demo</a></p>
... | python|regex | 0 |
10,118 | 27,491,513 | How can I get python to use css <![if !IE> correctly | <p>I am trying to create a dynamic page that has to do some work behind the scene/server side and also show a web page where the person can retrieve what we have processed server side. So just as a base template for a page I have this:</p>
<pre><code>#!/usr/bin/python
import cgi, os, sys, commands
print "Content-type... | <p>You can try this:</p>
<pre><code>print '<![if !IE]> <link href="../styles/screen.css" rel="stylesheet" type="text/css" media="screen" /> <![endif]>\n'
</code></pre> | python|html|css|cgi | 1 |
10,119 | 27,876,154 | Iterate Array/List in Python for Alpha Numeric | <p>What's the best method to iterate through (A-Z + 0-9) on 3 separate occasions that are all exclusive.
For instance AAA, AAB..AA0, AA1..ZZ0, ZZ1...all the way to 999. There is no restriction in whether a number or character appears in either slot.</p>
<pre><code>chars = [string.ascii_uppercase + string.digits]
genn... | <p>You dont need to put the string in list and dont use <code>list</code> for an generator , and use a list comprehension for join the products :</p>
<pre><code>>>> import string
>>> chars = string.ascii_uppercase + string.digits
>>> genned_chars=[''.join(i) for i in itertools .product(char... | python | 4 |
10,120 | 27,723,178 | BeautifulSoup to extract csv data from website | <p>I have used beautiful soup4 to get the following from the command</p>
<pre><code>print(soup.prettify)
<html>
<head>
<title>
Euro Millions Winning Numbers
</title>
<body>
<pre> Euro Millions Winning Numbers
No., Day,DD,MMM,YYYY, N1,N2,... | <p>You can use <code>BeautifulSoup</code> to find the <code>pre</code> tag and extract all text nodes from it. Then, split each text node by new-line and get rid of anything not starting with <code>No.</code> or a digit:</p>
<pre><code>import csv
from bs4 import BeautifulSoup
data = """
your HTML here
"""
soup = Bea... | python-3.x|beautifulsoup | 0 |
10,121 | 27,626,821 | Django cannot see the new column I've added to both my table and my model | <p>Here is the 'maps_accesspoint' table in a MySQL database:</p>
<pre><code>id int(11) NO PRI auto_increment
name varchar(255) NO
location varchar(255) NO
geolocation varchar(255) NO
restricted_area varchar(3) YES
</code></pre... | <p>Try to not update manually your database. The easiest solution might be to delete maps_accesspoint table and run syncdb again. <br></p>
<p>Remember, every time when you change your model you have to update your database. You can do it manually or using this <a href="http://south.aeracode.org" rel="nofollow">south</... | python|mysql|django|python-2.7|django-models | 1 |
10,122 | 27,674,880 | Python: Replace a number in array with a string | <p>I have an array of numbers, which I would like to replace with a string depending on some condition. I can replace them with numbers:</p>
<pre><code>d_sex = rand(10)
d_sex[d_sex > 0.5] = 1
d_sex[d_sex <= 0.5] = 0
d_sex
</code></pre>
<p>But I cannot do <code>d_sex[d_sex>0.5] = "F"</code>. How would I do th... | <p><a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow">numpy.where</a> is the equivalent of Julia's <code>ifelse</code>:</p>
<pre><code>>>> np.where(d_sex > 0.5, 'M', 'F')
array(['F', 'M', 'M', 'F', 'F', 'M', 'F', 'M', 'F', 'F'],
dtype='|S1')
</code></pre> | python|arrays|numpy | 4 |
10,123 | 72,323,936 | Is it possible to make the given inputs into seperate variables? | <pre><code>
a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p = map(int, nums.split(' '))
</code></pre>
<p>print (a)
print (b)</p>
<p>Is it possible to make the inputs given in <code>nums</code> into their own separate variables.</p> | <p>The map function returns a generator object, You can cast it to a list by calling <code>list()</code>.</p>
<p>For example:</p>
<pre class="lang-py prettyprint-override"><code>lst = list(map(int, nums))
</code></pre>
<p>Then you can access each item by indexing</p>
<pre class="lang-py prettyprint-override"><code>a =... | python|variables | 1 |
10,124 | 43,458,185 | How to create a spreadsheet like layout for data table? | <p>I am trying to create a online dashboard which populates all the data from my database into a table and im using javascript datatable plugin for it. But I want to create a better way and want a layout similar to google spreadsheet, in which the spreadsheet tuple can be edited or saved similar to google spreadsheet.<... | <p>It may be a bit late, but as Anddrw already stated you could use pandas dataframes for this. There is a direct export-to-html function for dataframes. You can style the output and apply conditional formatting with <a href="https://pandas.pydata.org/pandas-docs/stable/style.html" rel="nofollow noreferrer">CSS-like no... | javascript|jquery|python|mysql | 0 |
10,125 | 67,161,539 | Faster way to sum all combinations of rows in dataframe | <p>I have a dataframe of 10,000 rows that I am trying to sum all possible combinations of those rows. According to my math, that's about 50 million combinations. I'll give a small example to simplify what my data looks like:</p>
<pre><code>df = Ratio Count Score
1 6 11
2 7 ... | <p>After these improvements it takes <strong>~2 minutes</strong> to run for 10k rows.</p>
<ol>
<li><p>For the sum computation, you can pre-compute <code>cumulative sum(cumsum)</code> and save it. <code>sum(i to j)</code> is equal to <code>sum(0 to j) - sum(0 to i-1)</code>.
Now <code>sum(0 to j)</code> is <code>cumsum[... | python|pandas|performance|numpy|combinations | 3 |
10,126 | 48,266,063 | Is there a way to communicate with Raspberry pi 3 using python 3 and MacOS? | <p>I have tried many different ways, but none of them worked. If you have a solution, can you provide a step-by-step description about it?</p> | <p>Use python <a href="https://docs.python.org/3/library/socket.html" rel="nofollow noreferrer">Socket</a> module. Here you can find <a href="https://www.tutorialspoint.com/python/python_networking.htm" rel="nofollow noreferrer">Socket's documentation for Python 3.x</a>. And here you can jump right into <a href="https:... | python|python-3.x|macos|raspberry-pi | 1 |
10,127 | 47,989,173 | Get top N largest rows of every group in a pandas DataFrame | <p>i have a dataframe</p>
<pre><code>val1 val1 distance
100 200 1.5
100 300 5.2
100 234 3.7
200 100 1.6
200 600 4.8
</code></pre>
<p>i want to find Top 2 distance rows for every <code>val1</code>.
i'e</p>
<p>for every <code>val1</code> get the top 2 minimu... | <p>It seems I was overanalysing your question, but a simple <code>sort_values</code>, followed by <code>groupby</code> + <code>head</code> should give you what you need.</p>
<pre><code>df.sort_values(['val1', 'distance']).groupby('val1').head(2)
val1 val2 distance
0 100 200 1.5
2 100 234 3.7
... | python|pandas|dataframe|group-by|pandas-groupby | 4 |
10,128 | 51,531,224 | Non-contiguous data reading of binary file in python | <p>I have a binary file which contains time series from sensors.
Data format goes as follows:</p>
<p>#1(t0) #2(t0) #3(t0) ... #n(t0) #1(t1) #2(t1) #3(t1) ... #n(t1) ...</p>
<p>At a time, measured data from n sensors are stored in the file in binary format.
I would like to reconstruct the time seires of a sensor such... | <p>This simpler code may be faster. You might also want to look into using <code>mmap</code> to map the file into your process's address space, which lets you bypass a layer of kernel I/O calls.</p>
<pre><code>def collect_signal(fp, channel_no, stride, dtype):
byte_size = np.dtype(dtype).itemsize
fp.seek(chann... | python | 1 |
10,129 | 51,288,942 | How to transform values from a cell into new columns in Pandas? | <p>My dataframe looks like this:</p>
<pre><code>+-------+-----------------------------------------+
| Image | Bounding Boxes |
+-------+-----------------------------------------+
| a.jpg | xyz 0.1 0.2 0.3 0.4 |
| b.jpg | xyz 0.1 0.2 0.3 0.4 ijk 0.4 0.3 0.2 0.1 |
+-------+--... | <p>You can just use <a href="https://pandas-docs.github.io/pandas-docs-travis/generated/pandas.Series.str.split.html" rel="nofollow noreferrer"><code>str.split(' ', expand=True)</code></a> to split on the space, and then join with the <code>Image</code> Column:</p>
<pre><code>new_df = df[['Image']].join(df['Bounding B... | python|pandas|dataframe|data-science | 3 |
10,130 | 51,490,358 | the first x label is missing using matplotlib | <p>This is my data:</p>
<pre><code>a3=pd.DataFrame({'OfficeName':['a','b','c','d','e','f','g','h'],
'Ratio': [0.1,0.15,0.2,0.3,0.2,0.25,0.1,0.4]})
</code></pre>
<p>and this is my code to draw a bar chart:</p>
<pre><code>fig, ax = plt.subplots()
ind = np.arange(a3.loc[:,'OfficeName'].nunique()) # ... | <p>There is an easier way to produce your bar chart in Pandas:</p>
<pre><code>a3.set_index('OfficeName').plot.bar(width=0.35, legend=False)
plt.xticks(rotation=0, ha='center')
</code></pre>
<p>(You still need to set the x and y axis labels and the title.)</p> | python|pandas|matplotlib|label | 0 |
10,131 | 17,321,138 | How can I use a conditional expression (expression with if and else) in a list comprehension? | <p>I have a list comprehension that produces list of odd numbers of a given range:</p>
<pre><code>[x for x in range(1, 10) if x % 2]
</code></pre>
<p>That makes a filter that removes the even numbers. Instead, I'd like to use conditional logic, so that even numbers are treated differently, but still contribute to the l... | <p><code>x if y else z</code> is the syntax for the expression you're returning for each element. Thus you need:</p>
<pre><code>[ x if x%2 else x*100 for x in range(1, 10) ]
</code></pre>
<p>The confusion arises from the fact you're using a <em>filter</em> in the first example, but not in the second. In the second ex... | python|list-comprehension|conditional-operator | 447 |
10,132 | 64,521,320 | Python pandas dataframe: Count number of elements a in column greater or smaller than a threshold | <p>This code will count the number of elements in column <code>c2</code> that have value greater than or equal 3</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'c1': ['A', 'B','C','D','E'], 'c2': [3, 1, 0,2,5]})
count=df.loc[:,'c2']
count=count[~ (count<3)]
count=count.shape[0]
</code></pre>
<p>Is there a di... | <p>You can update your code to add the condition and do the count in one single line as below</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'c1': ['A', 'B','C','D','E'], 'c2': [3, 1, 0,2,5]})
count=df[df['c2'] >= 3].count().shape[0]
print(count) # prints 2
</code></pre> | python|pandas|dataframe | 2 |
10,133 | 64,476,745 | Tensorflow-Lite unresolved reference for tfLite!!.setUseNNAPI in kotlin Android App | <p>I am trying to run <a href="https://github.com/lmoroney/dlaicourse/tree/master/TensorFlow%20Deployment/Course%202%20-%20TensorFlow%20Lite/Week%202/Examples/Android%20Apps/object_detection" rel="nofollow noreferrer">this app</a> which is an object detection application. The app uses Tensorflow-Lite.</p>
<p>When tryin... | <p>Please check the build.gradle file for app.
If you see the below line or if the version is less than 2.3.0 update it to the latest version</p>
<p><strong>implementation 'org.tensorflow:tensorflow-lite:0.0.0-nightly'</strong></p>
<p>change it to</p>
<p><strong>implementation 'org.tensorflow:tensorflow-lite:2.3.0'</st... | android|android-studio|tensorflow|kotlin|tensorflow-lite | 6 |
10,134 | 69,902,184 | Python pandas how to transform defaultdict to csv format? | <p>So I have data that will appear in this format:</p>
<pre><code>defaultdict(<class 'list'>, {'ZY20': [545, 27, 402], 'ZYV0': [2190, 5,
78], 'ZZL0': [175, 21, 90]})
</code></pre>
<p>I want to take this data and parse it to look like this:</p>
<pre><code>ZY20 545 27 402
ZYV0 2190 5 78
ZZL0 175 21 90
</code></pre>... | <p>You can do</p>
<pre><code>out = pd.DataFrame.from_dict(d,'index')
Out[23]:
0 1 2
ZY20 545 27 402
ZYV0 2190 5 78
ZZL0 175 21 90
</code></pre> | python|pandas|csv | -1 |
10,135 | 55,672,513 | Why big numbers show only two reference even when you define new variables? | <p>When i use getrefcount method in sys module and try to count reference of certain big numbers (in this example 1000000) it shows two references. Now I know that these two references could be used by IDLE or python itself (as per the book) but when i introduce a variable a = 1000000 it should show 3 references but st... | <p>You seem to be assuming that every time you have <code>1000000</code> in your code, that refers to the same object. That's not the case.</p>
<p>What you have in your code are three different, unrelated <code>1000000</code> objects:</p>
<pre><code>In [1]: id(1000000)
Out[1]: 4328822600
In [2]: id(1000000)
Out[2]:... | python | 1 |
10,136 | 55,748,464 | Defined an ajax function in my urls.py file, but getting a 404 when invoking it in a test | <p>I'm using Django and Python 3.7. I have this in my urls.py file</p>
<pre><code>urlpatterns = [
path(r'^ajax/calculate_taxes/$', post, name='calculate_taxes'),
]
</code></pre>
<p>However, I'm getting a 404 when I try and invoke the logic in my test_views.py class ...</p>
<pre><code># Basic test to verify we ... | <p>You have to return a JsonResponse</p>
<pre><code>return JsonResponse(data)
</code></pre> | python|ajax|django|python-3.x|python-unittest | 0 |
10,137 | 73,277,756 | Allow the conversion a class instance into `Decimal` type | <p>Suppose I implement a class which maintains a <code>Decimal</code> value, and I'd like to be able to convert an instance of that class into <code>Decimal</code> type.</p>
<p>For example, given:</p>
<pre><code>from decimal import Decimal
class MyClass:
def __init__(self, data):
self.data = Decimal(data)
... | <p>The docs of <a href="https://docs.python.org/3/library/decimal.html#decimal.Decimal" rel="nofollow noreferrer"><code>Decimal</code></a> state that the argument can be</p>
<blockquote>
<p>an integer, string, tuple, float, or another Decimal object.</p>
</blockquote>
<p>So if your object is something else, then it won... | python|operator-overloading|decimal | 1 |
10,138 | 64,651,650 | Merging Pandas DataFrames by column | <p>I have two data frames:</p>
<pre><code>df1 = pd.DataFrame({'dateRep': ['2020-09-10', '2020-08-10', '2020-07-10',
'2020-24-03', '2020-23-03', '2020-22-03'],
'cases': [271, 321, 137,
8, 0, 1],
'countriesAndTerritories... | <p>You can use <code>df.append</code> with <code>df.combine_first()</code>:</p>
<pre><code>In [297]: x = df1.append(df2)
In [299]: x.date = x.dateRep.combine_first(x.date)
In [301]: x.country_refion = x.country_refion.combine_first(x.countriesAndTerritories)
In [308]: x = x.sort_values('date').drop(['dateRep', 'countr... | pandas|dataframe|join|merge | 1 |
10,139 | 64,712,343 | Add name of many directories to a filename | <p>I have a folder structure like this:</p>
<p>C:\Users\me\JupyterNotebooks\Work\LabCode\datafiles\2020_09sept_17\00\58</p>
<p>Under the last '58' folder, a file is placed; 00.avro</p>
<p>I would like to rename the file to: 2020_09sept_17_00_58_00.avro (adding the three last directories to the filename)</p>
<p>I am abl... | <p>Try this:</p>
<pre class="lang-py prettyprint-override"><code>for root, dirs, files in os.walk(r'C:\Users\me\JupyterNotebooks\Work\LabCode\datafiles\2020_09sept_17\00'):
if not files:
continue
dirnames = []
pref = root
for _ in range(3): # Collect the last 3 dir names
dirnames.... | python|directory | 0 |
10,140 | 64,689,935 | Cannot figure out inputting floats or integers into my neural-network | <p>Sorry if this is a trivial question, or just plain stupid, I'm just getting started with python and neural-networks... So I made this simple neural network off a tutorial and everything's working fine, my question is how I would go about changing my input and output goal, because at the moment I don't understand why... | <p>You need to know what <strong><code>batch size</code></strong> is, generally speaking, we usually input multiple samples into the NN, <code>batch size</code> is the num of samples, see, the input has <strong>at list 2 dim</strong> <code>[batch_size, fea_size]</code>, so we use ndarray to contain the input.</p>
<p>If... | python|arrays|neural-network|artificial-intelligence | 0 |
10,141 | 65,067,608 | tf.cast() causes my program to fail back propagation, how can I solve this problem? | <pre><code>import tensorflow as tf
tf.compat.v1.disable_eager_execution()
A = tf.constant([[1,7,3]],dtype=tf.float32)
B = tf.zeros_like([[1,0,0],[0,1,0]])
C = tf.cast(A,dtype=tf.int32)+B
f = tf.gradients(C,A)
with tf.compat.v1.Session() as sess:
print(sess.run(f))
</code></pre>
<p>I am using tensorflow 2.3.0 ver... | <p><a href="https://www.tensorflow.org/guide/autodiff#3_took_gradients_through_an_integer_or_string" rel="nofollow noreferrer">Tensorflow does not differentiate through integers</a>. Cast your int to float instead.</p>
<pre><code>import tensorflow as tf
tf.compat.v1.disable_eager_execution()
A = tf.constant([[1,7,3]]... | tensorflow|tensorflow2.0 | 0 |
10,142 | 71,928,675 | Subtracting dates in Python for Gantt chart | <p>I am following a tutorial to make a Gantt chart with this tutorial:
<a href="https://towardsdatascience.com/gantt-charts-with-pythons-matplotlib-395b7af72d72" rel="nofollow noreferrer">https://towardsdatascience.com/gantt-charts-with-pythons-matplotlib-395b7af72d72</a></p>
<p>I have tried to recreate part of the tes... | <p>You need to convert date column to datetime type first</p>
<pre class="lang-py prettyprint-override"><code>df['Start'] = pd.to_datetime(df['Start'])
df['End'] = pd.to_datetime(df['End'])
# Or
df[['Start', 'End']] = df[['Start', 'End']].apply(pd.to_datetime)
</code></pre> | python|pandas|gantt-chart | 1 |
10,143 | 68,690,415 | Enable tabs in pyqt after loading a directory | <p>I'm designing a pyqt app where the main layout has some tabs. The first tab is where a user loads a default directory (tab1). All the other tabs cant be enabled without loading a directory. I have been trying to enable the tabs after loading a directory but no success till now. If anyone could help me it will mean a... | <p>Create a signal for the first tab:</p>
<pre><code>from PyQt5.QtCore import *
class Test(QWidget):
directoryLoaded = pyqtSignal(str)
# ...
def loadworkdir(self):
global workdir
self.dialog = QFileDialog()
workdir = self.dialog.getExistingDirectory(None, "Select Folder",... | python|python-3.x|pyqt|pyqt5 | 1 |
10,144 | 71,561,441 | Interleaving tuple with predicates | <p>I need to define a function interleaved_tuple_picky that takes three arguments, tuple_a, tuple_b and predicate and return a tuple of values either from tuple_a or tuple_b. For all values x from tuple_a, we will add x to the final tuple if predicate(x) is True, else we will add the corresponding value from tuple_b. F... | <ul>
<li>You want to go through all pairs in the tuples <code>tuple_a</code> and <code>tuple_b</code>, so you need to iterate over <code>zip(tuple_a, tuple_b)</code>, so your generator expression becomes <code>(_____ for x, y in zip(tuple_a, tuple_b))</code></li>
<li>You want to select <code>x</code> if <code>predicate... | python | 3 |
10,145 | 67,584,932 | New rolling mean column which group by one column and find rolling mean of another column | <p>I have a dataframe df</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Date</th>
<th>Orders</th>
<th>Group</th>
</tr>
</thead>
<tbody>
<tr>
<td>1/1/2021 00:00:00</td>
<td>20</td>
<td>A</td>
</tr>
<tr>
<td>1/1/2021 00:12:00</td>
<td>100</td>
<td>B</td>
</tr>
<tr>
<td>2/1/2021 00:00:00</td>... | <p>This worked for me:</p>
<pre><code>df['Rolling Mean'] = df['Orders'].rolling(window=pd.Timedelta(days=14)).mean()
</code></pre>
<p>Note that the <code>min_periods</code> argument in the <code>pd.rolling()</code> method takes an integer and doesn't handle time series easily, so you'll need to overwrite the first 14 d... | python|pandas|group-by|mean|rolling-computation | 0 |
10,146 | 67,548,578 | Unable to access Widget ids in Python | <p>Code:</p>
<pre><code>from kivymd.app import MDApp
from kivy.properties import ObjectProperty
from kivy.lang import Builder
KV = """
MDScreen:
submit_btn: submit_btn
MDRaisedButton:
id: submit_btn
text:'Submit'
on_press: app.btn()
"""
class Test(MDApp):
... | <p>This is pretty similar to your previous question a few minutes ago: you have not set <code>self.submit_btn</code> to anything except None. It looks like you tried to in the kv rule, but you've actually set the property of the <code>MdScreen</code> instance which is your root widget, accessed as <code>self.root.submi... | python|kivy|kivy-language|kivymd | 1 |
10,147 | 67,463,806 | Vectorizing thetas, rs combinations with numpy | <p>I am generating thetas, radius ranges, cos_thetas and sin_thetas using numpy.</p>
<p>I am still left with code that is highly inefficient, in terms of getting those combinations.</p>
<p>I have tried to go down the path of vectorization but reshaping makes things worse.</p>
<p>I currently have the following code:</p>... | <p><a href="https://numpy.org/doc/stable/user/basics.broadcasting.html#broadcasting" rel="nofollow noreferrer">Broadcasting</a> is your friend:</p>
<pre><code>d = np.zeros((num_thetas*rs.size, 3), order = "F", dtype = int)
d[:,0] = np.repeat(rs, num_thetas)
d[:,1] = np.ravel(rs[:,None] * cos_thetas[:num_theta... | python|numpy | 3 |
10,148 | 71,213,758 | Percentile Python, problems Setting values | <p>Im calculating percentiles and doing some operations along too many columns.</p>
<pre><code>perc = np.percentile([100,100,100,100,100,100,100,200,300,123,124,90,98,999,567,345],[20,40,60,80])
print(perc)
array([100., 100., 123., 300.])
</code></pre>
<p>I need to get the unique values then, setting my vector i got th... | <p>Since <code>nan</code> values, which are float, are not equal even to themselves, you can use code below:</p>
<pre class="lang-py prettyprint-override"><code>perc_1 = np.percentile([100,100,np.inf,np.inf,np.inf,np.inf,-np.inf,-np.inf,-np.inf],[20,40,60,80])
list(filter(lambda x: x==x, list(set(perc_1))))
</code></pr... | python|python-3.x | 1 |
10,149 | 56,583,979 | How to deserialize splitted json data | <p>I stream data via Server Send Event and get about <code>500.000 datasets</code> but instead of getting one json I get this (example of 2 of the 500.000 datasets)(this is how it looks like opening it in gedit, all question marks are \" and all new lines are \n):</p>
<pre><code>data:{\"data\":[\"Kendrick\",\"Lamar\"... | <p>Juggling with replaces is of course a convoluted path -
the language does have the parsers for this kind of escaping built in -
the simpler of which would be passing the string that contains JSON through an <code>eval</code> call. But eval is seldom needed and should be avoided in most cases as "not elegant" - if ... | python|json|deserialization | 1 |
10,150 | 61,055,393 | python reading json string with headers in initial part | <p>I am trying to grab output from a package (defined in the package documentation as 'jsonDICT') and eventually write it as csv.
I will call this PackResult, and it is a dictionary.</p>
<p>The first, and last, few characters of print(PackResult) looks like this:</p>
<pre><code>{'startDate': '2019-11-01T00:00:00', 'e... | <p>Ah. A new day and some rest gives me the obvious thing I was missing: </p>
<pre><code>df = pand.read_json(json.dumps(PackResult["volume"]),'records','frame')
</code></pre>
<p>This results in </p>
<pre><code># startDate endDate numberOfDocuments
0 2019-11-01T00:00:00 2019-11... | python|pandas | 0 |
10,151 | 63,132,415 | Time Module not working in Pycharm (I am using Python 3.8.5, Pycharm & Pygame) | <p>I am trying to write my first game using Python3 & Pygame in the Pycharm Community IDE. I am trying to make a simple Pong game :-D lol I am a beginner so please help me if you can.</p>
<p>When I run my code, I am getting the following error:</p>
<pre><code>pygame 1.9.6
Hello from the pygame community. https://ww... | <p>The clock is a class, so you should use C instead of c.</p>
<p><code>clock = pygame.time.Clock()</code></p>
<p>and you have another problem, <code>setmode</code> is not an available function. You meant to write <code>set_mode</code></p>
<p>The code that works fine for me:</p>
<pre class="lang-py prettyprint-override... | python|time|module|pygame|pycharm | 0 |
10,152 | 62,960,403 | Batch Normalization while Transfer Learning | <p>I am currently transfer learning using the MobilenetV2 architecture. I have added several Dense layers on the top before my classification. Should I add <code>BatchNormalization</code> between these layers?</p>
<pre><code>base_model = MobileNetV2(weights='imagenet', include_top=False, input_shape=(200,200,3))
x = ba... | <p>Batch Normalization will help with covariance shift and as you are training on new data batch-wise, it would be a good thing for the network. There is nothing as too much BatchNormalization, just put after every layer that is having activations in it.</p> | python|tensorflow|keras|transfer-learning|batch-normalization | 1 |
10,153 | 58,799,879 | VSCode on discover tests Error: spawn python ENOENT | <p>I am running a python project in vscode with <code>virtualenv</code>. Python interpreter is set right. When I'm trying to discover tests it gives me an error saying</p>
<pre><code>python /Users/user/.vscode/extensions/ms-python.python-2019.10.44104/pythonFiles/testing_tools/run_adapter.py discover pytest -- -s proj... | <p>I just ran into the same issue and found that it was due to a non-existing folder in the <code>python.testing.cwd</code> setting where I used <code>workspaceDir</code> instead of <code>workspaceFolder</code> as a variable</p>
<p>Note that it seems to require restarting VSCode before a change here has any effect, i.... | python|visual-studio|visual-studio-code|vscode-python | 6 |
10,154 | 58,836,695 | Concatenate values from two dataframes, based on two sets of indices, in Pandas | <p>I have the following dataframes: </p>
<pre><code>test1 = pd.DataFrame({'id_A' : [1,2,3,4,5,6],
'value_A' : 6*['dog']})
test2 = pd.DataFrame({'id_B' : [1,3,5],
'value_B' : 3*['cat']})
</code></pre>
<p>and I want to obtain a dataframe in which, where <code>id_A</code> = <co... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.isin.html" rel="nofollow noreferrer"><code>Series.isin</code></a> for check membership and then change your <code>map</code> solution with mainly add <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.f... | pandas|dataframe|pandas-groupby | 2 |
10,155 | 59,593,361 | How to manage multiple conditions under route method | <p>I am working on something like Advance filter search in Flask, where i have inputs as:</p>
<h2>index.html: (form)</h2>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code> ... | <p>You can use a dictionary to manage many possible conditions.
Put the search selection arguments into one tuple, such as:</p>
<pre><code>(True, False, True, True)
</code></pre>
<p>Then, you have a dictionary populated with selection tuples as keys and functions to execute as values.</p>
<p>Example:</p>
<pre><code... | python|flask | 1 |
10,156 | 24,941,642 | Python Beautiful Soup scape page containing Java Script | <p>I am trying to scrape from this page:
<a href="http://www.scoresway.com/?sport=basketball&page=match&id=45926" rel="nofollow">http://www.scoresway.com/?sport=basketball&page=match&id=45926</a></p>
<p>but having trouble getting some of the data.</p>
<p>The second table on the page contains the home ... | <p>There is a separate request going for the <code>advanced</code> tab. Simulate it and parse with <code>BeautifulSoup</code>.</p>
<p>For example, here's the code that prints all of the players in the table:</p>
<pre><code>import requests
from bs4 import BeautifulSoup
ADVANCED_URL = "http://www.scoresway.com/b/bloc... | javascript|python|python-2.7|web-scraping|beautifulsoup | 4 |
10,157 | 24,963,444 | Storing python dictionary in json file and substitute values upon reading | <p>I am attempting to create a system that stores information about a sensor(s) in a json file. So far so good. I can store almost all the data in json and pull it out without issue. </p>
<p>Where I am stuck is with the database calls. This is a basic example of the json file for a fish tank sensor, but there are othe... | <p>If <code>data.unpack()</code> returns a <em>sequence</em>, then don't use named parameters at all, just use the sequence:</p>
<pre><code>{
"sensor_info": {
"name" : "fish tank",
"unpack_commands" : "floatle:32, floatle:32"
},
"database_query" : "INSERT INTO fish_tank (pH, temperature, t... | python|json|dictionary | 0 |
10,158 | 67,967,493 | Instead of appending values, pandas appends a column of NaNs. Why? | <p>Why do I get NaN value when adding values in the b column and not for a?
This is the code:</p>
<pre><code>df = pd.DataFrame({'grps': list('aaabbcaabcccbbc'),
'vals': [12,345,3,1,45,14,4,52,54,23,235,21,57,3,87]})
#extract all rows where a is present in the grps column
#for each... | <p>Try the following:</p>
<pre><code>df = pd.DataFrame({'grps': list('aaabbcaabcccbbc'),
'vals': [12,345,3,1,45,14,4,52,54,23,235,21,57,3,87]})
#extract all rows where a is present in the grps column
#for each a in a row, create an entry in a column (index 'a') in newdf from corresponding... | python|pandas|dataframe | 1 |
10,159 | 67,164,748 | converting python code to python spark code | <p>Below code is in Python and i want to convert this code to pyspark, basically
i'm not sure what will be the codefor the statement - pd.read_sql(query,connect_to_hive) to convert into pyspark</p>
<p>Need to extract from data from the EDL, so making the connection to the EDL using PYODBC and them extract the data usin... | <p>The above code can be converted to SparkSQL code as follows:</p>
<pre><code>spark = SparkSession.builder.enableHiveSupport().getOrCreate()
query=f'''
with trans as (
SELECT
a.employee_name,
a.employee_id
FROM EMP
'''
employeeDF = spark.sql(query)
employeeDF.show(truncate=False)
</code... | python|apache-spark|pyspark|apache-spark-sql|pyodbc | 2 |
10,160 | 65,859,394 | How to put validation logic as dependency on SCONS target | <p>I have a simple, yet non obvious requirement to a build process on SCONS.</p>
<p>I need to enter the following command:</p>
<pre><code>scons release [version]
</code></pre>
<h2>Expected results</h2>
<p>What this should do is:</p>
<ol>
<li>Activate a target called release.</li>
<li>Capture the parameter passed soon a... | <p>The SCons way to do this would be to use Variables. That would lead to invoking as:</p>
<pre><code>scons release VERSION=1.2.3
</code></pre>
<p>Variables are covered in SCons docs <a href="https://scons.org/doc/production/HTML/scons-user.html#sect-command-line-variables" rel="nofollow noreferrer">here</a>:</p>
<p>Fo... | python|scons | 0 |
10,161 | 65,636,637 | Keras gradient wrt something else | <p>I am working to implement the method described in the article <a href="https://drive.google.com/file/d/1s-qs-ivo_fJD9BU_tM5RY8Hv-opK4Z-H/view" rel="nofollow noreferrer">https://drive.google.com/file/d/1s-qs-ivo_fJD9BU_tM5RY8Hv-opK4Z-H/view</a> . The final algorithm to use is here (it is on page 6):</p>
<p><a href="h... | <p>First, move <code>dataNoised = xBatchTrain + R</code> inside of <code>with tf.GradientTape(persistent=True) as imTape:</code> to recording the operation related to <code>R</code></p>
<p>Second, instead of using:</p>
<pre><code>for l,r in zip(C,R):
print(imTape.gradient(l,r))
</code></pre>
<p>You should using <co... | python-3.x|keras|tensorflow2.0 | 1 |
10,162 | 51,025,825 | How to specify at least one decision variable should take minimum value in python pulp? | <p>I solved the basic problem with the help of LP in python with PULP. And now I want to add one more conditional constraint to specify at least one decision variable should take minimum value of 2. </p>
<pre><code>prob = LpProblem("Minimizing cost", LpMinimize)
A = LpVariable("A", lowBound=0, cat='Integer')
B = LpVar... | <p>With some extra binary variables α,β,γ we can formulate:</p>
<pre><code>A ≥ 2α
B ≥ 2β
C ≥ 2γ
α+β+γ ≥ 1
α,β,γ ∈ {0,1}
</code></pre>
<p>This models: "at least one of A,B,C should be ≥ 2". These are simple linear inequalities and can be implemented directly in Pulp. </p> | python|linear-programming|pulp | 0 |
10,163 | 50,449,196 | Python-Error installing python package (libmagic) | <p>When I try to install <code>libmagic</code> using <code>pip install python-libmagic</code>, I get the following error:</p>
<blockquote>
<p>Could not install packages due to an EnvironmentError: [Error 13] Permission denied: 'c:\users\*****\anaconda\Lib\site-pakages\_cffi_backend.cp36-win_amd64.pyd'
Consider... | <p>You are trying to install the package to a system folder which you don't have permissions to write to.
You have two options(use only one of them):
<br><br>
1-setup a virtual env to install the package (recommended):</p>
<pre><code>python3 -m venv env
source ./env/bin/activate
python -m pip install python-libmagic[... | python|spyder | 0 |
10,164 | 44,833,904 | Extracting two, rather than four, digit year from datetime object | <p>I am using the following code to create a new time variable in a pandas dataframe from a datetime object:</p>
<pre><code>data['Date'] = pd.to_datetime(data['Date'])
data['Year'] = data['Date'].apply(lambda x: x.year)
data['Month'] = data['Date'].apply(lambda x: x.month)
data['Day'] = data['Date'].apply(lambda x: x.... | <p>Use the date accessor with <code>strftime</code>: <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.strftime.html" rel="nofollow noreferrer"><strong><code>pd.Series.dt.strftime</code></strong></a><br>
Refer to <a href="http://strftime.org/" rel="nofollow noreferrer"><strong>http://strft... | python|pandas|datetime | 3 |
10,165 | 61,303,674 | Why does nonlocal not create new outer variable (unlike global) | <p>I've noticed a difference between the <code>global</code> and <code>nonlocal</code> keywords while reading the Python 3 tutorial <a href="https://docs.python.org/3/tutorial/classes.html" rel="nofollow noreferrer">here</a>.</p>
<p>If I try the following code, it works:</p>
<pre><code># Does not need: spam = ''
def ... | <p>The <a href="https://docs.python.org/3/reference/simple_stmts.html#grammar-token-nonlocal-stmt" rel="nofollow noreferrer">documentation for nonlocal</a> is clear about it:</p>
<blockquote>
<p>Names listed in a nonlocal statement, unlike those listed in a global
statement, must refer to pre-existing bindings in ... | python|python-3.x|scope|global-variables | 2 |
10,166 | 53,935,639 | Create a signal for when a model is created | <p>I have checked django docs on built in signals for this (<a href="https://docs.djangoproject.com/en/2.1/ref/signals).I" rel="nofollow noreferrer">https://docs.djangoproject.com/en/2.1/ref/signals).I</a> have 2 models: Member and Tithe. Every member has a tithe record, I want a tithe record to be created whenever a m... | <p>Put that code in your models file.</p>
<pre><code>from django.db.models.signals import post_save
from django.dispatch import receiver
@receiver(post_save, sender=Member)
def create_tithe(sender, instance=None, created=False**kwargs):
if created:
Tithe.objects.create(member=instanse)
</code></pre> | python|django|django-models|django-signals | 0 |
10,167 | 35,809,473 | Django mutliple same GET parameter names not working | <p>I have this simple Django form for filtering data with <code>GET</code> form:</p>
<pre><code>from reservations.models import Reservation, ServiceType
from django import forms
PAYMENT_OPTIONS = (
('CASH', 'Cash'),
('ROOM', 'Charge to room'),
('ACCOUNT', 'Account'),
('VISA', 'Visa'),
('MASTERCAR... | <p>Your <code>PAYMENT_OPTIONS</code> choice array is OK. </p>
<p>This is how I have it getting the payment options directly from the Model</p>
<pre><code>class MyForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['payments'] = forms.ModelMultiple... | python|html|django | 1 |
10,168 | 46,448,285 | AttributeError at /blog/index/ 'tuple' object has no attribute 'get' | <p>I'm a beginner in python.I get an error and I have been struggling with for hours.</p>
<pre><code>AttributeError at /blog/index/
'tuple' object has no attribute 'get'
Request Method: GET
Request URL: http://localhost:8000/blog/index/
Django Version: 1.10.2
Exception Type: AttributeError
Exception Value:
'tu... | <p>Remove the trailing comma from your <code>return</code>.</p> | python|django | 2 |
10,169 | 53,452,595 | Webscraping with BeautifulSoup multiple pages using click() method | <p>I want to webscrape data from the imdb. In order to do it for multiple pages i have used <code>click()</code> method of the selenum package.</p>
<p>Here is my code:</p>
<pre><code>from bs4 import BeautifulSoup
from selenium import webdriver
import pandas as pd
pages = [str(i) for i in range(10)]
#getting url for... | <p>You could also use a CSS selector target the class of the next button</p>
<pre><code>driver.find_element_by_css_selector('.lister-page-next.next-page').click()
</code></pre>
<p>This class is consistent across pages. You could add a wait for element to be clickable:</p>
<pre><code>WebDriverWait(driver, 10).until(E... | python|selenium-webdriver|web-scraping | 1 |
10,170 | 38,385,616 | Python urllib/lib2 error checking & converting between 2.7 and 3.4 | <p>The following code works fine most of the time unless the internet connection gets bogged down and then it kills the program and doesn't finish off the complete program. How do I go about doing the error checking so I can go up and have it rerun the html link again? Also I'm looking to simplify my entire computer ... | <p>As for your primary question about error handling, which I do not entirely address in this answer, can you be more specific about "go up and have it rerun the html link again?" I'm not exactly sure how you intend to handle the error: do you intend to start the whole process over or pick up a the last successful url ... | python|urllib | 0 |
10,171 | 52,108,342 | Google Cloud PubSub not being called properly in Python | <p>I am squeezing my brain but I am not getting why this issue is happening and I couldnt figure out the cause. I am trying to read an image and pass it to pubsub. Once the messages are sent through pubsub, it is redirected to AutoML model to identify or predict the given image. Below is the code snippet</p>
<pre><cod... | <p>The issue here is that <code>subscriber.subscribe(subscription, callback)</code> is setting up an asynchronous call to <code>callback</code>.</p>
<p>This means that when you publish a new topic, you're essentially setting up a race condition between whether the call to <code>flash(...)</code> will get executed firs... | python|google-app-engine|flask|google-cloud-platform|google-cloud-pubsub | 2 |
10,172 | 51,719,430 | passing a parameter from html page url mapping to the views in django | <p><strong>front.html</strong></p>
<pre><code><div class="row">
<a href="{% url 'emp_pay_list' Information_technology %}">
<div class="col-md-6 col-sm-6 col-lg-3">
<div class="dash-widget clearfix card-box" style="height: 200px;">
<span class="dash-widget-icon"&g... | <p>Your URL pattern must look like</p>
<pre><code>from django.urls import path, re_path
path('list_of_employees/<str:department>/', views.Pay_slip_list , name='emp_pay_list'),
</code></pre>
<p>or use <code>re_path</code></p>
<pre><code>re_path(r'^list_of_employees/(?P<department>[\w\-]+)/$', views.Pay_s... | python|django|url-mapping | 2 |
10,173 | 43,904,908 | Animation of a projection object use pygame | <p>I'm trying to make a animation of projection movement but it does't work.
Just a black window appear.</p>
<pre><code>import math
import time
import pygame
V0 = int(input("please enter initial speed(m/s)"))
angle = int(input("please enter throwing angle"))
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
pygame.init()
sc... | <p>Read the comments. I've changed the way you calculated time and angle.</p>
<pre><code>import math
import time
import pygame
V0 = int(input("please enter initial speed(m/s)"))
angle = int(input("please enter throwing angle"))
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
pygame.init()
screen = pygame.display.set_mode(... | python-3.x|animation|pygame | 1 |
10,174 | 54,677,638 | Skipping import modules in pytest from the command line | <p>The documentation for <code>pytest</code> suggests you can skip certain imports:</p>
<p><a href="https://docs.pytest.org/en/latest/skipping.html#skipping-on-a-missing-import-dependency" rel="nofollow noreferrer">https://docs.pytest.org/en/latest/skipping.html#skipping-on-a-missing-import-dependency</a></p>
<p>We a... | <p>There is no such feature in <code>pytest</code>, so you should do this directly in code (usually in a <code>conftest.py</code>).</p>
<p>A hacky workaround to do the same directly at the command line woud be:</p>
<pre><code>python -c "import pytest; pytest.importorskip('tensorflow'); pytest.main()"
</code></pre>
<... | python|import|pytest | 1 |
10,175 | 52,867,302 | `IndexError: only integers, slices (`:`), ellipsis (`...`),` Error in python snippet in numpy | <p>I'm running the following python snippet on my data(1500x2 matrix), and trying to implement KMeans algorithm from scratch:-</p>
<pre><code>def closestCentroids(arr, centroids):
idx = np.zeros(arr.shape[0]);
for i in range(0, arr.shape[0]):
idx[i] = 0
for j in range(0, centroids.shape[0]):
if(np.lina... | <p>By default, <code>numpy.zeros()</code> creates an array of floating point values, so your array <code>idx</code> is a floating point array. You use the values of <code>idx</code> to index the array <code>centroids</code>, and numpy doesn't allow indexing with floating point values, so <code>idx</code> must be an in... | python|numpy | 1 |
10,176 | 37,589,623 | Can't await work on a computation other than functions in python3.5? | <p>Does it have to be a function we are not blocking ?
Why isn't this working?</p>
<pre><code>async def trivial(L):
await [num**2 for num in L]
</code></pre>
<p>So "Object list can't be used in 'await' expression", Am I correct in assuming it's only looking for a function or is there something that's possible to ... | <p>Per <a href="https://docs.python.org/3/reference/expressions.html#await-expression" rel="nofollow">the documentation</a>, <code>await</code> will:</p>
<blockquote>
<p>Suspend the execution of <code>coroutine</code> on an <code>awaitable</code> object.</p>
</blockquote>
<p>You're in a coroutine, but a list is not... | asynchronous|async-await|python-3.5 | 1 |
10,177 | 34,457,533 | Heroku. Run sql to prepare DB. Posgtresql 9.3. Python | <p>I have prepared app on heroku and nned to prepare db.</p>
<p>I need just to run sql to create db and create user roles, function, tables etc.</p>
<p>But the problem is that I do not have premission for that.</p>
<p>I get the following errors:</p>
<pre><code>DROP SCHEMA
ERROR: database "operations_research" does ... | <p>You can't create dbs or roles on Heroku, and there is no reason to want to do so. You request one via the Postgres add-on and use it in your code.</p> | python|postgresql|heroku|cloud|tornado | 1 |
10,178 | 47,409,984 | How to check if Pepper is currently talking | <p>Is there a way to receive information if currently the robot is talking or not.
I have looked at ALDialog and ALTextToSpeech APIs, but couldn't find anything useful.</p>
<p>I am looking for something like <code>ALDialog.isSpeaking()</code> that returns 'True' if Pepper is currently saying something and 'False' if h... | <p>There's various information posted in ALMemory whom you can subscribe, giving you information about speaking and even more precisely: which word currently spoken...</p>
<pre><code>JVoyage [0] ~ $ qicli call ALMemory.getDataList ALTextToSpeech
["ALTextToSpeech/CurrentSentence","ALTextToSpeech/PositionOfCurrentWord",... | python|nao-robot|pepper | 4 |
10,179 | 64,491,050 | Import csv module file not opening | <p>I am trying to open a csv file using the csv module and then trying to read some data off of it using this code.</p>
<pre><code>import csv
def file_open():
input_file=str(input('enter the input file to use'))
while True:
try:
with open(input_file,'r') as grades:
grades... | <p>The file is closed because your <code>break</code> ends the loop, and the <code>with</code> body, therefore closing the file</p>
<p>You should keep that file reading code within the <code>with</code> indentation.</p>
<p>A <code>csv.reader</code> doesn't load the file into some in-memory list</p> | python|csv | 0 |
10,180 | 64,612,074 | Tabulating data received with json with python | <p>I can parse the following data. but I cannot show it as a table in columnar. How can I chart this?</p>
<pre><code> for item in items:
print(item['symbol'])
</code></pre>
<pre><code>[
{"symbol": "ZILUSDT", "positionAmt": "0", "entryPrice": "0.00000", &q... | <p>You have a list of dictionaries. The easiest way is to wrap them into pandas' DataFrame, which handles that type out-of-the box.</p>
<pre><code>import pandas as pd
tabulated = pd.DataFrame(items)
print(tabulated)
</code></pre> | python|json|python-3.x|python-2.7 | 2 |
10,181 | 55,829,142 | Using pre-installed library or packages with flask in python | <p>I already have all the libraries required for development installed. But when I try to import them in flask virtual environment, it says "Module not found".
When I try to run python in command prompt without a virtual environment, it does import them without any error. So I have reached the conclusion that virtual e... | <p>If you create your virtualenv with the <a href="https://virtualenv.pypa.io/en/latest/reference/#cmdoption-system-site-packages" rel="nofollow noreferrer"><code>--system-site-packages</code></a> flag, you can make use of globally installed packages. By default, you cannot.</p> | python|virtualenv | 2 |
10,182 | 50,033,183 | "func() missing 3 required positional arguments: 'b', 'c', and 'd'" | <p>I am trying to fit a Gaussian with on the following dataset (could not paste it all but hopefully that is enough rows)</p>
<pre><code>2.738237424 0.1956847
2.742886384 0.1956847
2.747535344 0.1956847
2.752184304 0.1956847
2.756833264 0.1776788
2.761482224 0.1956847
2.766131184 0.1956847
2.770780144 0.1776788
2.7754... | <p>The <a href="https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.odr.Model.html" rel="nofollow noreferrer">documentation</a> for <code>odr.Model</code> states that <code>fcn</code> takes only two arguments. </p>
<p>You defined <code>func</code> with 5 required arguments, so Python is throwing an error... | python|numpy|curve-fitting | 1 |
10,183 | 64,985,311 | How can i make guild counter in my bot status. Discord.py | <p>How can I make my bot shows guild counter in status?
I'm new to Discord.py and I want help with the latest version.</p>
<p><code>await bot.change_presence(status=discord.Status.online, activity=discord.Game(f'prefix $ | Serving (...) guilds'))</code></p>
<p>btw I'm not good at English, sorry if my question will not ... | <p>You're probably looking for <code>bot.guilds</code>, here you have an example on how to update the activity whenever the bot joins/leaves a guild</p>
<pre class="lang-py prettyprint-override"><code>@bot.event
async def on_guild_join(guild):
current_guilds = len(bot.guilds)
await bot.change_presence(status=di... | python|discord|discord.py | 1 |
10,184 | 64,951,136 | Solving equations of motion for coupled oscillators | <p>The question asks about a system with two masses each attached to two springs that looks like this:</p>
<p>|s s s s s M1 S S S S M2 s s s s|</p>
<p>The outer springs have a spring constant kb and the inner spring has a constant of ks. I wrote some code to find the normal modes for the system and I get that the frequ... | <p>Recast the 2nd order system as a system of 1st order ODEs (dx/dt = Cx) by adding the velocities of each mass as variables. Look at <a href="https://scipy-cookbook.readthedocs.io/items/CoupledSpringMassSystem.html" rel="nofollow noreferrer">https://scipy-cookbook.readthedocs.io/items/CoupledSpringMassSystem.html</a>.... | python|scipy | 0 |
10,185 | 64,817,813 | Insert into many to many field Django | <p>I'm trying to build Reddit in Django and for that, I am creating a board where users can discuss topics. But I am not able to map user and board.</p>
<p>Model:</p>
<pre><code>class Board(models.Model):
id = models.AutoField(primary_key=True)
unique_id = models.CharField(max_length=100, null=False, unique=Tru... | <p>For your UserBoardMapping, <code>user</code> and <code>board</code> are M2M fields. Because of that, you have to use <code>.set()</code>like in your error message. You can also use <code>.add()</code>if you want to add a value, like in your example.</p>
<pre><code>user_board_mapping = UserBoardMapping.objects.create... | python|django|django-models|django-rest-framework|django-views | 0 |
10,186 | 71,574,485 | ValueError: time data '14.03.2022 00:00:00.000 GMT-0400' does not match format '%d.%m.%Y %H:%M:%S.%f %z' (match) | <p>I want to change the date format of my data but it doesn't seem to work.</p>
<p>here is the error that it give me when I try to run my code "ValueError: time data '14.03.2022 00:00:00.000 GMT-0400' does not match format '%d.%m.%Y %H:%M:%S.%f %z' (match) "</p>
<p>here my code:</p>
<pre><code>import pandas a... | <p>According to <a href="https://strftime.org/" rel="nofollow noreferrer">strtime.org</a> <code>%z</code> is</p>
<blockquote>
<p>UTC offset in the form ±HHMM[SS[.ffffff]] (empty string if the object
is naive).</p>
</blockquote>
<p>So clearly <code>GMT-0400</code> is not valid value for that.</p>
<p>As you are already u... | python|pandas|numpy | 1 |
10,187 | 10,786,189 | Python for loop in avoid similar match | <p>Consider the following list:</p>
<pre><code>items = ['about-conference','conf']
</code></pre>
<p>Iterating over the list using the following for loop prints "about-conference" and "conf"</p>
<pre><code>for word in items:
if 'conf' in word:
print word
</code></pre>
<p>How do I get the if statement to ... | <p>Don't use <code>in</code>, use <code>==</code> to test for exact equality:</p>
<pre><code>if word == "conf":
print word
</code></pre> | python|for-loop|match | 6 |
10,188 | 10,458,093 | How to compare inheritance with several classes? | <p>I want to check if an object is an instance of any class in a list/group of Classes, but I can't find if there is even a pythonic way of doing so without doing</p>
<pre><code>if isinstance(obj, Class1) or isinstance(obj, Class2) ... or isinstance(obj, ClassN):
# proceed with some logic
</code></pre>
<p>I mean,... | <p>You can pass a tuple of classes as 2nd argument to isinstance.</p>
<pre><code>>>> isinstance(u'hello', (basestring, str, unicode))
True
</code></pre>
<p>Looking up the docstring would have also told you that though ;)</p>
<pre><code>>>> help(isinstance)
Help on built-in function isinstance in mo... | python | 31 |
10,189 | 62,544,834 | Apscheduler calling function too quickly | <p>Here is my scheduler.py file:</p>
<pre><code>from apscheduler.schedulers.background import BackgroundScheduler
from django_apscheduler.jobstores import DjangoJobStore, register_events
from django.utils import timezone
from django_apscheduler.models import DjangoJobExecution
import sys
# This is the function you wan... | <p>The primary reason this might be happening is if you are running your development server without the <code>--noreload</code> flag set, which will cause the scheduler to be called twice (sometimes more).</p>
<p>When you run your server in development, try it like:</p>
<pre><code>python manage.py runserver localhost:8... | python|django|apscheduler | 1 |
10,190 | 61,927,596 | Controlling focus of matplotlib image | <p>I am trying to use PCA to annotate the words I modeled Word2Vec in 2d.
The variable <code>result</code> contains the value below :</p>
<pre class="lang-py prettyprint-override"><code>array([[ 0.01632784, 0.01212493],
[ 0.00070532, 0.01451515],
[-0.0055863 , -0.00661636],
[-0.01106532, -0.0157... | <p>What you need is to set a range on the plot's axis:</p>
<pre><code>for i,word in enumerate(words):
plt.annotate(word, xy=(result[i,0], result[i,1]))
plt.ylim(-0.04, 0.05)
plt.xlim(-0.04, 0.05)
plt.show()
</code></pre>
<p><a href="https://i.stack.imgur.com/1lPtQ.png" rel="nofollow noreferrer"><img src="https://... | python|matplotlib|pca | 0 |
10,191 | 60,478,833 | How to pass a value to a search query | <p>I am working with two pages and I would like to click on <code>a tag</code> on one page, which would insert a value to a search query on another page.</p>
<p>So here's my views.py:</p>
<pre><code>def bikes_all(request):
item_list = Bike.objects.all()
category_q = request.GET.get('cat')
if category_q:
... | <p>You are getting GET parameters in your request so you need to pass that GET parameter in your url like this:</p>
<pre><code>https://url?parameter=2
</code></pre>
<p>so set the <code>cat=i</code> in your <code>bikes_all</code> url:</p>
<pre><code>{% url 'core:bikes_all' %}?cat=i
</code></pre> | python|django | 2 |
10,192 | 60,548,117 | Plotting dataframe with different scale values in python | <p>I have the following dataframe</p>
<pre><code>df = pd.DataFrame({
'Date': [1930, 1931, 1932, 1933,1934],
'Income': [2300000, 5698907, 5976753, 6086762, 6577780],
'Age': [22, 45, 35, 40, 28],
'Weight': [0.01, 0.003, 0.04, 0.08, 0.07]
})
</code></pre>
<p>Each variable has different scale values. I want to plot the ... | <p>I believe you need create new <code>DataFrame</code>, because <code>fit_transform</code> return <code>2d numpy array</code>:</p>
<pre><code>import pandas as pd
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
df = pd.DataFrame(scaler.fit_transform(df), columns=df.columns, index=df.index)
... | python|pandas|dataframe|feature-scaling | 2 |
10,193 | 71,180,883 | How can I plot a user activities during 24 hour on a day based on server logs? | <p>I have server logs for each user which is in the following format:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>DateTime</th>
<th>Event</th>
</tr>
</thead>
<tbody>
<tr>
<td>2021-02-10 13:25:44</td>
<td>login</td>
</tr>
<tr>
<td>2021-02-10 13:26:08</td>
<td>Run Script</td>
</tr>
</tbod... | <p>You might want to use <a href="https://seaborn.pydata.org/" rel="nofollow noreferrer"><code>seaborn</code></a>. It can be installed by the following command:</p>
<pre class="lang-sh prettyprint-override"><code>pip install seaborn
</code></pre>
<h2>Code:</h2>
<pre class="lang-py prettyprint-override"><code>import mat... | python-3.x|pandas|matplotlib|pandas-groupby | 1 |
10,194 | 71,409,168 | How to pass 2d numpy array to C++ pybind11? | <p>In C++ pybind11 wrapper:</p>
<pre><code>.def("calcSomething",
[](py::array_t<double> const & arr1,
py::array_t<double> const & arr2)
{
// do calculation
}
)
</code></pre>
<p>In python:</p>
<pre><code>example.calcSomething(
arr1=np.full((10, 2), 20, dtype='float64'),
arr2=np.... | <p>In pybind11 <code>array_t</code> is an n-dimensional array, just like a numpy array.</p>
<p>So there are no restrictions on dimensionality.</p>
<p>The error message is probably coming from somewhere else. Not from pybind11.</p>
<p>At least the code you show should not cause this behavior.</p> | python|c++|arrays|numpy|pybind11 | 0 |
10,195 | 71,191,409 | Using RegEx in Python to extract contents | <p>Good evening,</p>
<p>I am very new to Python and RegEx. I have the following sentence:</p>
<pre><code>-75.76 Card INSURANCEGrabPay ASIA DIRECT to Paid AM 1:16 +100.00 3257 UpAmex Top PM 9:55 +300.00 3257 UpAmex Top PM 9:55 -400.00 Card LTDGrabPay PTE AXS to Paid PM 9:57 (SGD) Amount Details Time here. appear will tr... | <p>Rather than give you the actual regex, I'll gently nudge you in the right direction. It's more satisfying that way.</p>
<p>"Words" here are seperated by spaces. So what you're searching for is a group of characters (captured), a space, characters again, space, characters, space, then capture everything and... | python|regex | 1 |
10,196 | 64,374,829 | convert matplotlib to interactive holoviews + datashader visualization (ideally with interactive brush) | <p>How can I port the following plot to hvplot + datashader?
<a href="https://i.stack.imgur.com/spNm2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/spNm2.png" alt="enter image description here" /></a></p>
<p><strong>Ideally, interactivity can be preserved and certain device_id can interactively be ... | <p>As long as you want up to 100,000 points or so, you don't need Datashader:</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
import hvplot.pandas
from pandas import Timestamp
df = pd.DataFrame(
{'metrik_0': {
Timestamp('2020-01-01 00:00:00'): -0.5161200349325471,
Tim... | python|time-series|seaborn|datashader|hvplot | 1 |
10,197 | 11,334,369 | how can I get python to append var and dont change it? | <pre><code>import twitter
import unicodedata
import string
def get_tweets(user):
resultado=[]
temp=[]
api=twitter.Api()#
statuses=api.GetUserTimeline(user)
for tweet in statuses:
var = unicodedata.normalize('NFKD', tweet.text).encode('utf-8', 'replace')
print var# Horóscopo wh... | <p>I assume you want to put the unicode into a list:</p>
<pre><code> var = unicodedata.normalize('NFKD', tweet.text)
resultado.append( var )
temp.append(var.encode('utf-8', 'ignore'))
</code></pre> | python|python-2.7 | 0 |
10,198 | 11,001,269 | Uniquely identify a file without downloading | <p>So the base project is this... </p>
<p>I am trying to write a server application that will download and hash files off of a website. </p>
<p>The reason for this is so that I can blacklist particular files that are re-uploaded under different names or provide further descriptions as to what a file really is. These ... | <p>Assuming that your problem is that you want to minimize the amount of bandwidth used, you could limit the amount of data downloaded to, say, the first 100kb and build your hash over that part. Other information you could use is anything sent in the header by the server, for example the total filesize and the MIME-fi... | php|javascript|python | 2 |
10,199 | 70,434,415 | Getting pika.exceptions.StreamLostError: Transport indicated EOF while running python script docker image which using pika | <p>I am using Python which is using RabbitMQ for input and output. I am able to run my script locally without any errors but when I try to Dockerize that script and run it it's giving me the following error:</p>
<pre><code>Traceback (most recent call last):
File "./Kusto_connection_with_rabbitmq_2.py", line 1... | <p>Maybe your connection is being interrupted, and pika is declaring your client dead. Try setting the heartbeat in your parameters to 30 or so.</p> | python|python-3.x|docker|rabbitmq|pika | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.