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
3,400
32,839,336
Import Error: No module named requests
<p>I know there are many posts on this, and I've tried using the solutions provided, but to no avail. I tried <code>pip install requests</code> and <code>pip install requests --upgrade</code>:</p> <pre><code>pip install requests --upgrade You are using pip version 7.1.0, however version 7.1.2 is available. You should ...
<p>You installed <code>requests</code> into a different Python installation. The <code>/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages</code> is the site-packages directory for the Mac OS X <code>/usr/bin/python</code> installation.</p> <p>PyCharm is not currently configured to use that P...
python|python-requests
4
3,401
34,447,770
what does this regular expression in python mean (.+?)
<p>I saw this regular expression being used in a program - (.+?) But I don't understand What does this mean. I know that, . is for any character except newline + is for one or more characters ? is for zero or one character</p> <p>But don't understand what this entire regex (.+?) convey.</p>
<p>The parenthesis mean a <a href="https://docs.python.org/2/howto/regex.html#grouping" rel="nofollow"><em>capturing group</em></a>. The <code>.+</code> would match any character <em>1 or more times</em>. The <code>?</code> makes it work in a <a href="https://docs.python.org/2/howto/regex.html#greedy-versus-non-greedy"...
regex|python-2.7
2
3,402
34,871,605
StringIO portability between python2 and python3 when capturing stdout
<p>I have written a python package which I have managed to make fully compatible with both python 2.7 and python 3.4, with one exception that is stumping me so far. The package includes a command line script, and in my unit tests I use this code to run the script's main routine while overriding sys.argv to pass command...
<p>You replaced the Python 2 bytes-only <code>sys.stdout</code> with one that only takes Unicode. You'll have to adjust your strategy on the Python version here, and use a different object:</p> <pre><code>try: # Python 2 from cStringIO import StringIO except ImportError: # Python 3 from io import Strin...
python|python-2.7|stdout|python-3.4|stringio
12
3,403
34,750,845
Error when testing whether a matrix is positive semi-definite (PSD) in python
<p>I am using python 2 and I want to test whether a matrix is positive semi-definite (PSD) or not. I have built a random matrix X and I want to test the SDP property of Q = X<sup>T</sup>X. </p> <p>To do so I have adapted a function that tests positive definite property in order to test positive semi-definite property...
<p>Since the matrix Q you are creating in the script doesn't have full rank if N &lt; p, some of the eigenvals are going to be 0. However as mentioned in the comment , numerical errors in np.eigvals are causing these to become negative: </p> <pre><code>P = 5 N = 3 np.random.seed(18) X = bernoulli.rvs(0.5, size=N*P).r...
python|matrix
4
3,404
7,701,303
Error message which running Python tools in Visual Studio
<p>I am new to python and just started learning it today.</p> <p>I have installed Python Tools for Visual Studio 2010 and using VS as my Editor.</p> <p>My test python programs run correctly but the at the last line in the output window I see the following</p> <pre><code>The thread 'Python Thread' (0x6f4) has exited ...
<p>That means the script executed successfully. If the code was anything other than zero, that would indicate an error.</p> <p>Yes, that command window is likely the "Python Thread".</p>
python|visual-studio-2010|ptvs
5
3,405
1,139,835
Python fails to execute firefox webbrowser from a root executed script with privileges drop
<p>I can't run firefox from a sudoed python script that drops privileges to normal user. If i write</p> <pre> $ sudo python >>> import os >>> import pwd, grp >>> uid = pwd.getpwnam('norby')[2] >>> gid = grp.getgrnam('norby')[2] >>> os.setegid(gid) >>> os.seteuid(uid) >>> import webbrowser >>> webbrowser.get('firefox')...
<p>This could be your environment. Changing the permissions will still leave environment variables like $HOME pointing at the root user's directory, which will be inaccessible. It may be worth trying altering these variables by changing <code>os.environ</code> before launching the browser. There may also be other va...
python|browser|debian|uid
1
3,406
1,099,178
Matching Nested Structures With Regular Expressions in Python
<p>I seem to remember that Regular Expressions in DotNet have a special mechanism that allows for the correct matching of nested structures, like the grouping in "<code>( (a ( ( c ) b ) ) ( d ) e )</code>". </p> <p>What is the python equivalent of this feature? Can this be achieved using regular expressions with some ...
<p>Regular expressions <em>cannot</em> parse nested structures. Nested structures are not regular, by definition. They cannot be constructed by a regular grammar, and they cannot be parsed by a finite state automaton (a regular expression can be seen as a shorthand notation for an FSA).</p> <p>Today's "regex" engine...
python|regex|recursive-regex
22
3,407
47,129,301
Import Error with scikit-surprise
<p>When I ran the example code using scikit-surprise which is a package in python, it showed that "cannot import name similarities". </p> <p>My operating system is windows 10 and python version is 2.7. When I tried to ran the exactly the same code on the school computer, it succeeded. The operating system in school co...
<p>You see import error as those packages are not installed in your home computer. So if those are public packages then you can download it via pip or easy_install.</p>
python|scikit-learn
0
3,408
47,531,615
Pandas dataframe merge unsuccessful
<p>I have two pandas Dataframe with following columns: </p> <p><code>dataframe</code> 1 : </p> <pre><code>A, B, C </code></pre> <p><code>dataframe</code> 2 : </p> <pre><code>A, B, C, Count </code></pre> <p>here is the script:</p> <pre><code>dfcount = pd.read_csv ( "df1.csv") df = pd.read_csv ( "df2.csv") df = df...
<p>Strip the spaces in the dataframe using <code>.str.strip</code></p> <pre><code>dfcount[['A', 'B',' C']] = dfcount[['A', 'B',' C']].apply(lambda x : x.str.strip()) df[['A', 'B',' C']] = df[['A', 'B',' C']].apply(lambda x : x.str.strip()) </code></pre> <p>Then you are good to merge the dataframes. </p> <pre><code>...
python|pandas|merge
1
3,409
11,837,748
Python script encoding trouble when run in CRON job
<p>As many hopefully can relate, this encoding problem is driving me <em>mental</em>. I would really appreciate some light on this! </p> <p>End goal is to be able to run the same script.py from both terminal and cron, and from cron with <code>&gt; stdout.txt</code>. And needless to say, I'm having serious encoding tro...
<p>If you have control over the <code>statusObj</code> you should check the relevant code where data is being parsed into the object and try to get the input as <em>clean</em> as possible. </p> <p>You want to make sure your string is decoded to unicode before you try to encode it.</p> <p>If not you can try:</p> <pr...
python|utf-8|cron
1
3,410
46,905,586
how to summarize min and max of two separate columns in one column
<p>I have a data of bond market like this:</p> <pre><code>Id row Date BuyPrice SellPrice 1 1 2017-10-30 94520 0 1 2 2017-10-30 94538 0 1 3 2017-10-30 94609 0 1 4 2017-10-30 94615 0 1 5 2017-10-30 94617 0 1 1 20...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>groupby</code></a> and aggregate <code>min</code> and max first and then <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow noreferrer">...
python|pandas|data-science
0
3,411
67,865,384
Delete object from dictionary
<p>I have the following dictionary and I was wondering if there was a way to delete objects based off a key value when they are within a list. For instance,</p> <pre><code> {'Root': [{'ID': '1', 'version': '3'},{'ID': '2', 'version': '4'},{'ID': '3', 'version': '3'}]} </code></pre> <p>Is there a way to delete everythin...
<p>Try this:</p> <pre><code>new_dict['root'] = [element for element in old_dict['root'] if element['version'] !='3' ] </code></pre>
python
1
3,412
30,221,573
Python's setup.py installed CLI script doesn't allow importing same module
<p>I want to create a python app named knife that can be executed from CLI, the problem is that it can't import the modules. I followed the same folder structure as the Django project for reference.</p> <p>My directory structure is like this:</p> <pre><code>knife/ knife/ bin/ knife-cli.py ...
<p>Got it, The script was executing the old <code>/usr/bin/knife.pyc</code> file, I just deleted it and now works well.</p>
python|module|setuptools
5
3,413
30,149,538
I keep getting an AttributeError: 'str' object has no attribute '__get_author'. Could someone please help me with what I can do to fix it?
<p>I am creating a tweet manager and i'm coming upon a attribute error that i honestly don't know how to fix. I am a novice at Python so I'm still learning. Why am I getting AttributeError: 'str' object has no attribute '__get_author'. Here is my code:</p> <pre><code># The running flag and the tweets list are initiali...
<p>You probably wanted to call <code>tweets[i]</code> instead of <code>tweet[i]</code> within 'Handle "View Recent Tweets" input'</p>
python
0
3,414
65,854,707
Insert line or update line if it matches a condition. With repeated terms, not unique
<p>Note: It is not possible to use ON CONFLICT, the fields are not unique: serie_name and season are repeated several times.</p> <p>I need to update the number of episodes of a season in a series. I have a table with 3000 rows, which I need to check one by one, if the record does not exist, I will insert a new row, if ...
<p>You can define a composite <code>UNIQUE</code> constraint for the columns <code>serie_name</code> and <code>season</code>:</p> <pre><code>CREATE TABLE IF NOT EXISTS series_test ( id_key INTEGER NOT NULL, serie_name VARCHAR(100) NOT NULL, season INTEGER, episode_dub INTEGER, episode_leg INTEGER, ...
python|sql|sqlite|insert|case
0
3,415
43,073,027
Issue with Books on MediaWiki
<p>I am trying to get a MediaWiki to export to PDF format using the Books/Collection, but it has issues rendering.</p> <p>I found this useful <a href="http://www.speedron.com/blog/software/configuration-of-mediawiki-pdf-writer-extansion-with-mwlib-plugin-on-debianubuntumint/" rel="nofollow noreferrer">article</a> whic...
<p>If anyone's having issues with the "coros" module not being found by mwlib, downgrading the gevent library helps. The coros module has been deprecated and later removed in newer versions.</p> <p>I'm not sure which is the latest gevent version that has the coros module, but the following resolved the issue for me:</...
php|python|pdf|collections|mediawiki
2
3,416
43,248,122
LSTM model error is percent of one output class
<p>I'm having a rough time trying to figure out what's wrong with my LSTM model. I have 11 inputs, and 2 output classes (one-hot encoded) and very quickly, like within 1 batch or so, the error just goes to the % of one of the output classes and stays there.</p> <p>I tried printing weights and biases, but they seem to ...
<p>Since you have one hot encoding use <em><strong>sparse_softmax_cross_entropy_with_logits</strong></em> instead of <em>tf.nn.softmax_cross_entropy_with_logits</em>.</p> <p>Refer to this stackoverflow answer to understand the difference of two functions.<br /> <a href="https://stackoverflow.com/questions/37312421/tens...
tensorflow|neural-network|lstm
2
3,417
43,385,343
Python: How do you write a function that counts the occurrences of a specified non-overlapping string s2 in another string s1?
<p>For example, count("system error, syntax error", "error") returns 2. I'm not sure how to write this code. Any help is greatly appreciated. I tried starting the code, but I got lost after this.</p> <pre><code>def main(): s1 = input("Please enter string 1: ") s2 = input("Please enter string 2: ") print...
<p>I don't know if it's me but I think the problem is poorly written, you can find it @ <a href="https://imgur.com/a/UAas2ac" rel="nofollow noreferrer">Intro to Programing python by Daniel Liang</a></p> <p>here's my solution using Counter:</p> <pre><code>from collections import Counter def main(): s1 = input("En...
python
0
3,418
37,106,776
Searching for an equal string?
<p>I am not sure how to word the question title.</p> <pre class="lang-python prettyprint-override"><code>a = "Alpha"; b = "Bravo"; c = "Charlie"; fn = input("What is your first name: ") for fletter in fn.split(): fl = fletter[0] </code></pre> <p>The code above gets the first letter entered. The goal is to the...
<h1>Solution 1 [Using a dictionary]</h1> <p>Also makes things much simpler.</p> <p>In this case, instead of defining separate variables for each string, you store them in a dictionary. So for example, instead of this:</p> <pre><code>a = "Alpha" b = "Bravo" c = "Charlie" </code></pre> <p>You would have this:</p> <p...
python|python-3.x
1
3,419
20,056,936
How to turn a python program to a .exe
<p>I have been working a lot on python recently, mostly using IDE. Now I have a need to make a .exe program out of my code. Have tried cx_freeze but i couldn't understand what to do. So, if anyone could either give me a link to a good guide for begginers, or another easier .py to .exe program, I would be grateful. PS I...
<p>Try py2exe..</p> <p>Install py2exe in your system, then generate a setup file as shown <a href="http://www.py2exe.org/index.cgi/Tutorial" rel="nofollow"> here </a> </p> <p>Thats it. Your .exe file will be created.</p>
python|python-3.x
2
3,420
20,195,435
How to write a fast log-sum-exp in Cython and Weave?
<p>I am looking at options to accelerate the log-sum-exp (using the "max trick") operation from Python code. I am on Windows 8 using Python 2.7. I have put together a comparison of implementations using Numpy, Scipy's implementation, Numba, Cython, Weave and numexpr, which can be viewed <a href="http://nbviewer.ipytho...
<p>An explicitly vectorized (SSE) c version is about 2.5x faster than any of the alternatives that you posted on my machine (~360 us vs 150 us), for float32 data. I don't have numba so I couldn't try that.</p> <p><a href="http://nbviewer.ipython.org/github/rmcgibbo/logsumexp/blob/master/Accelerating%20log-sum-exp.ipyn...
python|numpy|cython
5
3,421
66,844,763
Numpy log on division with 0 in numerator gives "divide by zero" warning
<p>I have 120,000 X 120,000 numpy array called NUMERATOR of the format:</p> <pre><code>STEP1: NUMERATOR = [[8.85191777e-12 0.00000000e+00 6.62258993e-12 ... 0.00000000e+00 0.00000000e+00 0.00000000e+00] : [0.00000000e+00 1.22870643e-11 0.00000000e+00 ... 0.00000000e+00 0.00000000e+00 0.00000000e+00]] </code></pre> <...
<p>The &quot;divide by zero&quot; warning is slightly confusing, as you are (most likely) not dividing by zero in <code>NUMERATOR/NEW_DENOMINATOR</code>. Instead, you are trying to calculate the <code>log2</code> of zero values. Internally, <code>numpy</code> most likely performs a division by the input of <code>log2</...
python|python-3.x|numpy
3
3,422
4,106,500
In Google App Engine, how do you select entities where an attribute does not exist?
<p>Using the python version of GAE and extending models from db.Model, how do you fetch entities where an attribute equals None or does not exist? </p> <pre><code>#This works #Fetch 10 entities where duration == 0.0 entities = MyModel.all().filter('duration = ', 0.0).fetch(10) #This doesn't. How can I do the equival...
<p>You have entities without <code>duration</code> property (can't be filtered because index can't refer to them) and entities with <code>duration</code> set to None (can be filtered).</p> <p>Since you have changed <code>MyModel</code> schema, you should fix the entities stored without <code>duration</code> property w...
python|google-app-engine
3
3,423
48,162,645
How to get character wise confidence in tesseract using command line?
<p>I am able to get word level confidence score using tesseract 4.0 through the command line. Interested to know if there is a way to get the character confidence too.</p> <p>For word level confidence used the below command:</p> <pre><code>tesseract [Image name] outputbase --oem 1 -l eng --psm 8 tsv </code></pre>
<p>Set <code>hocr_char_boxes to 1</code> in your config file. Or, at the command line, your updated command would be:</p> <pre><code>tesseract [Image name] outputbase --oem 1 -l eng --psm 8 -c hocr_char_boxes=1 hocr </code></pre> <p>Note the hocr output option and look in that file for ...<code>_wconf</code>, e.g.</p...
tesseract|python-tesseract
5
3,424
51,126,376
multiple conditions in if statement using 'and'
<p>Problem statement : IP addresses of the following forms are considered special local addresses: 10. * . * . * and 192.168. * . * . The stars can stand for any values from 0 to 255. Write a program that asks the user to enter an IP address and prints out whether it is in one of these two forms</p> <p>My code :</p> ...
<p>Subscripting a string will return a string not an <code>int</code>, like you're comparing them to. You should use string literals in your conditions:</p> <pre><code>s=input('Enter the IP address :') if s[0]=='1' and s[1]=='0' and s[2]=='.': print('It is a special IP address') elif s[0]=='1' and s[1]=='9' and s[...
python|if-statement
1
3,425
51,519,696
Idiomatic way to call method on all objects in a list of objects Python 3
<p>I have a list of objects and they have a method called process. In Python 2 one could do this</p> <pre><code>map(lambda x: x.process, my_object_list) </code></pre> <p>In Python 3 this will not work because map doesn't call the function until the iterable is traversed. One could do this:</p> <pre><code>list(map(la...
<p>Don't use <code>map</code> or a list comprehension where simple <code>for</code> loop will do:</p> <pre><code>for x in list_of_objs: x.process() </code></pre> <p>It's not significantly longer than any function you might use to abstract it, but it is significantly clearer.</p> <p>Of course, if <code>process</c...
python|python-3.x|list|methods
9
3,426
17,504,397
Eclipse - Console didn't show the Python code fragment output
<p>I wrote a simple code fragment using Eclipse version 3.7. After I run the file as a Python project. The console didn't show the simple output. </p> <ul> <li>I installed Python plug-in version 2.7.5 onto Eclipse </li> <li>I downloaded the Python 3.3.2 package onto my laptop computer, configured it and add PATH var...
<p>You need to save your file with the <code>.py</code> extension (i.e. <code>exercise1<b>.py</b></code>), denoting it as a Python source file.</p>
python|eclipse|pydev
1
3,427
17,600,833
Complex Python JSON object to custom dictionary conversion
<p>I do have following JSON object -</p> <pre><code>{ "Resource": [ { "@name": "Bravo", "@signature": "h#Bravo", "@type": "ESX_5.x", "@typeDisplayName": "ESX Server", "PerfList": { "@attrId": "cpuUsage", "@attrName"...
<p>Sometimes when operating on nested structures using recursive functions, its easier to think in terms of a walking function and an operation function. So we want to target all the dicts contained in the json structure and perform a transformation operation on them.</p> <p>Transforming a structure in-place, instead ...
python|json
1
3,428
70,397,729
How to convert a matplotlib spectrogram image into a torch tensor
<pre><code>import numpy as np from numpy import asarray from matplotlib import pyplot as plt import torch # generate a signal fs = 50 # sampling freq ts = np.arange(0, 10, 1/fs) # times at which signal is sampled s1 = np.sin(2 * np.pi * 2 * ts) # 2 hz s2 = np.sin(2 * np.pi * 3 * ts) # 3 hz s3 = np.sin(2 * np.pi * 6 * ...
<p><code>plt.specgram</code> returns the spectrogram in the <code>spectrum</code> variable. This means that you need to pass that variable to the <code>torch.from_numpy</code> function. Additionally, according to <a href="https://stackoverflow.com/questions/15961979/how-do-i-plot-a-spectrogram-the-same-way-that-pylabs-...
python|numpy|matplotlib|pytorch|spectrogram
1
3,429
70,691,100
Counting the number of syllables in a words with the exception that in words that end with "es","ed" are not counted as a syllable
<p>I want to count the number of syllables in a word, by counting the number of vowels in that word, and not counting the last &quot;e&quot; in the words that end with &quot;ed&quot; and &quot;es&quot;.</p> <p>I ran the following code, but I'm not able to handle that exception:</p> <pre><code>import re vowelRegex = re....
<p>You can use</p> <pre class="lang-none prettyprint-override"><code>(?i)(?!e[ds]\b)[aeiou] (?![eE][DdsS]\b)[aeiouAEIOU] </code></pre> <p>See the <a href="https://regex101.com/r/To9J4w/2" rel="nofollow noreferrer">regex demo</a>. <em>Details</em>:</p> <ul> <li><code>(?i)</code> - enable case insensitive matching</li> <...
python|regex
1
3,430
66,686,455
validictory is not able to validate properly
<p>I'm trying to validate the headers of a flask request and its failing. I'm trying to use the below code to simulate the same and can see that its failing to validate the headers properly even if I miss some of the mandatory headers.</p> <p><strong>The below code is expected to fail but its passing.</strong></p> <pre...
<p>I was able to find out the reason for this issue by going through the source code of <a href="https://github.com/jamesturk/validictory/tree/master/" rel="nofollow noreferrer">validictory</a>.</p> <p>It was passing the type validation since EnvironHeaders has both the attributes 'keys' and 'values'.</p> <pre><code> ...
python|python-3.x|validation|flask|werkzeug
0
3,431
66,375,687
Connect a slot to signals from all objects derived from a class
<p>I'm just starting out with PyQt5 and would appreciate some help. I have a widget W that responds to information from all object derived from some class C. Widget W can only ever be updated by objects of class C and, during an update, it must know, which particular object triggered it.</p> <p>The problem is that obje...
<p>One possible solution is to use metaclasses:</p> <pre class="lang-py prettyprint-override"><code>import sys from PyQt5 import QtCore, QtWidgets class MetaC(type(QtCore.QObject), type): def __call__(cls, *args, **kw): obj = super().__call__(*args, **kw) for receiver in cls.receivers: ...
python|pyqt|pyqt5
2
3,432
64,666,874
Problem to load .csv files into Apache Cassandra with Python
<p>I'm trying to load a .csv file with Python into Apache Cassandra database. The command &quot;COPY&quot; integrated with session.execute seems don't work. It gives an unexpected indent in correspondance of =',' but...I red something about and I found that the command COPY in this way is not supported.</p> <p>In this ...
<p>Main problem here is that <code>COPY</code> is not a CQL command, but a <code>cqlsh</code> command, so it couldn't be executed via <code>session.execute</code>.</p> <p>I recommend to use <a href="https://docs.datastax.com/en/dsbulk/doc/index.html" rel="nofollow noreferrer">DSBulk</a> to load data into Cassandra - it...
python|ubuntu|cassandra|cql
1
3,433
63,848,554
Python : Pivot up values in data frame using lamda
<p>I am reading a text file and using pandas and storing the details in Data Frame. Below is the Input file on which data frame is created :</p> <pre><code>SourceID|OrganizationName|AddressLine1|AddressLine2|City 1|Manor Drug Medical And Pharma|5795 N 1st St||Uta 1|Manor Drug Medical And Pharma|23230 Red River|Dr S...
<p>Use -</p> <pre><code>df.groupby(['SourceID', 'OrganizationName'], as_index = False).agg('^'.join) </code></pre> <p><strong>OR</strong></p> <pre><code>df.groupby(['SourceID', 'OrganizationName'], as_index = False).agg({'AddressLine1': '^'.join, 'AddressLine2': '^'.join, 'City': '^'.join}) </code></pre> <p><strong>Out...
python|pandas
0
3,434
53,036,491
Importing agents and their attributes from CSV in mesa
<p>My data is in .csv format and each row of data represents each agent while each column represents a certain attribute. </p> <p>My question is how to assign agents and their attributes from a csv file in Mesa? </p> <p>Could anyone help me with how to import them in Mesa please?</p> <p>Thanks.</p>
<p>To import a .csv and turn them into attributes you want to know how you are reading in the file and then pass that into the agent class as you are creating it.</p> <p>For example: </p> <p>you have 'people.csv':</p> <pre><code> agent, height, weight bill, 72 in, 190lbs anne, 70 in, 170lbs...
python-3.7|agent-based-modeling|mesa-abm
1
3,435
61,939,305
How do I arrange the items into a list and assign?
<p>In the comments, I have written some pseudocode to remind myself of what to do. So far, I know how to split and find the length of the string. But after that, I don't know how to arrange the items into a list and assign that list to a variable.</p> <p>Below is an example of what I think it is:</p> <pre><code>origi...
<p>I believe that you want to split the string, store it in a list and find it's length. You just use below code.</p> <pre><code>str_list = original_str.split() num_words_list = len(str_list) </code></pre>
python|split|variable-assignment|string-length
0
3,436
18,079,620
Changing values dynamically in python from a file
<p>I have a class that works with various values, and another that reads values from an external file. I need the other one to replace the values of the values class with the values taken from the file. Is there a way to do this?</p> <p>I guess I could submit my code here, but I don't think it'll be of much help becau...
<p>Instead of having lots of attributes, I'd use one dict:</p> <pre><code>self.data = dict(baetur = 0, ororkustyrkur = 1, ororkustyrkur_62 = 2, ororkulifeyrir = 3, ellilifeyrir = 4) </code></pre> <p>Then, after loading the new data from the file:</p>...
python|variables|dynamic
2
3,437
65,915,724
Launching Blender console in Docker container with Django
<p>I'm making a web application where the user can render an image with blender. I'm using django as the framework and have it running in a docker environment.</p> <p>You can render a image with blender console commands like this:</p> <pre><code>blender -b animation.blend -o //render_ -F PNG -x 1 -a </code></pre> <p>My...
<p>There's a similar question on Blender stackexchange: <a href="https://blender.stackexchange.com/a/1366">https://blender.stackexchange.com/a/1366</a></p> <p>I would recommend you using blender as a Python module and not running a separate process since it's harder to control the load on the system and handle errors. ...
python|django|docker|microservices|blender
0
3,438
69,263,354
ip: Host name lookup failure
<p>Here my code. I'm getting Host name lookup failure.</p> <pre><code>import random import time import os sec = int(input(&quot; input time to change Ip in Sec: &quot;)) limit = int(input('how many time do you want to change your ip: ')) ip = &quot;.&quot;.join(map(str, (random.randint(0, 255) for _ in range(4)))) # ...
<p>You're asking <code>ifconfig</code> to set the interface address to the hostname &quot;ip&quot; (which is probably not resolvable) which does not appear to be what you want to be doing.</p> <p>You need to pass the value of the variable <code>ip</code> so either:</p> <pre><code>os.system('sudo ifconfig wlo1 ' + ip) <...
python|linux|system|ip-address
0
3,439
69,076,602
Changing digits in numbers based on a conditions
<p>In Norway we have something called D- and S-numbers. These are National identification number where the day or month of birth are modified.</p> <pre><code>D-number [d+4]dmmyy S-number dd[m+5]myy </code></pre> <p>I have a column with dates, some of them normal (ddmmyy) and some of them are formatted as D- or S-numbe...
<p>Normalize dates by padding with 0 then explode into 3 columns of two digits (day, month, year). Apply your rules and combine columns to a <code>DateTimeIndex</code>:</p> <pre><code># Suggested by @HenryEcker # Changed: .pad(6, fillchar='0') to .zfill(6) dates = df['dates'].astype(str).str.zfill(6).str.findall('(\d...
pandas|string|series
2
3,440
72,825,021
Flask flash - use bootstrap toast
<p>I am using Boostrap-Flask (not Flask-Bootstrap) with Bootstrap 5.</p> <p>When I save a form I can use Flash to display an alert using the Bootstrap-Flask macro render_messages</p> <p>This works fine. However, I'd like to use a Toast rather than an Alert.</p> <p>I tried doing this via Javascript rather than using fla...
<p>I got this working by putting the following code into an HTML file and importing this into my base.html</p> <pre><code>&lt;!-- Begin alerts --&gt; {% with messages = get_flashed_messages(with_categories=true) %} {% if messages %} {% for category, message in messages %} &lt;script&gt; option = {&quot;autohide&qu...
python|flask|bootstrap-5
0
3,441
59,317,920
How to generate list of column names from Dataframe if row value =1
<p>I have a Pandas Data frame in the following format</p> <pre><code> CLASS 1 CLASS 2 CLASS 3 CLASS 4 CLASS 5 CLASS 6 CLASS 7 CLASS 8 CLASS 9 CLASS 10 CLASS 11 CLASS 12 CLASS 13 CLASS 14 CLASS 15 CLASS 16 CLASS 17 CLASS E CLASS V 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0...
<p>If there is MultIndex with one level only use:</p> <pre><code>print (df.columns) MultiIndex([( 'CLASS 1',), ( 'CLASS 2',), ( 'CLASS 3',), ( 'CLASS 4',), ( 'CLASS 5',), ( 'CLASS 6',), ( 'CLASS 7',), ( 'CLASS 8',), ( 'CLAS...
python|pandas
3
3,442
58,771,381
How to insert a column from dataframe A into dataframe B which has a different lenght?
<p>I have 2 dataframes:</p> <p>a) df_Q, has the name of a district and its longitude and latitude. The names of the districts repeat accoding to the number of coordinates.</p> <p>b) df_S, has the name (featureId) of a district and a count of its events. Here, the names of the districts repeat only once. </p> <p>I ne...
<p>You can use the "merge" function like this :</p> <pre><code>new_df_Q = df_Q.merge(df_S, how = 'left', left_on = 'name', right_on = 'featureId') </code></pre>
python-3.x|pandas
0
3,443
24,990,497
Filling dialog parameters from Django/Python app
<p>I'm creating a dashboard using Django that intends to simplify operation for several other (web) applications created by third parties, by redirecting the user to specific links on that applications without having to enter the information (customerId, user &amp; passwd, etc) multiple times. </p> <p>Flow is the foll...
<p>I was finally able to achieve this with a bit of Javascript. I created a function "open_dt" which creates a new window, waits for it to load and then fill the parameters and click "OK".</p> <p>Code looks like this:</p> <pre><code>function open_dt(param1, param1) { new_win = window.open("http://&lt;my_url&gt;/m...
javascript|jquery|python|django
0
3,444
42,772,714
How can I run this command using wand-py and imagemagick
<p>I'm attempting to recreate the following command using wand-py and imagemagick:</p> <pre><code>convert -density 500 hello_world.pdf -quality 100 -monochrome -enhance – morphology close diamond hello_world.jpg </code></pre>
<p>You'll need to bind methods from MagickCore, and MagickWand libraries. Keep in mind that Kernel performance can differ widely between systems, so don't be surprised if you hit a `Operation canceled' message when working with large density images.</p> <pre class="lang-py prettyprint-override"><code>import ctypes fro...
python|imagemagick-convert|wand
2
3,445
72,403,905
Sorting np arrays according to another list
<p>I am working on a project with convolutional neural networks. I already trained my model (binary) and got nice results. Then I inserted my data and used the model to predict outcomes. My output is in the form of np array of an image + the value of prediction as shown on the image in the link below. Now, I am trying ...
<p>I suspect that all you need, is to sort <code>ynew</code>, but more specifically to get the indices of sorted elements using <code>np.argsort</code>. E.g. for</p> <pre><code>ynew = np.array([0.6, 0.9, 0.7]) </code></pre> <p>The sorted indices you'll get with <code>np.argsort(ynew)</code> would be <code>[0, 2, 1]</co...
python|neural-network
0
3,446
50,690,699
Replacing values in a Pandas DataFrames with similar indexes
<p>I have two dataframes with similar but not equal indexes:</p> <pre><code>df1 = pd.DataFrame(np.random.rand(10,4),columns=list('ABCD'), index = list ('IJKLMNOPQR')) df2 = pd.DataFrame({'1': [1,2,3,4,5,6,7], '2':[3,4,5,6,7,8,9]}, index =list('IQLMRFW') ) </code></pre> <p>What I would like to do is replace t...
<p>Change the columns of df2 , and using <code>update</code> </p> <pre><code>df2.columns=['A','B'] df1.update(df2) df1 Out[448]: A B C D I 1.000000 3.000000 0.792863 0.501980 J 0.545532 0.142258 0.814975 0.207339 K 0.335758 0.114109 0.864096 0.435545 L 3.000000 5.000000...
python|pandas|dataframe
1
3,447
35,332,978
Pygame, set transparency on an image imported using convert_alpha()
<p>in my pygame game, to import jpeg image, I use <code>convert()</code> <a href="http://www.pygame.org/docs/ref/surface.html#pygame.Surface.convert" rel="nofollow">http://www.pygame.org/docs/ref/surface.html#pygame.Surface.convert</a></p> <p>then, to play with the image transparency (how much we can see trough the im...
<p>When you read the documentation for <strong>set_alpha</strong> you can read this : <em>If the Surface format contains per pixel alphas, then this alpha value will be ignored.</em></p> <p>%In your case, with a png image, it's a per pixel alphas. So, you must manage alpha "per pixel". For example, you can do that (no...
python|image|pygame|png|transparency
6
3,448
69,305,596
Having issue with downloading files with same name from outlook using Python. Only one file is showing on folder
<pre><code>from datetime import date import os import email import win32com.client import pathlib import glob import re from pathlib import Path path = os.path.expanduser(file_location + &quot;/&quot; +date_file) outlook = win32com.client.Dispatch(&quot;Outlook.Application&quot;).GetNamespace(&quot;MAPI&quot;) inbo...
<p>This is very much expected behavior. <a href="https://www.meme-arsenal.com/memes/d0e24b03f9b65910584d944e7de63694.jpg" rel="nofollow noreferrer">There can be only one</a> file with a specific name in a specific folder. You will need to implement some logic to see if the file already exists, and rename it.</p> <p>See...
python|file|outlook|download
1
3,449
55,573,204
SQLAlchemy ignoring None when comparing date
<p>I would like to get rows from specified date range, but when limiter is None (beg_date==None, fin_date==None) I want to ignore scope on one side. </p> <p>For instance: If beg_date=='2019-10-23' and fin_date==None I would like to get rows from 2019-10-23 up to date. How can I achieve that using SQLAlchemy?</p> <p>M...
<p>You could build your date condition with Python conditions on <code>start_date</code> and <code>end_date</code> before building your whole query:</p> <pre><code>if start_date and end_date: date_condition = MyModel.date.between(start_date, end_date) elif start_date: date_condition = MyModel.date &gt; start_d...
python|python-3.x|postgresql|sqlalchemy
1
3,450
57,312,280
i wan to split a list into small lists inside the same list
<p>i have a list i want to to make every 5 elements become in a list in the same list</p> <pre><code>input = ['Operating System: free dos', 'Hard Disk Capacity: 500 gb', 'Processor Family: amd e series', 'Screen Size: 15 - 15.9 inch', 'Memory Size: 4 gb', 'Operating System: linux', 'Hard Disk Capacity: 1 tb', 'Proces...
<p>For example you can use <code>itertools.groupby</code>:</p> <pre><code>lst = ['Operating System: free dos', 'Hard Disk Capacity: 500 gb', 'Processor Family: amd e series', 'Screen Size: 15 - 15.9 inch', 'Memory Size: 4 gb', 'Operating System: linux', 'Hard Disk Capacity: 1 tb', 'Processor Family: intel 8th generati...
python-3.x
0
3,451
54,177,687
Loading data from S3 to dask dataframe
<p>I can load the data only if I change the "anon" parameter to True after making the file public.</p> <pre><code>df = dd.read_csv('s3://mybucket/some-big.csv', storage_options = {'anon':False}) </code></pre> <p>This is not recommended for obvious reasons. How do I load the data from S3 securely?</p>
<p>The backend which loads the data from s3 is s3fs, and it has a section on credentials <a href="https://s3fs.readthedocs.io/en/latest/#credentials" rel="noreferrer">here</a>, which mostly points you to boto3's documentation.</p> <p>The short answer is, there are a number of ways of providing S3 credentials, some of ...
python|dask|dask-distributed
8
3,452
45,582,645
How to get hours value greater than 24 hours in python 2.7?
<pre><code>time1 = timedelta(days=2, hours=6.20) time2 = timedelta(hours=20.10) sum_time = time1 + time2 print str(sum_time) print sum_time.total_seconds() / 3600 </code></pre> <p>Output:</p> <pre><code>3 days, 2:18:00 74.3 </code></pre> <p>How to get output <strong>74:18:00</strong> ?</p>
<p>With <code>total_Seconds / 3600</code> you only get the hours in decimal format.</p> <p>You can use <a href="https://docs.python.org/2/library/functions.html#divmod" rel="nofollow noreferrer"><code>divmod</code></a> to break down the seconds into full hours, minutes and seconds:</p> <blockquote> <p>divmod(a, b)</p> ...
python-2.7
2
3,453
41,432,212
Insure app is original and not modified
<p>Could someone explain to me how (any) general app's processes are authenticated against original code to insure malicious actors don't wreck havoc?</p> <p>i.e. everyone is using approved or same version of a particular app and someone hasn't written something similar to interact with original.</p>
<p>One of the method to check code authenticity is check the checksum and compare it. You can use the following code to compute the checksum.</p> <pre><code>import hashlib md5checksum = hashlib.md5("filename.py").hexdigest() </code></pre>
javascript|python|reactjs
1
3,454
57,227,998
Reshape (grouping or pivoting) pandas dataframe by converting a row into a column
<p>I want to reshape a dataframe from this shape</p> <pre class="lang-py prettyprint-override"><code>Country subject 2017 2018 Frq 2017 Score 2018 Score Argentina subject 1 12 22 100 50.77214238 51.54316539 Argentina subject 2 68 13 150 66.92805676 67.60645268 </code></pre> ...
<p>You can do <code>unstack</code> </p> <pre><code>s=df.set_index(['Country','subject']).stack().unstack([1,2]).reset_index() </code></pre>
pandas|pivot-table|pandas-groupby
0
3,455
20,666,947
screen support in kivy set to normal and large screens
<p>Is there a way to establish a "supports-screens" kind of configuration to make my application available only for normal and large screens android devices.is there a way to do this with the build.py script?(i have bets on --intent-filters option but not sure how it might be used)</p>
<p>There is no way to do it from the build.py. However, you can change manually the <code>templates/AndroidManifest.xml.tmpl</code> and adapt it for your needs.</p>
android|python-2.7|kivy
1
3,456
29,342,042
How to set timeouts between connections using gevent.server in Python?
<p>How to set timeouts between connections using gevent.server in Python?</p> <pre><code>from gevent.server import StreamServer def handle(socket, address): message = socket.recv(1024) if __name__ == "__main__": server = StreamServer((SERVER_HOST, SERVER_PORT), handle) server.serve_forever()...
<pre><code>from gevent.server import StreamServer import gevent lock = {} def handle(socket, address): if address[0] in lock.keys(): print "sleep" gevent.sleep(1) handle(socket, address) lock[address[0]] = 1 try: message = socket.recv(1024) print address final...
python|timeout|server|serversocket|gevent
0
3,457
49,753,494
Access to google search console api through google app engine (read-only file system)
<p>When I use oauth2client.file.storage.get() in an google app engine application, it returns IOError(errno.EROFS, 'Read-only file system', filename). The log stack is shown below:</p> <pre><code>File "c:\Users\john\AppData\Local\Google\Cloud SDK\gsc2gbq-test\main.py", line 291, in main run_wsgi_app(app) File "C:\User...
<p>My own question is solved. So I post my solution here and hope it could help you out there when you read this.</p> <p>The problem was the short-live token for credential file has to be refreshed and thus new token has to be written to the the credential file on google app engine.</p> <p>I could not have this done ...
google-cloud-platform|google-app-engine-python|google-search-console
1
3,458
53,546,156
What is the difference between __metaclass__ attribute and metaclass kwarg
<p>What is the difference between the class attribute <code>__metaclass__</code> and the class keyword argument <code>metaclass</code>.</p> <p>Consider this example:</p> <pre><code>class Meta1(type): def __new__(cls, name, bases, attrs): attrs.update({'x': 100}) return super().__new__(cls, name, b...
<p><code>__metaclass__</code> attribute is python2 syntax for declaring a metaclass. The <code>metaclass=</code> kwarg is python3 syntax for it.</p> <p>If you need one codebase to support both python2 and python3 you can use <code>future</code>, which has <a href="https://python-future.org/what_else.html#metaclasses" ...
python|python-3.x
4
3,459
30,787,397
Pycharm, virtualenv and kivy setup
<p>I'm moving to pycharm from sublime text and can't get it working with kivy and virtualenv. I've created a virtualenv with a new project in pycharm but I can't figure out how to get kivy working. The kivy help shows using the kivy.bat as the python interpreter but I want to use the virtualenv. One possible option wou...
<p>I found a way to set the environmental variables found in the kivy.bat. I simply created a new .bat that sets the environmental variables and then runs pycharm from the command line. This allows the variables to persist between projects.</p>
python|pycharm|kivy
0
3,460
29,309,016
Bundling a PyQt5 application using py2app: keep getting "Abort trap: 6" error
<p>I am trying to create an OS X application from this code:</p> <pre><code>import sys from PyQt5.QtWidgets import QApplication if __name__ == "__main__": app = QApplication(sys.argv) app.lastWindowClosed.connect(app.quit) sys.exit(app.exec_()) </code></pre> <p>I'm in OS X 10.10 using py2app (0.9.1) and ...
<p>You import <code>QApplication</code> and then you try to instantiate it using the package name: <code>QtWidgets.QApplication</code> Apart from that, I used the following setup.py and it worked:</p> <pre><code>from setuptools import setup setup( app=["MyApplication.py"], setup_requires=["py2app"], ) </code></pre> <...
python|pyqt|py2app|pyqt5
2
3,461
52,598,458
How to print Alternate A.P and G.P series in Python
<p>I want to print Alternate A.P and G.P series like:</p> <pre><code>- 2 2 4 6 6 18 8 54 10 162 12 486... i.e (A1 G1 A2 G2 A3 G3 .....) </code></pre> <p>here variable is with literal meaning asinged below. I found in form of </p> <pre><code>[(2, 2), (4, 6), (6, 18), (8, 54), (10, 162), (12, 486), (14, 1458), (16, ...
<p>if you just want to <a href="https://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python">flatten your list</a>, you could use <a href="https://docs.python.org/3/library/itertools.html?itertools.chain.from_iterable#itertools.chain.from_iterable" rel="nofollow noreferrer"><code>iterto...
python|python-3.x
0
3,462
47,311,632
Jupyter | How to rotate 3D graph
<p>I am not sure about how to rotate graph in Python Jupyter notebook, its static for me and not rotate on mouse movement</p> <pre><code>from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(111, projection='3d') x =[1,2,3,4,5,6,7,8,9,10] y =[5,6,2,3,13,4,1,2...
<p>To enable interactivity you need to use the <code>notebook</code> backend of matplotlib. You can do this by running <code>%matplotlib notebook</code>.</p> <p>This must be done before you plot anything, e.g.:</p> <pre><code>%matplotlib notebook import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import axes3...
python|matplotlib|jupyter-notebook
95
3,463
64,503,725
How can I export installed libraries on Python to one install shell?
<p>Recently, I'm changing Linux distro from PopOs to Ubuntu, and there is a lot of libraries installed by pip on Python that I want to bring on. Could I migrate from these other distros, exporting and import all installed libraries on python? There's a way to do that?</p>
<p>You should read about the <a href="https://www.techiediaries.com/python-pip-local-cache/" rel="nofollow noreferrer">pip cache system</a> and how to enabled in different OS. If you already have a pip cache directory configured you can tell where is by:</p> <pre><code>pip cache dir </code></pre> <p>And then you could ...
python|linux|pip|libraries|linux-distro
0
3,464
64,473,721
Discord.py custom statuses animation
<p>I have started experimenting with Discordbots in python, and a friend of mine taught me that you can customize the game activity manually with your Bot. So here is my Question: If you type in the activity1, is there a way to add to activity2 and they swap each second in an infinite loop? Thanks</p>
<p>You have to use <code>tasks.loop</code></p> <p>Below is the code:</p> <pre><code>from discord.ext import tasks @bot.event async def on_ready(): print(&quot;Online&quot;) bot.statuses = cycle(['Activity 1', 'Activity 2']) change_status.start() @tasks.loop(seconds=30) async def change_status(): await b...
python|discord.py
0
3,465
64,344,798
How to change output of graph title from a list?
<p>I have this for loop in python</p> <pre><code>for i in range(len(population_data[&quot;State&quot;])): list = (population_data[&quot;State&quot;][i]) </code></pre> <p>which prints the list of states</p> <pre><code>AK AL AR AZ . . . WY </code></pre> <p>I am creating multiple graphs, and I need the title on each ...
<p>its simple</p> <pre><code>for i in list: plt.title(&quot;%s&quot; %i) </code></pre>
python|python-3.x|list|for-loop
0
3,466
64,372,390
What does BUFFER_SIZE do in Tensorflow Dataset shuffling?
<p>So I've been play around with this code: <a href="https://www.tensorflow.org/tutorials/generative/dcgan" rel="nofollow noreferrer">https://www.tensorflow.org/tutorials/generative/dcgan</a> and have almost developed a good idea about its functioning. However, I can't quite discover what is the <strong>BUFFER_SIZE</st...
<p>It's used as the <code>buffer_size</code> argument in <code>tf.data.Dataset.shuffle</code>. Have you read the <a href="https://www.tensorflow.org/api_docs/python/tf/data/Dataset#shuffle" rel="nofollow noreferrer">docs</a>?</p> <blockquote> <p>This dataset fills a buffer with <code>buffer_size</code> elements, then r...
python|tensorflow|machine-learning|generative-adversarial-network
1
3,467
69,753,069
pytest collecting test cases but not executing the script
<p><a href="https://i.stack.imgur.com/Ff4Ed.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ff4Ed.png" alt="enter image description here" /></a></p> <p>I am trying to run a pytest script like this :</p> <p><code>pytest myfile.py -m marker_name -v -s --disable-warnings</code></p> <p>pytest.ini contain...
<p>To me it looks like you did not add the marker to the test file at all. From your description how you run the test file, you would only run the tests, marked with the <code>marker_name</code>, but you do not have any tests marked correctly.</p> <p>You need to mark the tests with <code>@pytest.mark.marker_name</code>...
python|linux|pytest|pytest-markers
0
3,468
73,026,896
css is not working after deploying django application on aws with gunicorn nginx
<p>I have deployed my django project on EC2 but the css is not working after deployement. I also ran collcectstatic command but still got unlucky, when I checked in nginx error.log it showing in front of css files that permission denied like this:</p> <blockquote> <p>2022/07/18 17:38:01 [error] 2262#2262: *4 open() &qu...
<p>In the absence of STATICFILES_STORAGE, your location value in your nginx config should reflect the name of the folder you are putting your files in. In this case, the same folder as your STATIC_ROOT.</p> <pre><code>location /static/ { alias /home/ubuntu/theoj/online_judge_project/staticfiles/; } </code></pre> <p...
python|django|nginx|amazon-ec2|gunicorn
0
3,469
55,595,203
Scrapy FormRequest can't handle complex dicts as formdata
<p>I am trying to provide formdata to a scrapy.FormRequest object. The formdata is a dict of the following structure: </p> <pre><code>{ "param1": [ { "paramA": "valueA", "paramB": "valueB" } ] } </code></pre> <p>via equivalent to the following code, run in scrapy shell:</p> <pre><code>from sc...
<p>Instead of <code>formdata</code> you can try to use <code>body</code> parameter. Example:</p> <pre><code>FormRequest(url=url, method=method_post, body=json.dumps(formdata)) </code></pre>
python|web-scraping|scrapy|form-data|scrapy-shell
6
3,470
50,220,573
Manipulating data from text file - Python 2.7
<p><strong>I need help importing data like this from a text file:</strong></p> <p>Orville Wright 21 July 1988 </p> <p>Rogelio Holloway 13 September 1988 </p> <p>Marjorie Figueroa 9 October 1988</p> <p><strong>and display it on the python shell like this:</strong></p> <p>Name</p> <ol> <li>O. Wright</li> <li>R. H...
<p>Read lines of files into a list <a href="https://stackoverflow.com/questions/3277503/in-python-how-do-i-read-a-file-line-by-line-into-a-list">In Python, how do I read a file line-by-line into a list?</a></p> <p>Enumeration <a href="https://docs.python.org/2.3/whatsnew/section-enumerate.html" rel="nofollow noreferre...
python|python-2.7|file-io|external-data-source
-1
3,471
50,110,824
ssl handshake failure using proxy for scrapy
<p>I'm trying to setup a proxy on a scrapy project. I followed te instructions from this <a href="https://stackoverflow.com/questions/4710483/scrapy-and-proxies?utm_medium=organic&amp;utm_source=google_rich_qa&amp;utm_campaign=google_rich_qa">answer</a>:</p> <p>"1-Create a new file called “middlewares.py” and save it ...
<p>I think the issue may be related to you touching the order of the <code>ProxyMiddleware</code>. I updated your code and ran it like below</p> <p>from scrapy import Spider</p> <pre><code>class Test(Spider): name ="proxyapp" start_urls = ["https://www.coursetalk.com/subjects/data-science/courses"] cust...
python|proxy|scrapy
1
3,472
66,475,052
Django filter all items within bounding box (by LAT, LNG)
<p>I use <code>Postgres</code> with <code>Django</code> and I have a model <code>Parcel</code> that has coordinate fields:</p> <pre><code>address_lat = models.DecimalField... address_lat = models.DecimalField... </code></pre> <p>I'm trying to create a method (on Manager) that returns all parcels withing the given area ...
<p>You have computed a factor taking into consideration the latitude, but you forgot to them apply your buffer distance.</p> <pre><code>lng_change = Decimal(km / 111.2) * Decimal(abs(math.cos(lat * (Decimal(math.pi) / Decimal(180))))) </code></pre>
python|django|postgresql|geometry|coordinates
1
3,473
66,728,134
numpy - why mean and SD are unstable for the same value?
<h1>Question</h1> <p>Why the same value <code>-3.29686744</code> results in different mean and standard deviation?</p> <h2>Expected</h2> <pre><code>X = np.array([ [-1.11793447, -3.29686744, -3.50615096], [-1.11793447, -3.29686744, -3.50615096], [-1.11793447, -3.29686744, -3.50615096] ]) mean = np.mean(X, a...
<p>This is normal behavior when you consider that IEEE-754 double precision floats are stored as 64 bits of data. 53 bits are mantissa 10 bits are exponent, and one bit is sign. You can look up the details elsewhere.</p> <p>The important part is that floats are effectively stored as integers with a scale factor. This i...
numpy|rounding-error
1
3,474
64,029,672
Python - Flask with mercure_hub
<p>I tried to follow chat implementation from here <a href="https://github.com/dunglas/mercure/tree/master/examples/chat" rel="nofollow noreferrer">https://github.com/dunglas/mercure/tree/master/examples/chat</a>. But so far, I didn't succeed to achieve that.</p> <p>For Mercure hub implementation I build a small docker...
<p>I figured it out :</p> <p>So first SUBSCRIPTIONS to 1 <a href="https://github.com/dunglas/mercure/issues/324" rel="nofollow noreferrer">issue</a>:</p> <pre><code>version: '3.5' services: mercure: container_name: mercure image: dunglas/mercure environment: - JWT_KEY=!ChangeMe! - DEMO=1 ...
python|flask|mercure
0
3,475
65,479,239
Most Pythonic way to convert None to an empty list in case a default argument is not passed in a Function?
<p>I want to write a general function that takes two input variables <code>var1</code>, <code>var2</code> and returns the concatenation of both.</p> <p>Each variable has the default value <code>None</code>, and can be either a single element or a <code>list</code>.</p> <p>The expected output should be a <strong>list</s...
<p>Instead of <code>None</code> you could use <code>[]</code> as a default argument for each <code>var</code>.</p> <pre><code>def my_func(var1 = [], var2 = []): if not isinstance(var1, list): var1 = [var1] if not isinstance(var2, list): var2 = [var2] return var1 + var2 lst = my_fun...
python|list|function|nonetype|default-arguments
6
3,476
65,233,569
How to check if user input is the same as the first item in each subtuple?
<p>I want to check if user input is the same as any of the first items of the subtuples in a tuple. Then, if it is the same, I want to print the subtuple. I've seen others use <code>any</code> but it doesn't work. I'm not really sure how to iterate over all the subtuples because I am given the error message:</p> <pre><...
<p>Looping iterates over the items directly, not the indices, so I would call the loop variable <code>subtuple</code> instead of <code>i</code> and get rid of all the bracketed lookups.</p> <pre><code>for subtuple in a: if subtuple[0] == input_city: print(subtuple) </code></pre>
python
1
3,477
71,517,415
Using Filter or Q in Aggregation
<pre><code>class Streamer(models.Model): name = models.CharField(max_length=50, null=True) is_working_with_us = models.BooleanField(default=False) class Account(models.Model): streamer = models.ForeignKey(Streamer, on_delete=models.CASCADE) salary= models.Decimalfield(decimal_places=2, max_digits=7) ...
<p>You can use a <a href="https://docs.djangoproject.com/en/dev/ref/models/querysets/#filter-1" rel="nofollow noreferrer"><strong><code>filter=…</code></strong> parameter <sup>[Django-doc]</sup></a>:</p> <pre><code>streamer_salary_stats = Streamer.objects.filter(is_working_with_us=True).aggregate( expensive_streamers...
python|mysql|django|orm
2
3,478
71,487,975
How to detect the colour of the specific pixel the mouse curser is directly on (for any place on the screen)
<p>I am trying to automate some work using python code and the function &quot;pyautogui&quot; but I need to find a way to detect colours where the mouse is on the screen. Anyone has any solutions? Thanking in advance.</p>
<pre><code>import pyautogui while True: x, y = pyautogui.position() px = pyautogui.pixel(x, y) print(px) </code></pre>
python-3.x|opencv|pyautogui
1
3,479
10,726,361
seek ( ) while reading in binary files
<p>I'm an uber-beginner with Python; I've rather been thrown into the deep end. A bit of background: the files we're reading are from a sonar imaging camera; at the moment I'm trying to read in attributes written into the files such as date, filename, number of frames, number of beams, etc. First, I'd like to read in...
<p>You read the entire contents of the file into <code>didson_data</code>, then seek the file handler <code>didson_file</code> back to zero, and never use it again as you're splitting all your fields up from <code>didson_data</code> and not stepping through lines/chunks in your file, so of course your second <code>.tel...
python|binary-data|seek
2
3,480
4,856,373
Adding to an array every 1 second in python
<p>Can anyone please help me to add to an array every second? thanks.</p>
<p>You can simply do <code>time.sleep(secs)</code> to create a delay in a script.</p> <pre><code>import time ls = [] add = True while add: ls.append(0) time.sleep(1) </code></pre>
python|timer
2
3,481
62,646,061
How to convert different date formats in pandas?
<p>I have 2 columns with different date formats. In every row string dates are formatted differently.<br /> I want to convert the columns to Date type. However, I am wondering if there is any built in method that will do the parsing for me:</p> <p><strong>What I tried</strong></p> <pre><code>from datetime import dateti...
<p>Data</p> <pre><code>newDF=pd.DataFrame({'Effective_Date':['10/07/2016','10/07/2016 09:00','09 August 2016'],'Paid_Off_Time':['10 July 2016','10/08/2016','10/09/2016 01:00:30']}) Effective_Date Paid_Off_Time 0 10/07/2016 10 July 2016 1 10/07/2016 09:00 10/08/2016 2 09 August 20...
python-3.x|pandas
1
3,482
61,905,358
Extract specific JSON from log file in Python
<p>I am trying to extract particular JSON from log file which contains multiple JSON and normal text, in this case I am trying to extract JSON containing "Output payload" text. I have tried multiple ways but not able to extract required JSON, the file is in the format:</p> <pre><code>[2020-05-17 15:32:11.698000] INFO ...
<p>You could probably read the file as text and then parse it with regex. Something like this:</p> <pre class="lang-py prettyprint-override"><code>import re logfile = open(logfilepath, 'r') log = logfile.read() logfile.close() objects = re.findall("(Output payload.*:\s?)(\{\s?[\s\S]+?\s?\})", log) </code></pre> <p>I...
python|json
0
3,483
61,976,553
display and save a piechart with tkinter
<p>1) I have a problem with listbox,when user selected one of the country names in the listbox i want it to show the name as entry (default text).</p> <p>2) after that when i click save button it shows error(actually,I don't know what is about).user could enter the name of the desire country(everything is possible).</...
<p>To achieve what you want, you need to use a <a href="https://docs.python.org/3/library/tkinter.ttk.html#tkinter.ttk.Treeview" rel="nofollow noreferrer"><code>Treeview</code></a> widget. </p> <p>Also, to make the treeview editable(with textboxes, like you said), see this <a href="https://stackoverflow.com/a/18815802...
python|pandas|matplotlib|tkinter|pickle
0
3,484
71,130,519
framerate independent movement breaking at higher fps?
<p>I am trying to understand framerate independence and wrote this test code: import pygame, sys, time</p> <pre><code>pygame.init() screen = pygame.display.set_mode((1280,720)) clock = pygame.time.Clock() framerate = 60 test_rect = pygame.Rect(0,340,40,40) move_speed = 300 prev_time = time.time() while True: fo...
<p><a href="https://www.pygame.org/docs/ref/time.html#pygame.time.Clock.tick" rel="nofollow noreferrer"><code>tick()</code></a> already returns how many milliseconds have passed since the last call. So there is no need to use <code>time</code>:</p> <pre class="lang-py prettyprint-override"><code>clock = pygame.time.Clo...
python|pygame
0
3,485
70,100,312
Django's user_passes_test always gets Anonymous User
<p>I'm using the following class-based view and applying the <a href="https://docs.djangoproject.com/en/3.2/topics/auth/default/#django.contrib.auth.mixins.UserPassesTestMixin" rel="nofollow noreferrer">UserPassesTestMixin</a> to it to check some pre-conditions.</p> <pre><code>class SomeTestView(UserPassesTestMixin, AP...
<blockquote> <p>What I'm not able to understand is that why is the <code>request.user</code> anonymous inside the <code>user_passes_test</code> check.</p> </blockquote> <p>The <code>UserPassesTestMixin</code> does <em>not</em> check if the user has logged in. Sometimes you might want to check a property that can be <co...
python|django|django-rest-framework|django-views
2
3,486
70,152,689
Why isn't my image drawing correctly in my platformer?
<p>I've been following a tutorial online just to get a simple 2D platformer working and I can't understand why it can't get the boxes to draw? Also the poorly drawn stick figure is being drawn in 2 parts that are then broken</p> <p>I've tried messing with the values for 'stickman.png', 'woodenboxbutsmaller.png' and win...
<p>There is a typo in your application. It has to be <code>self.image = pygame.image.load(image)</code> instead of <code>self.image = pygame.image.load('stickman.png')</code> (in class <code>Sprite</code>).</p>
python|pygame
0
3,487
63,335,110
What is the python equivalent of curl -x
<p>What is the -x option in curl and how to implement equivalent command in python using the requests library. I want the following command to be in python.</p> <pre><code>curl \ -X DELETE \ -H &quot;Accept: application/vnd.github.v3+json&quot; \ https://api.github.com/repos/octocat/hello-world </code></pre>
<pre class="lang-py prettyprint-override"><code>import requests headers = {'Accept': 'application/vnd.github.v3+json'} response = requests.delete(url='https://api.github.com/repos/octocat/hello-world', headers=headers) </code></pre> <p><code>-X DELETE</code> is the HTTP method you are using, here we use <code>delete<...
python-3.x|rest|curl|python-requests
1
3,488
56,627,106
Reading an n-dimensional complex array from a text file to numpy
<p>I am trying to read a N-dimensional complex array from a text file to numpy. The text file is formatted as shown below (including the square brackets in the text file, in a single line):</p> <pre><code>[[[-0.26905+0.956854i -0.96105+0.319635i -0.306649+0.310259i] [0.27701-0.943866i -0.946656-0.292134i -0.334658+0.9...
<p>as it seems your file is not in a "pythonic" list ( no comma between object).</p> <p>I assume the following:</p> <ol> <li>you can not change your input, you get it from 3rd party source)</li> <li>the file is not a csv. ( no delimiter between rows)</li> </ol> <p>as a result :</p> <ol> <li>try to convert the strin...
python|python-3.x|numpy|text
0
3,489
56,617,521
"Ambiguous Class Definition" for classname "I" (Pep8 in Python)
<p><strong>Question:</strong> Why does PEP8 raise a warning <code>PEP8: amiguous class definition 'I'</code> when I try to define a class of name <code>I</code>? I could not find that there is any build-in <code>I</code>.</p> <p><a href="https://i.stack.imgur.com/Ayubm.png" rel="nofollow noreferrer"><img src="https://...
<p>According to <a href="https://www.python.org/dev/peps/pep-0008/#names-to-avoid" rel="noreferrer">PEP 8: Names to avoid</a>:</p> <blockquote> <p>Never use the characters 'l' (lowercase letter el), 'O' (uppercase letter oh), or 'I' (uppercase letter eye) as single character variable names.</p> <p>In some f...
python|class|pycharm|pep8
8
3,490
17,986,485
AttributeError: 'bool' object has no attribute 'keys'
<p>i am a newbie on this site and am also a newbie to programming, i'm trying to learn python using a book for beginners on python 3.1. I have come across an example that just won't work whatever I try, I have searched for faults in writing about 10 times still it seems exactly what I see in the book. This is the examp...
<pre><code>def get_ingredients(self, fridge): self.from_fridge= fridge.get_ingredients(self) </code></pre> <p>In this function, your <code>fridge.get_ingredients()</code> might be returning <code>False</code>.</p> <p>So <code>self.from_fridge</code> has <code>Boolean</code> value which does not have <code>keys()<...
python
2
3,491
60,950,147
Scraping images from websites in a list
<p>I would like to know if it is possible to scrape images in websites with a code that can work for all the types of websites (I mean independently of the HTML format). I have a list of websites ant I would need to get all the images related to each link. For instance: </p> <p><code>list_of links=</code>['<a href="...
<p>Assuming all the images are inside <code>src</code> tag and those image elements aren't dynamically added (not virtual DOM), modifying your code a little bit would work:</p> <pre><code>from urllib.request import urlopen from bs4 import BeautifulSoup import re link= '...' html = urlopen(link) bs = BeautifulSoup(ht...
python|web-scraping
0
3,492
66,129,847
Pythonic Way to group sections of a list into multiple lists based off value
<p>Below is a plot I made where the y-axis (v) are values contained in a list. As you can see, the list values alternate between segments of high values and segments of low values such that the list looks like:</p> <pre><code>li = [0.5,0.49,0.5,..,0.5,0.001,0.001,...,0.001,0.49,0.5,...,0.5,] </code></pre> <p>My goal is...
<p>Using <code>numpy</code> and spliting by the mean.</p> <pre><code>import numpy as np li = np.array([ 0.5, 0.49, 0.5, 0.001, 0.001, 0.001, 0.49, 0.5, 0.5, 0, 0.002, 0.01, ]) # Split into high/low groups using the mean: is_high = li &gt;= li.mean() is_low = li &lt; li.mean() # Determine the groups: ...
python|list|for-loop|list-comprehension
1
3,493
69,218,491
Making two bots count each other's messages
<p>So, as a holiday project, I'm trying to make two bots who reply to the other's messages. They'll check the ID of the sender and if it matches the ID of the other bot, it will send a message with the number of times that bot has replied.</p> <p>The problem is that when I try to execute this, both bots send two messag...
<p>In every message, you are setting the tally variable to 0. This is resetting the counter and thus it doesn't increase</p> <p>About the variable being referenced before assignment, you should define it above the function for clarity. Defining it anywhere <strong>before</strong> <code>client.run</code> is gonna work, ...
python|discord|bots
0
3,494
69,016,674
Flag difference in panda dataframe
<p>I have pandas dataset and want to create a column that would flag the difference</p> <p>i.e Column B should have the same values for each value in column A and vice versa. If it's not then flag it as 1</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>column A</th> <th>Column B</th> <th>Ne...
<p>Since the question is updated, here is a way of doing it. I use this data :</p> <pre><code>df = pd.DataFrame({&quot;column A&quot;: [&quot;Atlanta&quot;, &quot;Atlanta&quot;, &quot;New York&quot;, &quot;New York&quot;], &quot;column B&quot;: [&quot;AT&quot;, &quot;AT&quot;, &quot;YN&quot;, &quot;NY&quot;]}) df c...
python|pandas|conditional-statements
1
3,495
72,633,802
multiprocessing + logging + tqdm progress bar flashing
<p>Can someone experienced with <code>tqdm</code> help me with the following reproducer please?</p> <pre><code>import itertools import logging import multiprocessing import random import sys import time import tqdm from tqdm.contrib import DummyTqdmFile log: logging.Logger = logging.getLogger(__name__) DEFAULT_FORM...
<p>Maybe this will partially help. This concerns progress in multiprocessing. After doing some research, I wrote a small module called <a href="https://github.com/dubovikmaster/parallelbar" rel="nofollow noreferrer">parallelbar</a>. It allows you to display both the overall progress of the pool and for each core separa...
python|python-multiprocessing|tqdm|python-logging
0
3,496
68,105,951
Combining two dataframes into 1 (only taking certain columns!)
<p>This is probably easy, but I have the following data:</p> <p>In data frame 1:</p> <pre><code>ID data data2 0 9 66 1 5 664 </code></pre> <p>In data frame 2:</p> <pre><code>ID data data6 2 7 tt 3 6 xtt </code></pre> <p>I want a data frame with the following for (only taking the first 2 columns fro...
<pre><code>pd.concat([df1[['ID', 'data']], df2[['ID', 'data']]]) </code></pre> <p>solved - Thanks Chris</p>
python|pandas
0
3,497
68,132,164
Groupby Pandas & Weight Time Series
<p>i'm trying to compute the weights for each time series or data values by the groupby of &quot;plant_name&quot; and &quot;month&quot; and I cannot see the solution. I have data that looks like this -</p> <pre><code> plant_name month adjusted_wspd 0 ARIZONA I 1 7.62 1 ARIZONA I 2 ...
<p>Let's try <a href="https://pandas.pydata.org/docs/reference/api/pandas.core.groupby.DataFrameGroupBy.transform.html#pandas-core-groupby-dataframegroupby-transform" rel="nofollow noreferrer"><code>groupby transform</code></a> sum on just <code>plant_name</code> not <code>plant_name</code> and <code>month</code>:</p> ...
pandas|group-by|apply|weighted
1
3,498
68,082,600
how to plot class labels using a distribution list
<p>I have a dataset with train and test sets and three classes <code>A</code>,<code>B</code>,and <code>C</code>. I want to create a plot in which I show the distribution of data labels in each class for TRAIN and TEST sets separately (these are binary class labels 0 and 1). Ideally, I would like to show TRAIN and TEST ...
<pre><code>labels = ['a_train', 'a_test', 'b_train', 'b_test','c_train','c_test'] Positive = [40, 10, 41, 10, 51, 12] Negative = [75, 19, 75, 19, 75, 19] x = np.arange(len(labels)) width = 0.30 # the width of the bars fig, ax = plt.subplots() rects1 = a...
python|python-3.x|matplotlib|plot
1
3,499
68,158,933
Does a decorator run once even if the decorated function was called many times?
<p>so this code is supposed to count how many times a functions is called, but I'm trying to understand decorating in python more deeply and not just copying code, by running this code below</p> <pre><code>def counter(func): print('counter function executed') def wrapper(*args, **kwargs): print('wrapper...
<p>The decorator runs only at the time the decorated function is defined, in order to modify the function definition. The function returned by the decorator (<code>wrapper</code>) is what gets executed each time the decorated function is called.</p>
python|function|python-decorators
2