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 |
|---|---|---|---|---|---|---|
5,600 | 43,498,921 | How to set global variable with method | <pre><code>abc = None
def load() :
abc = cPickle.load('a.pkl')
load()
def main(review):
print abc.predict('example')
</code></pre>
<p>The variable <code>abc</code> is still set to <code>None</code>. <code>main</code> is accessing <code>abc</code> many times and I don't want to load the file every time. H... | <p>With <code>global</code> keyword</p>
<pre><code>abc = None
def load() :
global abc
abc = cPickle.load('a.pkl')
load()
def main(review):
print abc.predict('example')
</code></pre>
<p>Without <code>global</code> interpreter will create a new local variable <code>tested</code> in function scope.<br>
B... | python | 2 |
5,601 | 54,305,922 | Eclipse PyDevd remote debugger Raspberry Pi | <p>I have just created a <strong>SSH</strong> connection between my <strong>Raspberry Pi 3 b+</strong> and my computer using WiFi. I have downloaded <strong>Eclipse</strong> and the <strong>PyDev</strong> and <strong>RSE</strong> plugins so I can use Eclipse as IDE for my Python scriptss that I need to run on my Rasp P... | <p>After looking for an answer I came up with the solution of disabling the firewall and it worked. So i'ts a matter of the access that are permited in the firewall.</p> | python|eclipse|raspberry-pi|pydev|remote-debugging | 0 |
5,602 | 54,388,823 | Sending a .mp4 file over sockets in python3 | <p>I am trying to make two small programs; one is a server which will receive mp4 files from a client. The client is just a small program that sends a .mp4 file located in its folder.</p>
<p>I am able to fully send the mp4 file and a file in the same size is created, but for some reason the mp4 gets corrupted or someth... | <p>Fix bugs in your server code:</p>
<pre><code>#!/usr/bin/python3
from socket import socket, gethostname
s = socket()
host = gethostname()
port = 3399
s.bind((host, port))
s.listen(5)
n = 0
while True:
print("Listening for connections...")
connection, addr = s.accept()
try:
print("Starting to... | python-3.x|file|sockets|video|mp4 | 2 |
5,603 | 9,274,322 | Django Authentication from .NET Application | <p>My main data-storage system is built on Django. However, due to inevitable reasons, I have to develop another desktop application for data-entry that uses .NET platform. </p>
<p>However, how can I authenticate the .NET application based on Django user authentication? I looked at the encrypted password, and apparent... | <p>The passwords aren't encrypted, they're hashed. There is a big difference. You don't want to encrypt passwords, as when you encrypt something you're expecting to be able to unencrypt it. With passwords, you <em>never</em> want to unencrypt them: when you're checking that the user has entered their password correctly... | .net|python|django|web | 3 |
5,604 | 39,071,351 | Get the number of same string in a list | <p>I want to get the no. of same string in a list</p>
<p>Example</p>
<pre><code>list = ['jack','jeen','jeen']
number_of_jeen = getnumber('jeen',list)
print(number_of_jeen)
</code></pre>
<p>Output</p>
<pre><code>2
</code></pre>
<p>I have tried this so far</p>
<pre><code>def getnumber(string_var,list):
if any... | <p>There's a built-in method <code>count</code> that does this.</p>
<pre><code>number_of_jeen = list.count('jeen')
</code></pre> | python | 6 |
5,605 | 39,262,664 | How I can either deny a login or registration a user based on current session | <p>How can I deny or redirect an active user to the logged-in screen?</p>
<p>I want, user only can access pages when current session allows the access. </p>
<p>Is this can be done directly in the HTML code or only in views ?</p> | <p>If I understand you correctly, you mean that the user shouldn't see the login and signup links (maybe in the topbar). This can be done in the template as:</p>
<pre><code>{% if user.is_authenticated %}
<!-- show logout link/button -->
{% else %}
<!-- show login and signup links/buttons -->
{% endif %}
</... | python|html|django|redirect|views | 0 |
5,606 | 52,545,000 | Tensorflow.js loading model returns function predict is not defined | <p>When I load a saved model like this (please dont mind the fact that the predict function has no input)</p>
<pre><code>const tf = require('@tensorflow/tfjs');
require('@tensorflow/tfjs-node');
const model = tf.loadModel('file://./model-1a/model.json').then(() => {
model.predict();
});
</code></pre>
<p>I get t... | <p>You need to work with <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" rel="noreferrer">promises</a>.</p>
<p><code>loadModel()</code> returns a promise resolving into the loaded model. So to access it you either need to use the <code>.then()</code> notation or be in... | javascript|tensorflow.js | 5 |
5,607 | 47,638,877 | Using PhraseMatcher in SpaCy to find multiple match types | <p>The SpaCy documentation and samples show that the PhraseMatcher class is useful to match sequences of tokens in documents. One must provide a vocabulary of sequences that will be matched.</p>
<p>In my application, I have documents that are collections of tokens and phrases. There are entities of different types. Th... | <p>spaCy's <code>PhraseMatcher</code> supports adding multiple rules containing several patterns, and assigning IDs to each matcher rule you add. If two rules overlap, both matches will be returned. So you could do something like this:</p>
<pre><code>color_patterns = [nlp(text) for text in ('red', 'green', 'yellow')]
... | python|nlp|spacy | 38 |
5,608 | 37,350,450 | Why is a list access O(1) in Python? | <p>I understand that a list is different from an array. But still, O(1)? That would mean accessing an element in a list would be as fast as accessing an element in a dict, which we all know is not true.
My question is based on <a href="https://wiki.python.org/moin/TimeComplexity" rel="noreferrer">this document</a>:</p>... | <p>Get item is getting an item in a specific index, while lookup means searching if some element exists in the list. To do so, unless the list is sorted, you will need to iterate all elements, and have <code>O(n)</code> Get Item operations, which leads to O(n) lookup.</p>
<p>A dictionary is maintaining a smart data st... | python|list|dictionary|data-structures|time-complexity | 34 |
5,609 | 66,101,812 | Merging items in list given condition | <p>Let's say I have <code>['A B', 'B C', 'X Y', 'C D', 'Y Z', 'D E', 'C G']</code>.</p>
<p>If the second word in each element of the list is same as first word in any other elements in the list, they should be merged into one item. The order matters as well.</p>
<p><code>['A B C D E G', 'X Y Z']</code> should be the fi... | <p>A simple algorithm solving this appears to be:</p>
<ul>
<li>initialize <em>results</em> as empty list</li>
<li>repeat for each <em>pair</em> in input list:
<ul>
<li>repeat for each sublist <em>R</em> in <em>results</em>:
<ul>
<li>if <em>R</em> contains the first item of <em>pair</em>, append second item to <em>R</em... | python|list|algorithm | 1 |
5,610 | 7,141,621 | Django error: AttributeError: 'NoneType' object has no attribute 'db' | <p>Has anyone seen this error before? It comes whenever I try to execute a query on a particular model of mine. Querying the db directly works fine and it doesn't happen with other models. </p>
<p>For example, it's triggered by something like:</p>
<pre><code>MyModel.objects.get(name__iexact = 'an existent name')
<... | <p>Kicking myself for this one, especially given how obvious the error message makes it in retrospect.</p>
<p>My migration had added a new field named "_state" to the model. This field collided with the _state attribute of the object referenced in line 289 of query.pyc above.</p>
<p>So new lesson: no field can be na... | python|django|django-south | 0 |
5,611 | 31,769,525 | Printing a list as a string without parentheses or commas in python | <p>I have the list :: <code>[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]</code>
created by a loop. </p>
<p>I want it to print</p>
<pre><code>0 1 2 3 4 5 6 7 8 9
</code></pre>
<p>I've used the <code>.strip('[]')</code> to get rid of the parentheses but I cannot get rid of the commas. </p> | <p>You're trying to mutate the list's respresenting string instead of using it's members to build your specific
representation. This is not the way to go.</p>
<p>Use <a href="https://docs.python.org/3/library/functions.html#map" rel="nofollow"><code>map</code></a> to create strings and <a href="https://docs.python.org... | python | 4 |
5,612 | 38,845,134 | Saving and searching data with Tkinter entry boxes | <p>This might be a strange question because I am new to Python.</p>
<p>I am trying to create form in Python which data can be entered into boxes and saved, then opened again. I'm currently using Tkinter to create a Gui which has entry boxes and buttons:</p>
<pre><code>import sys
from tkinter import *
def mstore():
p... | <p><strong>Hello Gregulimy!</strong></p>
<p>I have simplified your code and made it do what you want it to do. I have left comments explaining what the code does. If you have any questions about what I have done feel free to ask!</p>
<pre><code>from tkinter import *
def mstore(text):
file = open("file.txt", "w")... | python|tkinter | 0 |
5,613 | 38,904,167 | How to format the beginning a loop correctly? | <p>I have a program which I designed both for myself and my colleague to use, with all the data being stored in a directories. However, I want to set up the loop so that it work both for me and him. I tried all of these:</p>
<pre><code>file_location = glob.glob('/../*.nc')
file_location = glob('/../*.nc')
</code></pre... | <p>You can get a directory relative to a user's home (called <code>~</code> in the function call) using <a href="https://docs.python.org/2/library/os.path.html#os.path.expanduser" rel="nofollow"><code>os.path.expanduser()</code></a>. In your case, the line would be </p>
<pre><code>file_location = glob.glob(os.path.ex... | python|loops|iteration|dropbox | 4 |
5,614 | 38,638,180 | How do "is" and "id" work in Python using integers above preallocated -5, 255 range | <p>Running interpreter</p>
<pre><code>>>> x = 5000
>>> y = 5000
>>> print(x is y)
False
</code></pre>
<p>running the same in script using <code>python test.py</code> returns <code>True</code></p>
<p>What the heck?</p> | <p>The <code>is</code> operator only returns <code>True</code> when the two operands reference the exact same object. Whether the interpreter chooses to create new values or re-use existing ones is an implementation detail. CPython (the most commonly used implementation) is clearly quite happy having several different ... | python | 3 |
5,615 | 26,301,914 | WSadmin TypeError: sequence subscript must be integer or slice using AdminConfig.modify | <p>I am trying to create a script in Jython to migrate some applications from was 7 to was 8.5. After I create the Data Source I am stuck for about 2 hours with this error: <strong>TypeError: sequence subscript must be integer or slice</strong></p>
<p>The problem appear at line 25 and i have no idea how to solve it. I... | <p>I solved the problem. </p>
<p>Replace the lines 25:31 with:</p>
<pre><code>AdminConfig.modify(connectionPoolId, [["maxConnections", databaseMaxConnections], ["minConnections", databaseMinConnections], ["connectionTimeout", databaseconnTimeout], ["reapTime", databasereapTime], ["unusedTimeout", databaseunusedTimeou... | python|websphere|jython|wsadmin|ibm-was | 0 |
5,616 | 26,289,325 | Save app data in kivy on Android | <p>Say I was making a fitness app where you can make your out workout. When you have configured the workout you would want to save it. How do I add this function so that when he exits the app and opens it again, he can view his workouts?</p>
<p>I am working specifically on Android.</p>
<p>This could be used to save l... | <p>I believe Kivy has a module that deals with this. Though it is still(at the time of writing) experimental. Look here: <a href="http://kivy.org/docs/api-kivy.storage.html#module-kivy.storage" rel="noreferrer">http://kivy.org/docs/api-kivy.storage.html#module-kivy.storage</a></p>
<p>They appear to be using Pickle to ... | android|python|kivy | 5 |
5,617 | 26,082,485 | Implementing a Function as Lambda | <p>Is there any way to implement the following function as a lambda:</p>
<pre><code>def z(s,f):
for c in s:
if c in f:f.remove(c)
else:return 0
return 1
</code></pre>
<p>My biggest trouble is the <code>f.remove(c)</code>:</p>
<pre><code>z=lambda s,f:f.remove(c) if c in f else 0 for c in s;1
</code></pre>
<p>T... | <p>An equivalent <code>lambda</code>:</p>
<pre><code>lambda s, f: int(all(c in f and f.remove(c) is None for c in s))
</code></pre>
<p>This uses lazy evaluation of <code>and</code> and <code>all</code> to <code>remove</code> only the appropriate characters. </p> | python|lambda | 3 |
5,618 | 60,183,699 | Anaconda 3 installation error - no scripts folder and no conda command prompt and shortcuts | <p>I am trying to install Anaconda3-2019.10-Windows-x86_64.exe on window 8.1. During installation, I checked details and there seemed have many issues. </p>
<ul>
<li>No Scripts folder or Conda Command prompt or shortcuts were created.</li>
<li>Only conda-meta, Lib, pkgs,_conda.exe and Uninstall-Anaconda3.exe are creat... | <p>Finally, I used 64 bit preview version of installer from from <a href="https://repo.anaconda.com/pkgs/misc/previews/anaconda/2020.02/" rel="nofollow noreferrer">2020 Feb</a>. The installation was completed successfully now and everything is working fine. I suspect there is issue with 2019.10 verion which might have ... | python|anaconda | 3 |
5,619 | 1,915,342 | Python: List of lists of integers to absolute value to single number | <p>If i had a list of list of integers say:</p>
<blockquote>
<p>[['12' '-4' '66' '0'], ['23' '4' '-5'
'0'], ['23' '77' '89' '-1' '0']]</p>
</blockquote>
<p>I wanted to convert the numbers to their absolute values and then to a single number, so the output would be:</p>
<blockquote>
<p>1246602345023778910</p>
<... | <p>What you're showing is (maybe) a list of lists of strings, and the syntax is extremely peculiar -- the sublists are shown with the normal, usual commas, but inside each there are just literal strings with spaces between them. If you actually type that into Python, you'll get a list where each sublist contains a sin... | python|list|mapping|integer|absolute | 2 |
5,620 | 62,907,698 | Calculate products of columns according to combinations with replacement | <h1>The Problem</h1>
<p>It's a bit difficult to explain but I will try my best. I know the equation to find the number of combinations with replacement. Let's say I have 6 vectors: A, B, C, D, E, F. If I want to find every possible cubic product of these 6 variables, it would be (6+3-1)!/3!(6-1)! = 56 combinations (see... | <p>You can avoid confusion of indexing by using a counter:</p>
<pre><code>clear all; close all
% Original matrix
M = [
2 2 3 2 8 8;
5 1 7 9 4 4;
4 1 2 7 2 9
];
% Number of combinations
order = 3;
sizeX = nchoosek(size(M,2)+order-1,order);
% Combinations
imat = ones(sizeX,order);
for c=2:sizeX
imat(c,:) ... | python|matlab|loops|combinations|combinatorics | 1 |
5,621 | 32,499,400 | UnicodeDecodeError when altering table | <p>I'm trying to do automatic <code>alter table</code> - adding column when it is necessary. The problem is that I've started to getting <code>UnicodeDecodeError</code>. </p>
<p>I don't understand why this error is raising. Why it wants to use <code>'ascii'</code> charset.</p>
<p>I've tried to <code>print attr.__clas... | <p>To convert from unicode to bytes you use <code>encode</code>, not <code>decode</code>.</p>
<p>Alternatively, make the SQL string unicode:</p>
<pre><code>self.cur.execute(u"""ALTER TABLE data ADD COLUMN {} TEXT""".format(attr))
</code></pre> | python|unicode|encoding|utf-8|sqlite | 1 |
5,622 | 32,221,063 | Where does Python store the name binding of function closure? | <p>So recently I understand the concept of function closure.</p>
<pre><code>def outer():
somevar = []
assert "somevar" in locals() and not "somevar" in globals()
def inner():
assert "somevar" in locals() and not "somevar" in globals()
somevar.append(5)
return somevar
return inne... | <p><sup>This depends on the python implementation. I assume you mean CPython.</sup></p>
<p>The <code>__code__</code> (or <code>func_code</code>) has a <code>co_freevars</code> attribute that contains the name of all non-local variables (they are called "free vars" as if a python function was a logical formula where th... | python|closures|python-2.x|cpython | 10 |
5,623 | 32,538,195 | String formatting issue (parantheses vs underline) | <p>I got a text file containing all my data</p>
<pre><code>data = 'B:/tempfiles/bla.dat'
</code></pre>
<p>from the text file I'm listing the column header and their types with</p>
<pre><code>col_headers = [('VW_3_Avg','<f8'),('Lvl_Max(1)','<f8')]
</code></pre>
<p>Then creating a dictionary variable holding th... | <p><strong>When you have problems with <code>genfromtxt</code> the first thing you should do is print the <code>shape</code> and <code>dtype</code>.</strong></p>
<p>Why do you have to use <code>()</code> in <code>col_headers = [('VW_3_Avg','<f8'),('Lvl_Max(1)','<f8')]</code>?</p>
<p>Is it because the file has t... | python|string|python-2.7|scipy | 1 |
5,624 | 28,035,042 | getting day of years for each month in python | <p>I wanted to get the first and last day of years, i.e., range of the day of years for each month in python.</p>
<p>I tried as follows:</p>
<pre><code>import datetime, numpy as np
dates = np.arange(np.datetime64('2014-01-01'), np.datetime64('2015-01-01'))
dates = [datetime.datetime.strptime(str(x),"%Y-%m-%d") for ... | <pre><code>import calendar
from datetime import date
from dateutil.relativedelta import relativedelta
start = date(2012,1,1)
end = date(2015,1,1)
while start < end:
first_delta = (start - date(start.year, 1, 1)).days + 1
last_delta = (start + relativedelta(days=-1, months=1) - date(start.year, 1, 1... | python|numpy | 4 |
5,625 | 27,968,591 | Numpy.arrange with datetime - ValueError: negative dimensions are not allowed: | <p>I am building a date axis for a matplotlib chart that should have a tick every 7 days. I am using numpy to build the range and the interval but am receiving the error message <code>ValueError: negative dimensions are not allowed</code> I've isolated the code to the important elements </p>
<pre><code>import numpy as... | <p>With the suggestion of np.datetime64 from Paulo Scardine, I was able to successfully solve this. I am posting a solution that others might find useful:</p>
<pre><code>import numpy as np
import datetime
first_date = np.datetime64('2014-12-13')
last_date = np.datetime64('2015-01-01')
print np.arange(first_date, last... | python|python-2.7|datetime|numpy | 2 |
5,626 | 44,013,436 | 1064, "check the manual that corresponds to your MySQL server version for the right syntax to use near '%d, %d, %s | <p>I'm doing a program to get data from arduino, temperature, humidity and rain, but I can not get rain values to be filled in the database.</p>
<pre><code>try:
lluvia =data['canLluvia']
except KeyError:
lluvia=None
curs = db.cursor()
curs.execute("INSERT INTO temps(fecha,hum,temp,lluvia)valu... | <p>You have combined prepared SQL statement syntax with direct statement syntax on line 6 - and also messed with the data types. If you want to pass <code>int</code> to the database because of the database column format, you should not cast them to <code>str</code> at all and stick with <code>int</code> instead.</p>
<... | mysql-python | 0 |
5,627 | 32,955,055 | serial.Serial.readline() raises SerialException, but the same code worked a week ago | <p>I have a pair of applications that communicate by sending text (in one direction only) over a serial port. They have been working great for a while. Last week the reading side stopped working <em>on my machine</em>, and raises a <code>SerialException</code> whenever I call the <code>readline()</code> method of my ... | <p>Ubuntu 14.04 3.13.0.65 kernel breaks python serial communication. Try downgrading kernel to 3.13.0-63 and serial communication should work as before</p> | python-2.7|ubuntu|pyserial | 1 |
5,628 | 14,316,088 | thread.start_new_thread: transfer exception to main-thread | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/2829329/catch-a-threads-exception-in-the-caller-thread-in-python">Catch a thread’s exception in the caller thread in Python</a> </p>
</blockquote>
<p>I have a given code and there is a </p>
<pre><code>thread.s... | <p><strong>UPD:</strong> It is not the best solution as your question is different from what I thought it is: I expected you were trying to deal with an exception in thread code you can not modify. However, i decided not to delete the answer.</p>
<p>It's hard to catch an exception from another thread. Usually it shoul... | python | 0 |
5,629 | 13,979,422 | How do I debug a script that uses stdin with ipython? | <p>I've got a python script that takes input on stdin. I'd like to drop into IPython.embed(), like this:</p>
<pre><code>for filepath in sys.stdin:
dir = os.path.basename(filepath)
...
IPython.embed()
</code></pre>
<p>I then invoke the script like this:</p>
<pre><code>find . -type f | thescript.py
</code>... | <p>You could read your stdin input into a list first, then reset stdin:</p>
<pre><code>stdin_list = list(sys.stdin)
sys.stdin = open('/dev/tty')
for filepath in stdin_list:
dir = os.path.basename(filepath)
...
IPython.embed()
</code></pre> | python|ipython | 6 |
5,630 | 34,507,077 | use double asterisk operator in django templates | <p>I'd like to provide some extra templates for my base template to include, just like the following code:</p>
<p><em>views</em>:</p>
<pre><code>def my_view(request):
extra_templates=[
{'path': 'dashboard/timewindow.html'},
{'path': 'dashboard/search_box.html'},
]
context = {'extras': extr... | <p>First, You can not use double asterisks in <code>include</code> tag. <code>include</code> tag's <code>with</code> parameter only understands <code>foo=1</code> or <code>1 as foo</code> notations.</p>
<p>So, you have three options:</p>
<p>1) Included template will have all variables available from top level templat... | python|django | 1 |
5,631 | 34,610,275 | Package : cx_Oracle for Python 3.5, windows64 bit. Oracle 11.2.0.1.0 | <p>I am trying to install cx_Oracle on my windows PC. I ran following command in command prompt:</p>
<pre><code>pip install cx_Oracle
</code></pre>
<p>This is giving me the following error:</p>
<pre><code>Collecting cx-Oracle
Could not find a version that satisfies the requirement cx-Oracle (from versions: )
No matc... | <p>Python 3.5 binaries of cx_Oracle were made available on January 18. See here:</p>
<p><a href="https://pypi.python.org/pypi/cx_Oracle/" rel="nofollow">https://pypi.python.org/pypi/cx_Oracle/</a></p> | python|oracle|cx-oracle|python-3.5 | 2 |
5,632 | 27,028,029 | how to pass arguments to falcon.before hook? | <p>I need to authorize user based on some rols, so I need to:</p>
<pre><code>class Things:
@falcon.before(myfunc, 'can_delete_tag')
@on_get(req, resp):
...
</code></pre>
<p>but it seems impossible... Any ideas?</p> | <p>Using internal falcon hooks is impossible unless we patch the functionality of falcon. Because hooks in falcon <a href="https://github.com/racker/falcon/blob/master/falcon/hooks.py#L23" rel="nofollow">do not accept</a> any parameters at all. But a standard decorator can do that:</p>
<pre><code>def Authorize(action)... | python|falconframework | 1 |
5,633 | 41,797,830 | strange with downloading modules python 3.5 | <p>I have used miniconda and pip to download modules such as matplotlib. The modules works fine when I work in command prompt, but doesn't work when I try to import in my IDLE 3.5 version</p> | <p>It's possible that your command prompt is using a different version of Python. I know that may not be the case, but there is a difference between <code>python</code>, <code>python2</code>, <code>python3</code>, and even more changes in a <code>virtualenv</code>.</p>
<p>In your command prompt (where the module works... | python|module|download|python-idle|miniconda | 0 |
5,634 | 41,749,261 | Web crawler page iteration | <p>I have written this code that goes to webMD and so far extracts all the link from each sub category in the message boards. What I was to do next is to make the program go through all the pages of the subcategory link. I have tried many thing but I always face a problem any idea? </p>
<pre><code>import bs4 as bs
imp... | <p>I've used Python and <a href="https://en.wikipedia.org/wiki/Wget" rel="nofollow noreferrer">Wget</a> to do a similar task in the past. <a href="https://www.gnu.org/software/wget/manual/wget.html" rel="nofollow noreferrer">See Wget documentation here</a>. You can look into the source to get an idea of how it works.<... | python|web-scraping|web-crawler | 0 |
5,635 | 47,539,344 | Pact: how to set up provider states | <p>I'm looking at the <a href="https://github.com/pact-foundation/pact-python/" rel="nofollow noreferrer">Python implementation</a> of Pact and trying to set up provider states. It seems to say that the way to do it is for the provider to have an endpoint built into the service that is called to put the provider in th... | <p>As per <a href="https://github.com/pact-foundation/pact-python#provider-states" rel="nofollow noreferrer">the documentation in Pact-Python</a>, it's a bit open ended how you actually accomplish this. Personally, how I would do it for say, a node provider as I normally don't work with Python, is within my provider t... | python|pact|pact-python | 2 |
5,636 | 11,630,106 | advanced string formatting vs template strings | <p>I was wondering if there is a advantage of using <a href="http://docs.python.org/library/string.html#template-strings">template strings</a> instead of the new <a href="http://docs.python.org/library/string.html#string-formatting">advanced string formatting</a>?</p> | <p>Templates are meant to be simpler than the the usual string formatting, at the cost of expressiveness. The rationale of <a href="http://www.python.org/dev/peps/pep-0292/" rel="nofollow noreferrer">PEP 292</a> compares templates to Python's <code>%</code>-style string formatting:</p>
<blockquote>
<p>Python curren... | python|string-formatting|template-engine | 25 |
5,637 | 58,510,943 | How can I better noise addition in python? | <p>I'm trying to add a random noise from uniform distribution between min pixel
value and 0.1 times the maximum pixel value to each pixel for each channel of original image.</p>
<p>Here's my code so far:</p>
<p><strong>[in]:</strong></p>
<pre class="lang-py prettyprint-override"><code>import cv2
import numpy as np
i... | <p>You can be simplistic and add the noise by only the numpy array.</p>
<pre><code>import numpy
import matplotlib.pyplot as plt
import cv2
</code></pre>
<p>Look, plotting the image will only work good with jupyter notebooks.
Do cv2.imshow() for other IDEs.</p>
<p>1) Have your Image</p>
<pre><code>img = cv2.imread('... | python|opencv|image-processing|noise | 1 |
5,638 | 58,485,567 | Tensorflow Installing gives me an error from pip module | <p>So, as the title says, I get an error whenever I try to install TensorFlow like this:</p>
<blockquote>
<p>pip install tensorflow</p>
</blockquote>
<p>Here is the error that I get:</p>
<pre><code>> Traceback (most recent call last):
> File "c:\program files (x86)\python36-32\lib\runpy.py", line 193, in ... | <p>If you're using conda try <code>conda install -c conda-forge tensorflow</code>, I heard that Tensorflow is not great on Windows so if you're installing it just to use Keras I would suggest to install Theano instead.</p> | python|tensorflow|pip | 0 |
5,639 | 33,563,158 | python stop exception passing | <p>I have a custom <code>InvalidError</code>, and I want my function handles two kinds of errors: one is <code>InvalidError</code>, the other are all other errors. I tried in this way:</p>
<pre><code>try:
a = someFunc()
if a:
# do things
else:
raise InvalidError('Invalid Error!')
except InvalidErr... | <p>Can you tell us how you created you InvalidError class? It is working.</p>
<pre><code>class InvalidError(Exception):
pass
>>> try:
... raise InvalidError("dsfsdf")
... except InvalidError as my_exception:
... print "yes"
... except Exception as e:
... print "No"
...
yes
</code></pre> | python|error-handling|exception-handling | 0 |
5,640 | 46,779,156 | ModuleNotFoundError: No module named 'tensorflow' after installing on Mac OS | <p>I have followed the installation instruction on <a href="https://www.tensorflow.org/install/install_mac" rel="nofollow noreferrer">https://www.tensorflow.org/install/install_mac</a>
for Tensorflow virtualenv (as recommended). </p>
<pre><code>pip3 install --upgrade virtualenv
virtualenv --system-site-packages -p py... | <p>I found the reason: TensorFlow requires the Python package <strong>six</strong>, and the version included in Apple's default Python installation is too old.</p>
<p>Solution: Upgrade the Python installation with the current version of six:</p>
<pre><code>$ sudo easy_install -U six
</code></pre> | tensorflow|pip|virtualenv|macos-sierra|python-3.6 | 1 |
5,641 | 46,931,347 | Set screenshot path from default project location to different folder location | <p>I have a suite which has 50 test cases. When I execute my suite, I get all the failed screenshots listed in the project's folder. I want to point and store those screenshots to a different directory with the name of the test case. I wanted it to be a one time setup than doing it explicitly for every test cases.</p> | <p>I suggest you to do the follow:</p>
<ol>
<li>For new directory, you should put the following immediately after where you open a browser such:</li>
</ol>
<p><code>Open Browser ${URL} chrome
Set screenshot directory ${OUTPUT FILE}${/}..${/}${TEST_NAME}${/}</code></p>
<ol start="2">
<li>For replace the scr... | python-2.7|selenium-webdriver|robotframework | 1 |
5,642 | 37,901,094 | Prime number printer stops at 251, why? | <p>I started learning Python today, and I came up with the idea of creating a program that prints all the prime numbers from 0 to 10 000. I managed to make my program print out all primes until 251, at which point it stops printing out numbers. Why does it do this?</p>
<p>Here is the code:</p>
<pre><code>for numberTo... | <p>The problem is that you are using <code>is</code> instead of <code>==</code>. The <code>is</code> operator performs <em>object identity</em> comparison, which "happens to work" for all numbers below <code>256</code> due to <strong>implementation details</strong>. <code>251</code> is the biggest prime below 256 (chec... | python | 74 |
5,643 | 38,010,391 | Share python objects between two (or more) .py files | <p>I'd like to be able to run a python file (<code>file1</code>) that simply loads several large files into memory as python objects, then, with a different python file (<code>file2</code>), access those same objects without having to reload the files into memory a second time. <em>The motivation is that I want to be a... | <p>Objects do not belong to a specific file. The class they belong to or the function that generates them may have been out of a module that "physically" resides in a different file, but this doesn't matter. As long as you are in a single python interpreter session objects will not need to be copied.</p>
<p>There is o... | python|memory|memory-management | 4 |
5,644 | 27,752,755 | How can I get the values from two list a time | <p>I have two Lists: one contains filenames and the other timestamps for the corresponding file name.</p>
<p>This is my code:</p>
<pre><code>for afile in filelist:
for times in timestamps:
self.importFiles(afile,times)
</code></pre>
<p>But this code will call the function prints different timestamp for s... | <p>Pythonic way, using <a href="https://docs.python.org/2/library/functions.html#zip" rel="nofollow">zip</a> function:</p>
<pre><code>for afile, timestamp in zip(filelist, timestamps):
self.importFiles(afile,timestamp)
</code></pre> | python|list|function|parameter-passing | 2 |
5,645 | 65,666,207 | drop column with empty name | <p>I have a dataframe with empty column name <code>df.info()</code>:</p>
<pre><code> # Column Non-Null Count Dtype
--- ------ -------------- -----
0 Timestamp 11586 non-null object
1 Email address 11586 non-null object
2 11586 non-null object
3 Score ... | <p>You can use this:</p>
<pre><code>df = df[[x for x in df.columns if len(x)>=1]]
</code></pre>
<p>This approach does not care in which index the empty name is, it just takes every column that has a length of at least 1 or more.</p> | python|pandas|dataframe | 2 |
5,646 | 65,784,075 | This is a simple Python question for list | <p>Im trying to take in user input to get a list of numbers and then use a for loop to grab the largest value. For what I have now I can use 8237483294 but It will list each integer as its own independent value and will have its own place in the list so it would be [8,2,3,7,4,8,3,2,9,4] Which was an A+ for what I wante... | <p>Use <a href="https://www.w3schools.com/python/ref_string_split.asp" rel="nofollow noreferrer"><code>string.split()</code></a>.</p>
<pre class="lang-py prettyprint-override"><code>#Get user input
# (no need for the two variables you used in your example)
numbers = input("List numbers separated by spaces").... | python-3.x | 3 |
5,647 | 72,468,387 | Creating a conda environment with python 3.8 with conflicting requirement(s)? | <h2>Context</h2>
<p>After setting up a conda <code>environment.yml</code> and trying to install it with a <code>python 3.8</code> version, I am experiencing some difficulties.</p>
<h2>Attempts</h2>
<p>I tried explicitly specifying the python version at the environment creation command:</p>
<pre><code>conda env create -... | <p>After specifying the python version as the first dependency, and removing the unneeded elements as suggested by merv, I found a working yaml. I removed <code>anaconda</code>, and the <code>conda</code> channel. Furthermore, I ensured the <code>default_version</code> in the <code>.pre-commit-config.yaml</code> file w... | python|anaconda|conda|miniconda | 1 |
5,648 | 72,174,950 | proper input and output shape of a keras Sequential model | <p>I am trying to run a <a href="https://keras.io/" rel="nofollow noreferrer">Keras</a> sequential model but can't get the right shape for the model to train on.</p>
<p>I reshaped <code>x</code> and <code>y</code> to:</p>
<pre><code>x = x.reshape(len(x), 500)
y = y.reshape(len(y), 500)
</code></pre>
<p>Currently, both ... | <p>LSTM layer expects input shape as [batch, timesteps, feature]. So, with the shape (9766, 1, 500), you have one timestep with 500 features. If you have 500 timesteps, your shape should be like <code>(9766, 500, 1)</code>.</p>
<p>Here is an example architecture:</p>
<pre><code>x = tf.random.uniform((9766,500,1))
y = t... | python|numpy|tensorflow|keras|data-science | 1 |
5,649 | 43,169,417 | scp in a nested ssh session in python's paramiko | <p>Basically, I have an issue with performing an scp over a nested SSH ssh session in Python. I used <code>paramiko</code> to establish an SSH from my local machine to another server, let's call this <strong>A</strong> and from <strong>A</strong>. I want to scp a file, let's call it <strong>f</strong> to a server <stro... | <p>Are you running this in PyCharm? At what point does it fail, and are you getting any errors? It could be that the string in </p>
<pre><code>buff.endswith('\'s password: '):
</code></pre>
<p>doesn't exactly match what's being outputted in the ssh session. Other than that it looks correct. I would recommend breakpo... | python|ssh|paramiko|scp|channel | 0 |
5,650 | 43,213,344 | Python difflib for 2 files, with incorrect line numbers | <p>I have to compare 2 files in Python and I am using <a href="https://docs.python.org/2/library/difflib.html" rel="nofollow noreferrer">difflib</a>. I tried this separately with <a href="https://docs.python.org/2/library/difflib.html#difflib.ndiff" rel="nofollow noreferrer">ndiff</a> and then with <a href="https://doc... | <p>The documentation for <a href="https://docs.python.org/2/library/difflib.html#difflib.unified_diff" rel="nofollow noreferrer"><strong><code>unified_diff</code></strong></a> says it takes a parameter <code>n</code>:</p>
<blockquote>
<p>Unified diffs are a compact way of showing just the lines that have changed plu... | python|python-2.7|difflib | 1 |
5,651 | 43,174,813 | Extract data from list with some conditions | <p>Basically, I am trying to adding two midi files and there is not much information on internet about it, so I am trying my own.</p>
<p>What I did so far is I have added two midi's messages (type of midi's data)
and I have list of both midi messages. This means I have all the data in which I need to merge two midi no... | <pre><code>from mido import MidiFile, MidiTrack
mid = MidiFile('har.mid')
mid2 = MidiFile('har2.mid')
l = [msg for track in mid.tracks for msg in track]
l.pop()
ka = [msg for track in mid2.tracks for msg in track]
ka.pop()
result = l + ka
mid3 = MidiFile()
track = MidiTrack()
mid3.tracks.append(track)
for m in res... | python|list|python-3.x|machine-learning|extract | 2 |
5,652 | 43,236,952 | Dynamically nesting a list, and related comprehension/mapping to find indices of string match | <p>The context of what I'm doing: I'm translating if/then/else statements between 2 languages via a Python script (2x for now, but may eventually upgrade to 3x). I have a function that takes the if/then/else statement from the original language and breaks it into a list of [if_clause,then_clause,else_clause]. The thing... | <p>If I understand correctly, you could call your function recursively.</p>
<pre><code>def split_if_then_else(str):
if check_if_if_in_string_function(str)
if_clause, then_clause, else_clause = split_str_core_function(str)
then_clause = split_if_then_else(str)
return [if_clause, then_clause,... | python|python-2.7 | 0 |
5,653 | 37,096,152 | understanding file handle and csv reader for python | <p>Can someone help me understand the behavior when we use csv.reader - Apparently in the second instance of csv.reader within same function handle seems to be coming out empty. Can someone please explain me operation/reason ?</p>
<pre><code>def getAllCategories(self, file):
csvread = csv.reader(file, delimiter=',... | <p>The contents of <code>file</code> are already consumed by the first reader. Once <code>csvread</code> reads all the rows it moves the file pointer to the end of file thus there's nothing left to read for second reader.</p>
<p>You could use <a href="https://docs.python.org/2/library/stdtypes.html#file.seek" rel="nof... | python|csv | 1 |
5,654 | 48,847,518 | Run an autocorrect program on a text file on python | <p>I am very new to Python, and I am currently working on a project. This project would be to create (among other things) a program to correct a text. I am having difficulty combining two separate ideas and parts of code together. First of all, I have been experimenting with a code to correct a word that is inputted by... | <p>Maybe you should look at this:
<a href="https://norvig.com/spell-correct.html" rel="nofollow noreferrer">https://norvig.com/spell-correct.html</a></p>
<p>It uses probability to give the best answer without being connected to a database.</p>
<p>Else, you can use urllib to connect to the english dictionary website: ... | python | 0 |
5,655 | 48,698,766 | null value in column "user_id" violates not-null constraint | <p>I am working on a RSVP project based on Django. When I want to make a Event model and connect it with every user. It always has this error! Event just has two fields: <code>user</code> and <code>name</code>. </p>
<p><code>views.py</code>:</p>
<pre><code>def create_event(request):
if request.method=='POST':
... | <pre><code>def create_event(request):
if request.method=='POST':
form = CreateEventForm(data=request.POST)
if form.is_valid():
... | python|django | 1 |
5,656 | 48,237,795 | print headers with my dataframe | <h1>how do I print my dataframe in such format given below?</h1>
<pre><code>Age Count
25-29 16
<25 16
30-35 16
>35 16
Name: Age, dtype: int64
Press any key to continue . . .
</code></pre>
<blockquote>
<p>My Output does not have the headers and here is my code</p>
</blockquote>
<pre><code... | <p>You need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.rename_axis.html" rel="nofollow noreferrer"><code>rename_axis</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.reset_index.html" rel="nofollow noreferrer"><code>reset_index</code></a>:... | python|pandas | 2 |
5,657 | 48,229,519 | Alpha Vantage API Define Proxy Python | <p>I am using Alpha Vantage API and python. I was able to successfully install alpha vantage on my machine. Unfortunately I am working in a corporate environment where I have to define a proxy. So this line of code works perfectly fine for me:</p>
<pre><code>from alpha_vantage.timeseries import TimesSeries
</code></pr... | <p>You can specify proxies using </p>
<pre><code>proxies = {
'http': 'http://user:pass@10.10.1.0:3128',
'https': 'http://user:pass@10.10.1.0:3128',
}
ts = TimeSeries(key='your_key')
ts.set_proxy(proxies)
</code></pre> | python|proxy|alpha-vantage | 1 |
5,658 | 51,221,094 | QRadioButtons widget are linked on uniqueness | <p>I have built a GUI window that is part of a project, and I need to have three separate groups of radio-buttons, each group must be independent in the uniqueness. I can't find the way how to separate the linkage between the radio-buttons. So only one can be checked, and all the others are automatically unchecked.</p>... | <p>The solution as you indicated is to use QButtonGroup, the problem is that your QButtonGroups is a local variable that will be eliminated when you finish executing the function, the solution is to pass a parent to the QButtonGroups so it will extend its scope.</p>
<pre><code>...
direction_group = QtWidgets.QButtonGr... | python|pyqt|pyqt5|qradiobutton | 1 |
5,659 | 70,703,342 | How to use aws boto3 put_object to stream download/upload | <p>I use <code>put_object</code> to copy from s3 bucket to another cross-region, cross-partition. The problem is the file sizes have become more unpredictable and since <code>get_object</code> stores to memory, I end up giving it more resource than it needs most of the time.</p>
<p>Ideally I want to "stream" ... | <p>I had the same problem recently, and the answer from <a href="https://stackoverflow.com/questions/7624900/how-can-i-use-boto-to-stream-a-file-out-of-amazon-s3-to-rackspace-cloudfiles">smallo</a> on this question helped me to find a solution! So all credits to him!</p>
<p>But basically, you can use the method <code>r... | python|amazon-web-services|amazon-s3|boto3 | 2 |
5,660 | 70,413,008 | splitting two lists in chunks in unison in python | <p>I have to two lists X and Y of same length. I want to split the two lists in unison of chunks of length 2000. List X and Y each are of length 3671460. So for example:</p>
<pre><code>#input
X = [1,2,3,4,5]
Y = [0,1,0,1,1]
#Expected output
X = [[1,2],[3,4],[5]]
Y = [[0,1],[0,1],[1]]
</code></pre>
<p>The example ofco... | <p>what about this?</p>
<pre><code>a = [1, 2, 3, 4, 5]
b = [a[x:x+2] for x in range(0, len(a), 2)]
</code></pre>
<p>2 might be 2000 in your case.</p> | python-3.x|list|deep-learning | 1 |
5,661 | 70,520,807 | Join dataframes matching a column with a range determined by two columns in the other one with PySpark | <p>I have a df on the left like this one:</p>
<pre><code>+----+-----+
| id|value|
+----+-----+
| 2| xx|
| 4| xx|
| 11| xx|
| 14| xx|
| 27| xx|
| 28| xx|
| 56| xx|
| 55| xx|
+----+-----+
</code></pre>
<p>And another one on the right like this one:</p>
<pre><code>+-----+---+----+
|start|end| ov... | <p>Use <code>between</code> operator with <strong><code>left join</code></strong>.</p>
<p><strong><code>Example:</code></strong></p>
<pre><code>#using dataframes api
df.join(df1,(df['id'] >= df1['start']) & (df['id'] <= df1['end']),'left').select(df["*"],df1['ov']).show(10,False)
#using spark sql ... | python|pyspark | 0 |
5,662 | 69,800,351 | How to check for string and get the string before after checking | <p>If I have a string "3 apples" or "3apples" and do a check like:</p>
<pre><code>fruit = "3 apples"
if fruit.find('apples') > -1:
</code></pre>
<p>How can i get the number 3 before apple if the statement is true?</p> | <p>Using <code>str.split</code> <em>(assuming the string supplied is in form: <code>'int(s) apples'</code> or <code>'int(s)apples'</code>)</em>:</p>
<pre><code>fruit = "3 apples"
try:
num, word = fruit.split()
except ValueError:
num = ''.join(filter(str.isdigit, fruit))
word = ''.join(filter(str.... | python|python-3.x|string | 1 |
5,663 | 69,804,602 | Identify magnitude of each spectrum obtained through spectogram in Python | <p>I am currently plotting a specgram using python matplotlib as shown below:
Pxx, freqs, bins, im=ax.specgram(data, NFFT=1024, Fs=fs, mode='psd', cmap='plasma',sides='twosided')
I am to generate a waterfall plot using this with varying magnitude:
<a href="https://i.stack.imgur.com/CWKvT.png" rel="nofollow noreferrer">... | <p>You can try to apply peak detection to each frame of your NFFT data by looping. <a href="https://github.com/MonsieurV/py-findpeaks#scipysignalfind_peaks" rel="nofollow noreferrer">Scipy</a> has the algorithm for peak detection. Or you can use a simple baseline parameter for the yellow part value to compare if the co... | python|signal-processing|spectrogram|waterfall | 1 |
5,664 | 55,903,786 | Dash: Creating a dropdown per column, instead of a dropdown per table | <p>I have a data set that looks like this:</p>
<pre><code>cat_id author year publisher country value (dollars)
name1 kunga 1998 D and D Australia 10
name2 siba 2001 D and D UK 20
name3 siba 2001 D and D US 20
name3 shevara 2001 D and D UK 10
name3 dougherty 1992 D and D A... | <p>Thanks, Kela, for making this question a little more specific. This still a good size bite, so I'll see if I can help with all of it.</p>
<p>First thing is you need to change the column defintion in the table to have <code>'presentation': 'dropdown'</code> in the dictionary for each column you want to show up as a ... | python|plotly-dash|plotly-python | 0 |
5,665 | 49,936,190 | Adding two dictionaries in a RDD in Pyspark | <p>I have created and RDD where every element is a dictionary. (This is a sample. There are 30,000 keys</p>
<pre><code>rdd.take(2)
[{'actor': 'brad',
'good': 1,
'bad': 0,
'average': 0,}
{'actor': 'tom',
'good': 0,
'bad': 1,
'average': 1,}]
</code></pre>
<p>I am trying to perform arithmetic operations on... | <p>It will be a faster solution if you convert the RDD to Spark DF and groupby the key to sum up the values:</p>
<pre><code>from pyspark import SQLContext, SparkContext
sc = SparkContext()
sql = SQLContext(sc)
a = [{'actor': 'brad', 'good': 1, 'bad': 0, 'average': 0,}, {'actor': 'tom','good': 0, 'bad': 1, 'average': ... | python|apache-spark|optimization|pyspark|rdd | 1 |
5,666 | 66,615,420 | Dataframe List Pandas | <p>Good morning,</p>
<p>I have the following List.</p>
<p>[ Unnamed: 0 R$/m3 Var./Dia Var./Mês
0 12/03/2021 2.9820 -0,03% 3,38%
1 11/03/2021 2.9830 -0,10% 3,41%
2 10/03/2021 2.9860 0,29% 3,52%
3 09/03/2021 2.9775 -0,02% 3,22%
4 08/03/2021 2.9780 0,25% 3,24%
5 05/03/2021 ... | <pre><code>import pandas as pd
esalq_dia = pd.read_html('https://www.cepea.esalq.usp.br/br/indicador/etanol-diario-paulinia.aspx')
esalq_dia[0]
</code></pre> | python|pandas|dataframe | 2 |
5,667 | 64,113,933 | convert python function to pyspark lambda function | <p>I have a python function like below</p>
<pre><code>def func(a, b, c):
if c != 0:
return b/c * a
else:
return a
</code></pre>
<p>I wanted to create a lambda function for this I have tried creating a lambda function like below</p>
<pre><code> func = lambda x,y,z : y/z * x if z != 0 else z
</cod... | <p>You are calling your <code>lambda</code> function wrong.</p>
<p>You pass it 3 string rather then numeric variables, you should pass the values of <code>x</code>/<code>y</code>/<code>z</code> rather then calling the the strings. You should probably do the following:</p>
<pre><code>df= df.withColumn('new_col' ,func($'... | python|dataframe|lambda|pyspark | 1 |
5,668 | 53,215,921 | Can Connect to Database via Command Line but not in Python Script? | <p>I hope the title is pretty self explanatory. I set up a database and web-server on the same machine using Amazon RDS and EC2 instance. I am running a Python script in the machine's <code>cgi</code> folder, and am having trouble connecting to the database. The errors are on the order of: <code>_mysql_exceptions.Opera... | <p>The RDS instance is not running on the EC2 instance, they're separate "machines". From the EC2 instance, instead of using the loopback address <code>127.0.0.1</code>, which would assume MySQL is running on the local EC2 instance, just use the host name <code>edutechfinal.cqk0lckbky4e.us-east-2.rds.amazonaws.com</cod... | python|mysql|amazon-ec2|amazon-rds | 1 |
5,669 | 65,160,129 | Retrieve data from postgresql in fastest way using python | <p>I have the following code:</p>
<pre><code>list1=[]
flatList_val=['user1','user2','user3','user4',......]
for val in flatList_val:
#count=flatList.count(val)
query="select count(title) as count from Data where authors like '%"+val+"%'"
luk=getValues("",query)
list1.append... | <p>I have solved it using pandas dataframe actually.Please find the solution below:
Instead of querying each time,I queried all the information and stored in dataframe</p>
<pre><code>
query="select authors from Data"
luk=getValues("",query)
for val in flatList_val:
... | python-3.x|postgresql | 0 |
5,670 | 72,113,541 | Utility of wrapping tensor in Variable with requires_grad=False in legacy PyTorch | <p>I'm using a codebase that was written in 2017/18 and I found the following code:</p>
<pre class="lang-py prettyprint-override"><code>audio_norm = audio_norm.unsqueeze(0)
audio_norm = torch.autograd.Variable(audio_norm, requires_grad=False)
</code></pre>
<p>I am aware that wrapping tensors in <code>Variable</code> fo... | <p>you are looking for</p>
<pre><code>audio_norm = audio_norm.unsqueeze(0)
audio_norm = torch.tensor(audio_norm)
</code></pre>
<p>if you need it to require grad then</p>
<pre><code>audio_norm = torch.tensor(audio_norm, require_grad=True)
</code></pre> | python|deep-learning|neural-network|pytorch | 1 |
5,671 | 71,208,714 | Spatial analysis to find nearby public transit options given a longitude/latitude and radius? | <p>I recently used foursquare's API to get a list of venues nearby a given region, and it looks like it's returned mostly commercial businesses like restaurants, pubs, gyms, and cafes.</p>
<p>I was wondering if it were possible to add "public transit" to the list, for instance, the number of bus stops nearby.... | <p>I would try OpenStreetMap.</p>
<p>If you are using default base layer in this Folium map, it comes from OpenStreetMaps data too, so you should get exactly the bus stops you see here.</p> | python-3.x|gis|geospatial|foursquare|folium | 1 |
5,672 | 70,112,298 | How do I read a text file line by line and return two strings and a list from the contents of the file? | <p>Because I want to read the text file into strings and a list at the same time, I'm stuck as to how to go about it. I'm trying using for loops and setting conditions but I'm still not sure. The text file content is:</p>
<p>Highest Goal Scorers 2018</p>
<p>Country</p>
<p>Australia, 529</p>
<p>Jamaica, 466</p>
<p>Engla... | <p>Try this:</p>
<pre><code>with open('file.txt') as f:
content = [line for line in f.readlines() if line != '\n']
first_line = content[0].rstrip('\n')
second_line = content[1].rstrip('\n')
other_lines = [line for line in content[2:]]
</code></pre> | python|string|list|file|text | 0 |
5,673 | 59,175,677 | How to send and receive with Python and socket? | <p>I want to send to a server that his a raspberry pi and a client that works on Windows. The problem is that the client can connect, but after that, it only sends the message when I close the socket. Going further maybe the cause can be that I use portforwarding.</p>
<p><a href="https://i.stack.imgur.com/ScxsD.png" r... | <p>Sorry, but I don't see that problem what you talking about.</p>
<p>Client code:</p>
<pre><code>user_tab = input("What do you want to send?")
data = (str(user_tab))
print(data)
data = data.encode("utf-8")
socket.sendall(data)
print("send all")
user_tab = input("something else?")
d=socket.recv(1024)
socket.close()... | python|sockets | 0 |
5,674 | 63,094,662 | I am trying to pass a global variable through py files. Is this correct? | <pre><code>def mods(*arg):
global mlist
if not arg:
mlist = [module for module in sorted(globals())]
return( [module for module in enumerate(mlist)])
#easily delete by indices instead of typing out module name
# i.e mods(18,19,20,21,22) deletes all those items quickly
... | <p>Assign the function's return value to a module level variable.</p>
<pre><code>#pyfile2.py
from pyfile1 import *
mlist = mods() # works
mlist , *stuff= mods("tensorflow") works
mlist, *stuff = mods(1,2,18,20) # having hard time coding this part
</code></pre> | python|function | 1 |
5,675 | 63,114,523 | python3 socket send recev 'bytes' object has no attribute 'read' | <p>I have two files: <strong>client.py</strong> and <strong>server.py</strong> that when run are connected by socket.<br />
When I send a command to the client from the server, for example a simple <code>ls</code>, I use a function (in the client) called <code>subprocess.Popen</code> to execute it in the shell. However... | <pre><code> args = shlex.split(datos)
</code></pre>
<p>datos is of type <code>bytes</code>, but <code>shlex.split</code> expects a <code>str</code>.</p>
<pre><code> args = shlex.split(datos.encode())
</code></pre> | python|sockets|subprocess|send | 0 |
5,676 | 62,205,768 | [python]I want an image to be sent as a retweet on twitter via tweepy, when the bot is tagged | <p>I want an image to be sent as a retweet on Twitter via Tweepy, when the bot is tagged, but I've hit a wall and can not figure out why. It is detecting the image in the external file, but not using it. I know it's a bit vague, but the documentation on Tweepy is a pain for me to understand, as I just picked up Tweepy ... | <p>It's not clear to me what the exact error you're seeing is, but I think you're saying that the image file is read, and the Tweet is sent, but the media is not attached?</p>
<p><code>api.media_upload()</code> returns a <code>Media</code> object, which will have its own values. You need to pass the <code>media.media_... | python|twitter|tweepy | 0 |
5,677 | 58,650,039 | Is there a way to append multiple items of the same value to a list from a dictionary without using another for loop? | <p>I have a dictionary of 'event' names (key) and multiplicities (value) for distributions. I want to convert this dictionary into a list to reduce run time to use binary search. I do not want to add another for loop as I feel like that will increase my run time.</p>
<p>I have tried looping through my dictionary and... | <p>You want the <code>list.extend</code> method.</p>
<pre><code>>>> mydict = {'a':5, 'b':7, 'c':10, 'd':2}
>>> myrichard = []
>>> for x,y in mydict.items():
... myrichard.extend(x * y)
...
>>> myrichard
['a', 'a', 'a', 'a', 'a', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'c', 'c', 'c', ... | python-3.x | 0 |
5,678 | 31,362,716 | OpenERP - OpenChatter and track_visibility fields datetime | <p>I understand that with 'track_visibility' can generate a kind of log of changes in value, this works very well, but I've found problems with my time zone and datetime fields; as the value showing me is the UTC-0 and my time zone is UTC-5.</p>
<pre><code>an Example
2015-17-31 18:25:42 → 2015-17-31 19:25:42
In OpenC... | <p>You no need to override that method. You can handle with simple this trick.</p>
<p>On <em>datetime</em> field add below attribute on <em>.py side</em></p>
<pre><code>track_visibility='always'
</code></pre>
<p>With this attribute will post a chatter log whenever field is change it's value. </p> | python|openerp|utc|openerp-7 | 1 |
5,679 | 49,058,913 | Interleaving multiple TensorFlow datasets together | <p>The current TensorFlow dataset interleave functionality is basically a interleaved flat-map taking as input a single dataset. Given the current API, what's the best way to interleave multiple datasets together? Say they have already been constructed and I have a list of them. I want to produce elements from them alt... | <p><strong>EDIT 2:</strong> See <code>tf.contrib.data.choose_from_datasets</code>. It performs deterministic dataset interleaving.</p>
<p><strong>EDIT:</strong> See <code>tf.contrib.data.sample_from_datasets</code>. Even though it performs random sampling I guess it can be useful.</p>
<hr>
<p>Even though this is not... | tensorflow|tensorflow-datasets | 11 |
5,680 | 25,009,688 | Grouping the arguments in argument parser | <p>I have a script named Myscript.py which accept following arguments</p>
<pre><code> parser = argparse.ArgumentParser("MyParams")
parser.add_argument('-a', '--info', dest='info', help='info help', required=True)
parser.add_argument('-b', '--config', dest='config', help='config help', required=True)
p... | <p>I'm not really sure that this is an easy thing to do with <code>argparse</code> -- either an option is required, or it isn't. You can't toggle it based on what else is there.</p>
<p>You can <a href="https://docs.python.org/dev/library/argparse.html#mutual-exclusion" rel="nofollow">add_mutually_exclusive_group</a> ... | python | 1 |
5,681 | 70,868,233 | Django Model: ForeignKey and Relations | <p>I have 2 models:</p>
<pre><code>class Post(models.Model):
pass
class Vote(models.Model):
post = models.ForeignKey(Post)
user = models.ForeignKey(django.contrib.auth.models.User)
</code></pre>
<p>I want to allow logged User to make a vote on Post's Admin site. I think about 2 solution as below:</p>
<o... | <p>On your <code>PostAdmin</code> class you can add an action:</p>
<pre><code>class PostAdmin(admin.ModelAdmin):
...
actions = [vote_on_post,]
</code></pre>
<p>and then you can implement the <code>vote_on_post</code> method based on <a href="https://docs.djangoproject.com/en/4.0/ref/contrib/admin/actions/#addi... | python|django | 1 |
5,682 | 71,027,144 | Is there a way to return one specific table from a webpage that has multiple tables in Python? | <p>I'm having trouble returning one particular table (the one titled 'BRN Substantial Shareholders') from this webpage - <a href="https://www.intelligentinvestor.com.au/shares/asx-brn/brainchip-holdings-ltd" rel="nofollow noreferrer">https://www.intelligentinvestor.com.au/shares/asx-brn/brainchip-holdings-ltd</a></p>
<... | <p>To <em>only</em> scrape the table with the words <em>"BRN Substantial Shareholders"</em>, you can use a CSS selector to locate that table with:</p>
<pre><code>table = soup.select_one("div:nth-of-type(11) table")
</code></pre> | python|beautifulsoup | 0 |
5,683 | 67,984,250 | execute multiple variable functions(var_1,var_2,var_3) | <p>I got another little question...</p>
<p>I want to make multiple variables which I create with 'setattr'</p>
<p>That works quite fine. It creates these variables:</p>
<pre><code>self.sectionButton_1 = Button(text=x)
self.sectionButton_2 = Button(text=x)
self.sectionButton_3 = Button(text=x)
</code></pre>
<p>Now I wan... | <p>If you have a group of related variables of the same type and you're doing the same operations to each one then that's a natural place to switch to using a list instead of individual variables.</p>
<p>Your code would become more like:</p>
<pre><code>self.sectionButtons = []
for i, x in enumerate(self.sections):
... | python|for-loop|tkinter | 1 |
5,684 | 56,165,603 | Extracting duplicate trips from a list of lists of Bus bookings | <p>I am using a csv file extracted from a database of bus records. I want to find and save all the records which correspond to a same user, identified by the same deviceID,from the huge list. There are about 300000 deviceID, with around 3 trips per device. So I want to generate a file that allows given a deviceID, find... | <p>You could use a <a href="https://docs.python.org/3/library/collections.html#collections.defaultdict" rel="nofollow noreferrer">defaultdict</a> to collect the rows for each device id in a list, with the device id as the key.</p>
<p>Something like this ought to work:</p>
<pre><code>import collections
devicedict = c... | python|list|csv | 1 |
5,685 | 57,725,818 | How to extract text from <span> nested in <li> which is nested in <ul> using BeautifulSoup? | <p>I wanna extract <strong>Here’s what’s new</strong> section's items from <a href="https://www.amazon.com/gp/help/customer/display.html/ref=hp_left_v4_sib?ie=UTF8&nodeId=G54HPVAW86CHYHKS" rel="nofollow noreferrer">this page</a>, starting with <em>In the coming weeks</em> and ending with <em>general enhancements</e... | <p>With bs4 4.7.1+ you can use :contains and :has to isolate</p>
<pre><code>import requests
from bs4 import BeautifulSoup as bs
r = requests.get('https://www.amazon.com/gp/help/customer/display.html/ref=hp_left_v4_sib?ie=UTF8&nodeId=G54HPVAW86CHYHKS')
soup = bs(r.content, 'lxml')
text = [i.text.strip() for i in s... | python|html|web-scraping|beautifulsoup | 3 |
5,686 | 54,136,969 | Merge two DataFrame but update the original columns | <p>I would like to merge two dataframes on 'key'. When the right contains the same key as left I would like left to update with what's in right's matching column ('A' column).</p>
<pre><code>left = pd.DataFrame({'key': ['K0', 'K1', 'K2', 'K3'], 'A': ['A0', 'A1', 'A2', 'A3']})
right = pd.DataFrame({'key': ['K0', 'K2'],... | <p>One painless way is using <code>update</code>:</p>
<pre><code>u = left.set_index('key')
u.update(right.set_index('key'))
</code></pre>
<p></p>
<pre><code>u.reset_index()
key A
0 K0 new
1 K1 A1
2 K2 new
3 K3 A3
</code></pre>
<hr>
<p>If the "key" column is unique, you can also <code>concat</code> ... | python|pandas|dataframe | 1 |
5,687 | 53,899,989 | Pagmo2 Pygmo2 warm start capablities | <p>I am experimenting with <a href="https://esa.github.io/pagmo2/" rel="nofollow noreferrer">Pygmo</a> and find it very convenient for setting up global optimization tasks. However, it would be great to have more CPU cores (>32) which I do not have on my computer. I would like to keep everything as cost efficient as po... | <p>All objects in pagmo can be serialized, the archipelago too. In python via pickle / dill, in c++ using the boost::serialization library. The method you found, i.e. <code>archipelago::save</code> implements the serialization of the object pagmo::archipelago following the API of the boost library. </p>
<pre><code> ... | python|pygmo | 2 |
5,688 | 45,539,241 | openpyxl - Unable to access excel file with openpyxl when it is open but works fine when it is closed | <p>I've been making this python script with openpyxl on a MAC. I was able to have an open excel workbook, modify something on it, save it, keep it open and run the script.</p>
<p>When I switched to windows 10, it seems that I can't modify it, save it, keep it open, and run the script. I keep getting an [ERRNO 13] Per... | <p>Windows does not let you modify open Excel files in another program -- only Excel may modify open Excel files. You must close the file before modifying it with the script. (This is one nice thing about *nix systems.)</p> | python|excel|openpyxl | 6 |
5,689 | 28,763,830 | JavaScript value has quotations that are breaking the code | <p>I am programming a football mashup application in google app engine and i'm having some trouble with specific videos when JwPlayer is trying to use them due to the title having either " or ' in.</p>
<p>I basically have this in JavaScript</p>
<pre><code>{image: "{{y.thumbnail.hqDefault}}", file: "{{y.player.default... | <p>Try the templatetag |escape (<a href="https://docs.djangoproject.com/en/1.7/ref/templates/builtins/#std:templatefilter-escape" rel="nofollow">https://docs.djangoproject.com/en/1.7/ref/templates/builtins/#std:templatefilter-escape</a>)</p>
<pre><code>{image: "{{y.thumbnail.hqDefault|escape}}", file: "{{y.player.defa... | javascript|python | 0 |
5,690 | 20,399,691 | ctypes - call library function passing a struct resulted from an other library call | <p>A shared-library function results a struct that I try to pass to a second function from the same lib:</p>
<pre><code>struct rohc_comp* rohc_alloc_compressor(int a, int b, int c, int d)
void rohc_activate_profile( struct rohc_comp * comp, int p )
</code></pre>
<p>I don't want to manipulate the struct in my python ... | <p>Handle it as a <code>void *</code>, i.e. set </p>
<pre><code>librc.rohc_alloc_compressor.restype = c_void_p
librc.rohc_activate_profile.argtypes = [c_void_p, c_int]
</code></pre> | python|ctypes | 1 |
5,691 | 46,571,594 | how to convert date to other format with special chars | <p>I'd like to convert date to such format:</p>
<blockquote>
<p>2017%2C01%2C02</p>
</blockquote>
<p>was trying to do this using:</p>
<pre><code>date.strftime('%Y%2Cm%2Cd')
</code></pre>
<p>But is doesn't work.</p>
<p>Can anyone explain what I am doing wrong and how to solve it ?</p>
<p>Thanks,</p> | <p>In order for <code>strftime</code> to print % as a literal string, you need to escape it by doing <code>%%</code>. You also need to add another <code>%</code> in front of <code>m</code> and <code>d</code> like you did with Year, if you want them to be replaced by actual month and dates. </p>
<p>This <a href="https... | python|python-2.7 | 1 |
5,692 | 54,989,478 | Python convert list to string in the dataframe | <p>I have bunch of list and string like texts in the cell value of the pandas data frame. I am trying to convert list to string, I am able to convert list to string, but its splitting the string as well. How do I only apply this logic if the cell contains list [] in the particular column?</p>
<pre><code>raw_data = {'N... | <p>You could use a <a href="https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions" rel="nofollow noreferrer">list comprehension</a> to generate a new list with the rows in <code>id</code> joining those entries that are lists using <a href="https://docs.python.org/2/library/string.html" rel="nofollo... | python|pandas | 2 |
5,693 | 52,231,108 | Get classification score of hypothetical detection box | <p>Is there anyway to assert the presence of a detection box in an image and obtain the classification score of said hypothetical box? </p>
<p>I am working with a tensorflow object detection graph and want to refine it's accuracy with a little trickery; by making the claim that there are more (N) objects in a given im... | <p>With tensorflow you cannot do that. What you are saying is almost like a region proposal and rest of the pipeline on which different platforms like tensorflow, yolo are built to arrive at object detection. You are proposing to a built a different platform by asking what you are asking.</p> | python|tensorflow|deep-learning | 0 |
5,694 | 27,066,721 | LIBSVM (nonlinear regression with e-svr using linear kernel) | <p>In what cases is libsvm supposed to returned [nan] as the predicted values of nonlinear regression (with e-svr using linear kernel)?</p>
<p>Is there a faq available ?</p>
<p>btw.</p>
<p>My inputs are not nan, but the std.dev of some of my feature columns are nan. Although when i remove this features nothing seems... | <p>From the faq (<a href="http://www.csie.ntu.edu.tw/~cjlin/libsvm/faq.html" rel="nofollow">http://www.csie.ntu.edu.tw/~cjlin/libsvm/faq.html</a>)</p>
<p>Q: Why the code gives NaN (not a number) results?</p>
<p>This rarely happens, but few users reported the problem. It seems that their computers for training libsvm ... | python|regression|nan|libsvm | 0 |
5,695 | 48,122,916 | JSON to Python objects | <p>I am deliberating about how to transfer the complex information from a JSON API response to (several) Python objects. I have included the (lengthy) model response below. Note that some values are not always included in the response, and some values are a list of dictionaries.</p>
<p>Is there an "easy" way to map th... | <p>Python provides a <code>json</code> module, from which you can "load" the data from JSON to Python. In this example, if <code>response</code> is a variable representing your big blob of JSON, you can do:</p>
<pre><code>import json
py_object_collection = json.loads(response)
</code></pre>
<p>If this does not work f... | python|json|api|class|object | 3 |
5,696 | 55,697,055 | Creating a program that returns a score by using a key on a list | <p>I'm basically trying to read a txt file, remove all symbols and punctuation that isn't in the alphabet (A-Z), and then produce an output that lists out all the words in the file with a score side by side. In order to get the score I'm trying to compare each letter of the word to a key. This key represents how much t... | <p>Does the punctuation have to be removed? Or are you doing that so that you can match up the keys of the dictionary? If you are okay with the punctuation staying in then this can be solved in a few lines:</p>
<pre><code>alphakey = {'a': 5, 'b': 7, 'c': 4, 'd': 3, 'e': 7, 'f': 3,
'g': 3, 'h': 5, 'i': 2, 'j': 2, ... | python|key|python-3.5 | 1 |
5,697 | 73,324,905 | Python language is not in a dropdown list in vscode when creating new azure function | <p>I was able to create Azure function app in vscode.</p>
<p><a href="https://i.stack.imgur.com/0K1mh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0K1mh.png" alt="enter image description here" /></a></p>
<p>Next, I am trying to create a new project using <code>Shift + Control + P</code> (cant find... | <p><em><strong>Can you please make sure that you have python pre installed if yes try deleting and reinstalling the extension because for me it is asking for language before going to runtime, when i try to reproduce i get it:</strong></em></p>
<p><img src="https://i.imgur.com/Bv1JGV5.png%5D" alt="enter image descriptio... | python|azure|azure-functions | 0 |
5,698 | 50,185,547 | Dataframe using For Loop in Pandas | <p>I need to run the code lines something like this.</p>
<pre><code>tweet24042018 = tweets.loc[tweets['date2'] == '24042018'].copy()
tweet23042018 = tweets.loc[tweets['date2'] == '23042018'].copy()
tweet22042018 = tweets.loc[tweets['date2'] == '22042018'].copy()
</code></pre>
<p>The function created and tried is like... | <p>Try using <code>locals</code></p>
<pre><code>variables = locals()
for key in collect:
variables["tweet{0}".format(key)]= tweets.loc[tweets['date2'] == key]
print(variables["tweet{0}".format(key)].head())
</code></pre> | python|pandas|loops|for-loop|dataframe | 1 |
5,699 | 49,906,131 | Is there a way to pause a code in the middle of a run? | <p>How do you handle a code where you have to pause the code at any given moment. For example, you could be reading files from server and server is going to be rebooted; you would want to pause the code so it stops trying to read the file from the server. You also wouldn't want to rerun the code if you have been runnin... | <p>I don't know how this will affect efficiency-wise but can't you use sleep() inside a while loop or something like that.
As in,</p>
<pre><code>while not condition: sleep(100)
</code></pre>
<p>or just,</p>
<pre><code>while not condition: pass
</code></pre> | python|python-3.x|python-2.7 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.