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 |
|---|---|---|---|---|---|---|
7,200 | 71,784,675 | Automatic Header Identification (Pandas / CSV) | <p>I am working on a project that parses csv files. In its current state, the user has to enter a unique string from the known column names to set the header row, both for parse column selection and to populate the columns-to-keep field.</p>
<p>My goal is to remove that step from the user end and automate the process, ... | <p>After toying with the code all day I think I found a solution that works. If anyone is willing to test it for me on their end, I would appreciate the feedback!</p>
<pre><code>import os, sys
import pandas as pd
import numpy as np
docs = os.listdir() #folder path where files are saved
os.chdir()
for file in docs:
... | python|pandas|dataframe|csv|header | 0 |
7,201 | 69,527,869 | How to resolve ImportError when using python pandas read_excel in program deployed to Google Cloud Run | <p>My program reads data from Excel files that are stored in Google Cloud Storage buckets using the pandas read_excel method.
The program works fine when run locally, but I am getting <a href="https://i.stack.imgur.com/7ferk.png" rel="nofollow noreferrer">this ImportError</a> when I try to run the program after it is d... | <p>This issue has been resolved.
I did not realize that I needed to manually choose the image build and re-deploy. I thought that if the build was successful, it would automatically deploy with the most recent build.
So my subsequent tests did not actually use the updated requirements.txt...
Adding openpyxl to the requ... | python|excel|pandas|importerror|google-cloud-run | 0 |
7,202 | 55,197,345 | Order doesn't work when using youtube API v3 | <p>I am trying to get the last 10 videos of a channel. When I run the following code:</p>
<pre><code>from apiclient.discovery import build
API_SERVICE_NAME = "youtube"
API_VERSION = "v3"
def youtubeTest():
KEY = "my key here"
service = build(API_SERVICE_NAME, API_VERSION , developerKey=KEY)
arg... | <p>Follow-up on issue #128673552, <a href="https://issuetracker.google.com/issues/128673552" rel="nofollow noreferrer">https://issuetracker.google.com/issues/128673552</a>.</p> | python|youtube-api|youtube-data-api | 4 |
7,203 | 42,286,765 | using repo other then pypi with pip | <p>I am having trouble understanding how pip works in a specific environment. The thing is that I am trying to install OpenStack using ansible-openstack deployment method. It provides playbooks to prepare the complete environment and install all components. Deployment fails at the step when python modules should be ins... | <p>FWIW, I had the very same symptom Danil described:</p>
<pre><code>root@control1-galera-container-434df170:~# pip install MySQL-python
Collecting MySQL-python Could not find a version that satisfies the requirement MySQL-python (from versions: )
No matching distribution found for MySQL-python
</code></pre>
<p>The ... | python|pip|ansible|openstack | 0 |
7,204 | 42,459,083 | How do I add a Key/Value in JSON with Python? | <p>This may sound like an average question, but I haven't found a good answer to what I am trying to do.</p>
<p>Take d.json:</p>
<pre><code>{"SDA":{"Info":{"Description":"Anti Advertisment Bot, Blocks invites extensively.","Download Link":"http://sda.khionu.net/docs/, http://sda.khionu.net/docs/"}}, "Unit 02":{"Info"... | <p>Use <a href="https://docs.python.org/2/library/json.html" rel="nofollow noreferrer"><strong>json module</a></strong> for that, code below shall give you the clue:</p>
<pre><code>import json
data = json.load('path_to_json_file')
data['key'] = 'value'
json.dump('path_to_json_file', data)
</code></pre> | python|json | 3 |
7,205 | 58,355,568 | Why is my function returning "function ___ at 0x7f37c058d378"? | <p>This function:</p>
<pre><code>hand_p = ''
def hand_player(card_variable):
global hand_p
hand_p = hand_p + str(card_variable)
return hand_p
</code></pre>
<p>is returning something like <code>function hand_player at 0x7f37c058d378</code>. </p>
<p>Why is this happening?</p> | <p>You haven't called the function anywhere in your code. If you wanted to pass an argument of <code>'a'</code> you could call it as follows:</p>
<pre><code>hand_p = ''
def hand_player(card_variable):
global hand_p
hand_p = hand_p + str(card_variable)
return hand_p
print(hand_player('a'))
</code></pre> | python | 2 |
7,206 | 58,202,209 | Calculate average and class-wise precision/recall for multiple classes in TensorFlow | <p>I have a multiclass model with 4 classes. I have already implemented a callback able to calculate the precision/recall for each class and their macro average. But for some technical reason, I have to calculate them using the metrics mechanism. </p>
<p>I'm using TensorFlow 2 and Keras 2.3.0. I have already used the... | <p>It occurs that in my very specific case, I can simply use <code>CategoricalAccuracy()</code> as unique metric because i'm using a <code>batch_size=1</code>. It this case, <code>accuracy=recall=precision={1.|0.}</code> for a batch. That only partially solve the problem. The best solution would be to update the confus... | tensorflow|keras | 0 |
7,207 | 22,639,838 | Start and stop multiple processes at once (Ubuntu) | <p>so I have a bunch of mixed scripts on my Ubuntu server which I would like to run all at once, keep the PID so i can kill them all at once. They are mixed ruby and python scripts, which shouldn't matter since it would just be a list of commands to run and save the PID of, I just don't know how. And would it possible ... | <p>have all scripts running from shell script</p>
<p>vi Main.sh</p>
<pre><code>#/bin/ksh
MODE=$1
if [ $MODE = "start" ]; then
#get PID of main sacript
echo " Main PID: $!" >> PID.txt
#Run first script
./script1.sh &
#save PID of script one
echo "script 1 PID: $!" >> PID.txt
#Run second script
./sc... | python|ruby|shell|ubuntu|scripting | 0 |
7,208 | 28,744,046 | Multiprocessing python not running in parallel | <p>I have been trying to use multiprocessing module from python to achieve parallism on a task that is computationally expensive.</p>
<p>I'm able to execute my code, however it doesn't run in parallel. I have been reading multiprocessing's manual page and foruns to find out why it isn't working and i haven't figured i... | <p>Make sure to read the Windows guidelines in the <code>multiprocessing</code> manual: <a href="https://docs.python.org/2/library/multiprocessing.html#windows" rel="nofollow">https://docs.python.org/2/library/multiprocessing.html#windows</a></p>
<p>Especially "Safe importing of main module": </p>
<blockquote>
<p>I... | python|parallel-processing|multiprocessing|python-multiprocessing | 2 |
7,209 | 68,634,033 | Why leetcode is producing different result than pycharm and jupyter-notebook? | <p>It sounds strange but I copied pasted and used the same input for the method, I get the correct result on my machine but leetcode is producing different result for the same code. this is the code on leetcode for Q-377:</p>
<pre><code>class Solution:
def combinationSum4(self, nums: List[int], target: int,memo={})... | <p>The question in Leetcode doesn't have the argument <code>memo = {}</code>. This is from LC code.</p>
<blockquote>
<p><code>def combinationSum4(self, nums: List[int], target: int) -> int:</code></p>
</blockquote>
<p>Since you are changing the functions arguments, it works for you <strong>only</strong> in PyCharm o... | python|python-3.x | 1 |
7,210 | 68,802,645 | How to create a 64-bit-DLL in Delphi 10.4 and call it from python/julia | <p>I have a Delphi library that I want to compile to a DLL (<code>PyMinMod_TRANS.dll</code>) that can be called from another programming language like Python or Julia. When compiling it from RADStudio Delphi 10.4 to Windows 32 Bit and calling it with 32-bit-Python 2 via</p>
<pre class="lang-py prettyprint-override"><co... | <p>The module initialization changed quit a bit between Python2 and Python3, so just exchanging the DLL to a Python3 one won't work without also adapting the init code. There's a good <a href="https://docs.python.org/3.7/howto/cporting.html?highlight=py_initmodule" rel="nofollow noreferrer">article</a> about this in th... | python|delphi|dll | 0 |
7,211 | 41,593,793 | print(tabulate(...)) to pretty print multiIndex pandas ? | <p>Say i have a pandas data frame: </p>
<pre><code>import numpy as np
import pandas as pd
from tabulate import tabulate
A = pd.DataFrame(np.random.randint(0,10,(3,6)), index= ['uno', 'dos', 'tres'])
A.columns = ['A','B','C','D','E','F']
A.index.names = ['type']
A.columns.names= ['group']
h = [A.index.names[0] +'/'+ ... | <p>With <a href="https://pypi.python.org/pypi/tabulate" rel="noreferrer">tabulate</a> version 0.8.1 or newer,</p>
<pre><code>import numpy as np
import pandas as pd
from tabulate import tabulate
A = pd.DataFrame(np.random.randint(0,10,(3,6)), index= ['uno', 'dos', 'tres'])
A.columns = ['A','B','C','D','E','F']
A.index... | python|python-3.x|pandas|python-3.5|pweave | 6 |
7,212 | 41,299,385 | Where to define a QuerySet in Django | <p>I want to define a queryset. In the shell it is all fine and I can filter the column I want with:</p>
<pre><code>pat1 = Patient.objects.get(pk=1)
pat1.examinationgeometry_set.filter(examination='FIRST')
</code></pre>
<p>now I want to define a QuerySet out of it but I don't know where to define it and how. In the V... | <p>Querysets should be made in the view, not in the template, given your code, it should be something like this:</p>
<p>view.py:</p>
<pre><code>def my_view:
patients = Patient.objects.all()
context = {"patients": patients}
return render(request, "template_path", context)
</code></pre>
<p>template.html:</p>
<p... | python|django|django-queryset | 0 |
7,213 | 6,717,221 | python: how to share an sqlite connection among threads with queues? | <p>I'm using Python 3.2.1 on Arch Linux x86_64.<br>
I'm trying to update an sqlite database in a threaded, timed loop with some code similar to the following:</p>
<pre><code>import sqlite3
from threading import Timer
from queue import Queue
class DBQueue(Queue):
def give(self, item):
self.task_done()
... | <p>You don't need the <code>Queue</code> - just use separate connections to the same database from the two threads. Keep in mind that you shouldn't expect much in terms of ordering when separate connections commit data into the DB. Treat it as if you had two different instances of your program accessing the DB simultan... | python|multithreading|sqlite|timer|queue | 5 |
7,214 | 56,995,391 | How to make percentage bar chart of topics from topic modeling? | <p>I have been racking my brain on this for a week. </p>
<p>I want to </p>
<ol>
<li>run NMF topic modeling</li>
<li>Assign each document a topic by looking at the maximum of weights, </li>
<li>Graph this distribution as a % bar chart using matplot. (I.e: Topics on the X axis, and % documents that are that topic on th... | <p>looks like a use case for a Counter().
I'd write something like this: </p>
<pre><code>from collections import Counter
mylist = [1,1,1,1,2,2,3,1,1,2,3,1,1,1]
mycount = Counter(mylist)
for key,value in mycount.items():
print(key,value)
</code></pre>
<p>This outputs your topics in the following structure: </... | python|pandas|matplotlib|scikit-learn | 0 |
7,215 | 57,241,254 | astropy.extern.configobj.configobj.ConfigObjError: Parsing failed with several errors | <p>When I import the astropy package, I got the following error message.</p>
<pre><code>>>> import astropy
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/lalitawadee/anaconda3/lib/python3.7/site-packages/astropy/__init__.py", line 288, in <module>
... | <p>It sounds like you somehow have a corrupt astropy config file somewhere. It would help if the error message gave the filename, but see <a href="http://docs.astropy.org/en/stable/config/" rel="nofollow noreferrer">http://docs.astropy.org/en/stable/config/</a> for possible locations.</p>
<p>For starters, I would try ... | python-3.x|astropy | 0 |
7,216 | 53,804,735 | Get similarity percentage on multiple strings | <p>Is there any function inside Python that can accept multiple rows of strings and return a percentage of how much similarity they have? something like <code>SequenceMatcher</code> but for multiple strings.</p>
<p>For example we have the following sentences </p>
<pre><code>Hello how are you?
Hi how are you?
hi how a... | <p>You can use <code>pandas</code> to operate with a dataframe, <code>itertools.combinations</code> to calculate the combinations of 2 strings from your list and <code>difflib.SequenceMatcher</code> for the similarity calculation:</p>
<pre><code>import pandas as pd
import itertools
from difflib import SequenceMatcher
... | python|string|similarity|sentence-similarity | 2 |
7,217 | 25,447,568 | Why does href change after downloading page | <p>I'm making a web parser and some href are driving me crazy</p>
<pre><code>resp = urllib.request.urlopen("http://portogruaro.trasparenza-valutazione-merito.it/storico-atti")
page = resp.read().decode('utf-8')
print(page)
</code></pre>
<p>I found this in the downloaded page:</p>
<pre><code><a.. href="http://port... | <blockquote>
<p>;jsessionid is added because the bot doesn't manage cookies, but It's not the only change...why?</p>
</blockquote>
<p>Hum ... apart from the ticket number and the <code>jsessionid</code> token, those are the same URL.</p>
<p>The parameters are <em>not</em> in the same order. But as far as I can tell... | python|html-parsing|anchor|html-parser | 0 |
7,218 | 25,691,164 | Numpy.unique behavior (flattening insconsistencies?) | <p>I have two lists from which I need to find the <strong>indices</strong> associated with unique pairs (all the SO posts I could find are only interested in the pairs themselves). I've been trying to use <code>numpy.unique</code> to do so, but am hitting an oddity. I zipped the lists to create a list of tuples, which... | <p>The <a href="https://github.com/numpy/numpy/blob/v1.8.1/numpy/lib/arraysetops.py#L93" rel="nofollow">source code</a> for <code>numpy.unique</code> in version 1.8.1 starts with the following:</p>
<pre><code>try:
ar = ar.flatten()
except AttributeError:
if not return_inverse and not return_index:
retu... | python|numpy|unique | 3 |
7,219 | 23,596,780 | How is the 'or' function used in listing vairables in a function python | <p>I want to list several vairables in a function so they will all be detected:</p>
<pre><code> if how != 'no'or'yes':
print"That is not a valid answer"
</code></pre>
<p>so i want the if how != to read no and yes but when i run only no is detected</p> | <p>in your if condition:</p>
<pre><code>if how != 'no' or 'yes':
</code></pre>
<p>you're making a wrong assessment, it's that python will understand that the value of <code>how</code> is either <code>no</code> or <code>yes</code>, like you would do in a natural language.</p>
<p>But what you're actually testing is wh... | python|if-statement | 0 |
7,220 | 23,981,916 | Django 'NoneType' object has no attribute '__getitem__' | <p>I read this article <a href="http://eshlox.net/en/2012/09/13/sphinxsearch-and-django-ubuntu/" rel="nofollow">http://eshlox.net/en/2012/09/13/sphinxsearch-and-django-ubuntu/</a></p>
<p>In view i get error for code: total = query_results['total']</p>
<p>error: 'NoneType' object has no attribute '<strong>getitem</str... | <p>I imagine your query results are None</p>
<pre><code>query_results = s.Query(query)
</code></pre>
<p>so when you try to access </p>
<pre><code>total = query_results['total']
</code></pre>
<p>you get the <code>__getitem__</code> error because None is not a List.</p>
<p>Here's an example from the interpreter.</p>... | python|django|sphinx|django-sphinx | 4 |
7,221 | 71,987,436 | on_voice_state_update() not running as expected when going [vc -> vc] | <p>The following code is meant to change the name of a voice channel depending on what game is being played. It works perfectly when the state change is <code>[NONE -> vc]</code> & <code>[vc -> None]</code> but not when going <code>vc -> vc</code>.</p>
<pre class="lang-py prettyprint-override"><code>@clien... | <p>Maybe for the beginning you should make. This checking when your action take field.</p>
<pre><code>if before.channel is None and after.channel is not None:
## do your stuff here
elif before.channel is not None and after.channel is None:
## do your stuff here
</code></pre>
<p>I use this one for logging ... | python|python-3.x|discord|discord.py | 0 |
7,222 | 46,585,670 | Does Cloud Python lib in GAE use caching or memcache for access to Cloud Firestore data? | <p>Setup: Google App Engine application on Python standard environment.</p>
<p>Currently, the app uses the NDB library to read/write from its Datastore. It uses async tasklets for parallel, asynchronous reads from Datastore, and memcache.</p>
<p>If I would like to use Firestore as a replacement for Datastore, it seem... | <p>The Cloud Firestore server-side client libraries are not optimized for App Engine Standard. They don't integrate with a caching solution like GAE's memcache; you'd have to write that layer yourself.</p> | google-app-engine|firebase|google-app-engine-python|google-cloud-python|google-cloud-firestore | 2 |
7,223 | 49,635,508 | How to access the raw query string (or full URL) in a Chalice (AWS Lambda/API Gateway) app? | <p>I'm using Chalice to build a fairly straightforward API on AWS Lambda & API Gateway.</p>
<p>I need a way to get access to the raw query string (i.e <code>foo=bar&abc=123</code>). When accessing the <code>app.current_request.query_params</code> dictionary, it's already been processed, such that any empty par... | <p>If you wish to get everything you do the following.</p>
<p>Let's say you are hitting the route <code>/objects/{what}?human=you&thing=computer</code></p>
<pre class="lang-py prettyprint-override"><code>@app.route('/objects', methods=['GET'])
def myobject(what):
everything = app.current_request.to_dict()
p... | python|amazon-web-services|aws-lambda|aws-api-gateway|chalice | 0 |
7,224 | 49,658,377 | Python - insert all elements of a list in the middle of another like in Ruby | <p>In Ruby I can do:</p>
<pre><code>irb(main):002:0> [1, 2, 3, *[4, 5], 6, 7]
=> [1, 2, 3, 4, 5, 6, 7]
</code></pre>
<p>Is there a Python equivalent? The Ruby syntax is invalid in Python:</p>
<pre><code>>>> l = [1, 2, 3, *[4, 5], 6, 7]
File "<stdin>", line 1
l = [1, 2, 3, *[4, 5], 6, 7]
... | <p>Upgrade your Python. That's valid syntax now. <a href="https://www.python.org/dev/peps/pep-0448/" rel="noreferrer">It's been valid since 3.5.</a></p>
<pre><code>>>> [1, 2, *[3, 4], 5]
[1, 2, 3, 4, 5]
</code></pre>
<p>If you're stuck on an old version, there is no equivalent.</p> | python|list | 9 |
7,225 | 49,497,663 | (fixed acidity;"volatile acidity";"citric acid";"re...)<-- how do I separate something like this with commas? | <p>I got this dataset (link below), I'm trying to do an exercise for learning TensorFlow and had problems loading the data. The instruction says:</p>
<p>"Read the data into a DataFrame with Pandas. pd.read_csv would be very useful here. Note, it has an option to specify the delimiter (and the wine csv files are not c... | <p>You don't need to change it into commas, just use semicolon as a seperator and set the <code>dtype</code> to float</p>
<pre><code>pd.read_csv('winequality-white.csv', sep=';', dtype='float')
</code></pre> | pandas|numpy | 0 |
7,226 | 45,839,744 | TensorFlow max_pool2d wrong output size | <p>I'm trying to use a max pool layer with filter size 2x2, so I expect the output size to be roughly half the input size.
The input size is 9x14x64, but for some reason the output size is 7x12x64 (see the attached <a href="https://i.stack.imgur.com/0UyZ8.png" rel="nofollow noreferrer">TensorBoard graph</a>).</p>
<p>H... | <p>It seems you are tensorflow default data_format <code>NHWC</code>; but your input format is <code>NCHW</code>. So you need to change your input format to <code>NHWC</code></p>
<pre><code>N -batch_size, H-height, W-width, C-num_channels
</code></pre>
<p>Note: Max-pool only changes <code>height</code> and <code>wid... | tensorflow|max-pooling | 0 |
7,227 | 45,905,403 | django post_delete() signal handler doesn't work | <p>I am trying to make it so that the 'num_posts' field of a blog object is decremented every time a post belonging to that blog is deleted, and incremented every time a post is created. I was able to implement the overloaded save method easily enough:</p>
<pre><code>def save(self, *args, **kwargs):
'''After savin... | <p>You forgot to save the updated <code>Blogs</code> instance in <code>handle_bpost_delete</code></p>
<pre><code>def handle_bpost_delete(sender, instance, **kwargs):
instance.blog.num_pages -= 1
instance.blog.save()
</code></pre>
<p>There's a simpler way to get the count of related objects, though. You can si... | django|python-3.x|django-signals | 0 |
7,228 | 45,789,849 | Testing database in django other than django models | <p>I am using mysql-server and MySQLdb for accessing my database. I have not even used django models to accessing the database tables. </p>
<p>Now the problem comes while testing. All the django documentation is talking about the testing using django models. While testing a data, i have to insert data into the databas... | <p>A better approach to setting up your database than overriding <code>setUp</code> and <code>tearDown</code> methods for <code>TestCase</code> is to get out of Django's way by implementing <code>setUpTestData</code> instead.</p>
<pre><code>from django.db import connections
class BasicTest(TestCase):
@classmetho... | python|mysql|django|unit-testing|automated-tests | 1 |
7,229 | 55,105,447 | Virtual python shell with Vte.Pty.spawn_async() | <p>I would like add virtual python shell with Vte to my GTK3.0 python3 app and <a href="https://stackoverflow.com/questions/49464926/pygobject-vte-terminal-command-printed-twice">I am able to do this with spawn_sync()</a> method, but this method is deprecated, so I would like to do it with preferred way with Vte.Pty.sp... | <p>There is final working solution, I made bad mistakes, now it is working great :). Thanks @elya5 for your answer :).</p>
<pre><code>import gi
gi.require_version('Gtk', '3.0')
gi.require_version('Vte', '2.91')
from gi.repository import Gtk, Vte, GLib, Pango, Gio
class TheWindow(Gtk.Window):
def __init__(... | python|python-3.x|gtk|pygobject|vte | 1 |
7,230 | 54,720,569 | Code works run Individually in a cell ,But not working when i'm importing it | <p>When i try to import classes from a python file and use them in collab it throws a name error ,but when i copy and paste the same code and run it in a cell in collab it works just fine .
the error is very wierd it will always show the same line as the source of the error .. even if it is blank</p>
<p>i've tried fi... | <p>Showing the same error at the same line even after you edit the code (or blank the line) strongly suggests you're not explicitly reloading the module. Python's import system is idempotent meaning that repeatedly calling "import foo" on the same module will have no effect after the first invocation, even if you edit ... | python|google-colaboratory | 0 |
7,231 | 12,658,713 | Using tuples in a Heap for multidimensional sorting? | <p>Say I have a list such as:</p>
<pre><code>[(3,4), (4,3), (1,5), (5,1), (2,6), (6,2)]
</code></pre>
<p>where I want to return the tuple with the lowest x-value, and also one with the lowest y-value.</p>
<p>Is it possible to build a (min-)heap using index 0, and a different heap using index 1? That would make two h... | <p>The answer is yes, you can use <a href="http://docs.python.org/library/heapq.html#basic-examples" rel="nofollow">heapsort</a> on tuples:</p>
<blockquote>
<p>Heap elements can be tuples. This is useful for assigning comparison values (such as task priorities) alongside the main record being tracked...</p>
</blockq... | python|algorithm|heapsort | 4 |
7,232 | 21,666,670 | Singly Linked List Python Implementation | <p>I am trying to get the second to last element from a singly linked list in python. Here is my implementation:</p>
<pre><code>class ListNode:
def __init__(self, data, next):
self.data = data
self.next = next
def make_arr(xx, arr):
if xx == None:
return arr
else:
arr.inser... | <p>You're not returning <code>arr</code> in <code>make_arr</code>...</p>
<p>Edit: a version of your code that works</p>
<pre><code>def make_arr(xx, arr):
if xx == None:
return arr
# No need for the else, in this case
arr.insert(0, xx.data)
return make_arr(xx.next, arr)
</code></pre> | python|singly-linked-list | 2 |
7,233 | 24,672,040 | how to plot an histogram with python ggplot? | <p>I would like to plot an histogram representing the value TP on the y axis and the method on the x axis. In particular I would like to obtain different figures according to the value of the column 'data'. </p>
<p>In this case I want a first histogram with values 2,1,6,9,8,1,0 and a second histogram with values 10,1... | <p>This is probably because you called <code>ggplot()</code> without an argument (Not sure if that should be possible. If you think so, please add a issue on <a href="http://github.com/yhat/ggplot" rel="nofollow">http://github.com/yhat/ggplot</a>).</p>
<p>Anyway, this should work:</p>
<pre><code>ggplot(df, aes(x='met... | python|ggplot2|histogram|python-ggplot | 0 |
7,234 | 40,929,744 | save print output to .txt | <p>I have a script that export all email adresses from a .txt document and print all the email adresses.
I would like to save this to list.txt, and if possible delete duplicates,
but it will give the error</p>
<pre><code>Traceback (most recent call last):
File "mail.py", line 44, in <module>
notepad.write... | <blockquote>
<p>When I remove .read() it shows only 1 email adres in list.txt when I
use print email is shows a couple of hundred. when refreshing the
list.txt while the extraction is busy the email adres change's but it
only shows 1.</p>
</blockquote>
<p>This is because you have <code>open()</code> and <code>... | python|regex|output | 0 |
7,235 | 29,316,173 | APScheduler run async function in Tornado Python | <p>I am trying to develop a small app which will gather weather data from an API. I have used APScheduler to execute the function every x minutes. I use Python Tornado framework.</p>
<p>The error I am getting is:</p>
<pre><code>INFO Job "GetWeather (trigger: interval[0:01:00], next run at: 2015-03-28 11:40:58 CET... | <p>By default, TornadoScheduler runs scheduled tasks in a thread pool. Your specific task, however, uses the IOLoop and so expects to be run in the same thread. To fix this, you can use the add_callback() method of the tornado IOLoop to schedule a task to be run in the IOLoop's thread as soon as possible.</p>
<p>Like ... | python|mongodb|asynchronous|tornado|apscheduler | 3 |
7,236 | 59,039,240 | how do you split list into x lists without using the elements on the inside? | <p>Working on an assignment, which in one of the parts requires me to split the list into "x" chunks of lists but I don't necessarily want to use the elements inside the list to do so as I have seen many examples that do this. For example, given the list <code>[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]</code>, I want to spl... | <blockquote>
<p>Most of the examples that I have seen on here tend to divide the whole list by "x" rather than making "x" groups of it which end up giving me a list like [[1,2,3],[4,5,6],[7,8,9],[10,11,12],[13,14,15]].</p>
</blockquote>
<p>In your example, a list of 15 elements divided into chunks of 3 makes 5 group... | python|chunking | 0 |
7,237 | 52,079,211 | Cannot update svg file(s) for saleor framework + python + django | <p>I would like to know how should i could manage to change the <strong>static</strong> files use by the <em>saelor framework</em>. I've tried to change the logo.svg but failed to do so.</p>
<p>I'm still learning python program while using the saleor framework for e-commerce.</p>
<p>Thank you.</p> | <p>Here is how it should be done. You must put your logo in the <code>saleor/static/images</code> folder then change it in <code>base.html</code> file in <code>footer</code> and <code>navbar</code> section.</p> | django|python-3.x|saleor | 1 |
7,238 | 52,302,453 | How to read a dictionary from this text file? | <p>I am still new to python and I am playing around with saving data to text files. My problem is that when I try to access a dictionary it comes up with this error <code>TypeError: string indices must be integers</code> but I don't know how to convert them.</p>
<p>This is what's inside my file:</p>
<pre class="lang-... | <p>I'd suggest using JSON to write the data out to a text file
<a href="https://docs.python.org/3/library/json.html" rel="nofollow noreferrer">https://docs.python.org/3/library/json.html</a></p>
<p>You can use the json.dumps method to create JSON data that can be written to a file and use the json.loads method to conv... | python|python-3.x | 1 |
7,239 | 51,837,245 | Encoding categorical variables : TypeError: '<' not supported between instances of 'str' and 'float' | <p>I tried to encode my categorical variables via the LabelEncoder and OneHotEncoder method.
My X matrix is composing of variables all with floats and my Y with variables of type object:</p>
<pre><code>X = df.loc[:, df.dtypes == np.float64]
Y = df['VCat']
</code></pre>
<p>when I apply my method:</p>
<pre><code>fro... | <p>You probably have some missing data in your dataframe. Treat the missing data before performing this action.</p>
<p>You can use df.count() to check which columns have the missing data.</p>
<p>If that doesn't work, go through your data and make sure that each column contains only data of the type that it is trying ... | python | 1 |
7,240 | 67,422,160 | How should callables retrieved with super() be called? | <p>I noticed that with this <code>B.f</code> implementation, the call <code>B.f(B)</code> raises a <code>TypeError</code>:</p>
<pre class="lang-py prettyprint-override"><code>>>> class A:
... def f(self): print('foo')
...
>>> class B(A):
... def f(self):
... super().f()
... pr... | <p>I have just realised with this <code>A.g</code> implementation that the issue is not specific to using <code>super()</code>:</p>
<pre class="lang-py prettyprint-override"><code>>>> class A:
... def f(self): print('foo')
... def g(self):
... self.f()
... print('bar')
...
>>>... | python|function|methods|super | 0 |
7,241 | 67,187,502 | Dataquest , Question about updating dictionary? | <p>Can someone please explain the red line. Why would we program <code>content_ratings[bilal]</code> I dont really understand the logic behind that. I know we are updating the empty dictionary but why would we program what we programed?</p>
<p><a href="https://i.stack.imgur.com/cv1Zd.png" rel="nofollow noreferrer"><img... | <p>The dictionary <code>content_ratings</code> calculates number of times a given rating appears.</p>
<p>So <code>if bilal in content_ratings</code> checks that if the key already exists.</p>
<p>If there is no item till now which is the same as the value <code>bilal</code> is currently having, the count is set to one.<... | python | 0 |
7,242 | 67,420,677 | Why are Java HTTP requests so slow (in comparison to Python), and how can I make them faster? | <p>Java is a beautiful language, and is also supposedly very efficient. Coming from a background of having used Python, I wanted to see the difference between the 2 languages- and from the start I was very impressed by the explicitness and clarity of Java's OOP based syntax. However, I also wanted to test out the perfo... | <p>I was really skeptical about the results you got, so I gave it a try with the exact same Python code and <code>main</code> Java method (that uses https) as yours.<br>
Here is the Java <code>run</code> method that reads the entire JSON content of the response:</p>
<pre class="lang-java prettyprint-override"><code>pri... | java|http|networking|python-requests|okhttp | 6 |
7,243 | 36,268,420 | How to concatenate text variables in python | <p>I have a real beginner question. I would like to do the following:</p>
<pre><code>FileName1 = open(r'C:\Users\data.txt')
PointID = '1'
</code></pre>
<p>Now, I'd like to create a new variable that is set to be equal to File1, i.e. a concatenation of File and PointID, or something like this if the variables were bot... | <p>When you use <code>open</code>, the result isn't a string. To read the contents of the file as a string, call <code>.read</code> on the result of your <code>open</code> call:</p>
<pre><code>File = open(r'C:\Users\data.txt').read()
PointID = '1'
</code></pre>
<p>You can now concatenate your two string variables lik... | python|file|text|concatenation | 1 |
7,244 | 36,505,384 | Problems With a Simple Driving Game | <p>I'm trying to make a simple top down driving simulator where you hold down the up arrow key to move and use the right/left arrow keys to steer. Ideally, if you were to hold down the up key and left or right key at the same time, the car would move in a circle.</p>
<p>The car should move the same distance on the sc... | <p>Following on my comment above, it looks like if you change:</p>
<pre><code> if drive == 1:
if turn == 1 and d != 359: # Turn Clockwise
d += 4
if turn == 1 and d == 359:
d = 0
if turn == -1 and d != 0: # Turn Counter Clockwise
d -= 4
if turn == -... | python|pygame|trigonometry | 1 |
7,245 | 19,606,973 | Eclipse plugin that enforce code documentation | <p>I'm developing python with PyDev in eclipse.
I'm looking for a plugin that will help me enforce documentation on my code.</p>
<p>Does anyone knows of such a plugin?</p>
<p>Thanks</p> | <p>Not exactly for Eclipse, but you could tie pep8 (the PEP-8 validator) to every git commit. One of the things pep8 complains is lack of docstrings.</p>
<p>Never tried, but <a href="http://widerin.org/blog/using-pep8-checks-in-eclipse" rel="nofollow noreferrer">http://widerin.org/blog/using-pep8-checks-in-eclipse</a>... | python|eclipse|pydev|code-documentation | 1 |
7,246 | 19,505,123 | variable sliding window on python list | <p>I have a dataset that looks like this (1D python list):</p>
<pre><code>[0,0,0,0,4,5,6,6,4,0,0,0,0,0,0,2,0,0,0,6,4,5,6,0,0,0,0,0]
</code></pre>
<p>I'm trying to find cutoff points for variations, based on the <strong>previous window</strong>. </p>
<p>I'm looking for an output of:</p>
<pre><code>[4, 9, 19, 23]
</c... | <p>The best approach I can think of for this problem is to fit a spline to the array, take the derivative, and then find all local maxima. These local maxima should represent the boundaries of peaks, which I think is what you are after. My approach:</p>
<pre><code>from scipy import signal
from scipy import interpolate... | python|arrays|numpy|standard-deviation | 1 |
7,247 | 13,444,666 | Implementing breadcrumbs in Python using Flask? | <p>I want breadcrumbs for navigating my <a href="http://flask.pocoo.org">Flask</a> app. An option could be to use a general Python module like <a href="http://russell.ballestrini.net/a-homegrown-python-bread-crumb-module/">bread.py</a>:</p>
<blockquote>
<p>The bread object accepts a url string and grants access to t... | <p>So you're after "path/history" breadcrumbs, rather than "location" breadcrumbs to use the terminology from the <a href="http://en.wikipedia.org/wiki/Breadcrumb_%28navigation%29" rel="noreferrer">wikipedia article</a>?</p>
<p>If you want to have access to the user's history of visited links, then you're going to hav... | python|navigation|flask|breadcrumbs | 13 |
7,248 | 54,593,489 | Change list, that you are iterating through, in that loop | <p>In my case I have a for loop, looping through a list, but I want to change that list in said loop.
After that I want the for loop to iterate through the new list.</p>
<pre><code>li = [4,5,6,7,8,9]
for item in li:
#do something
if item == 5:
#now continue iterating through this loop and not the old ... | <p>You shouldn't change the list through iteration. I would use indexing:</p>
<pre><code>for i in range(len(li)):
if li[i] == 5:
li = len(li) * [9]
</code></pre> | python|loops | 0 |
7,249 | 71,363,658 | cURL receives "encoded" response from nginx server | <p>I'm doing a scrape on a platform, and I'm using the cURL method to get the direct data, but I always get an "encoded" response, which I thought was compressed (but isn't), and now I believe the answer is in some format I don't know. Even intercepting the platform, it ALSO receives the same "encoded&qu... | <p>I believe the response is <code>gzip</code> encoded/compressed [1], and you need to decompress it. Try piping the body of the response into <code>gunzip</code> on linux.</p>
<p>[1] <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding" rel="nofollow noreferrer">https://developer.mozilla... | javascript|python|curl | -2 |
7,250 | 9,212,228 | Using custom formatter classes with Python's logging.config module | <p>I have the following logging class, which works fine when assigned as a formatter in code. It extends an existing formatter by prepending a string to the start of the message to be logged, to help show the importance of the message. (I don't just use <code>%(levelname)s</code> in the format string because I don't wa... | <p>As you are using Python 2.7, you could use dictionary-based configuration using <a href="http://docs.python.org/library/logging.config.html#logging.config.dictConfig" rel="noreferrer"><code>dictConfig()</code></a>: this is more flexible than <code>fileConfig()</code>, as it allows use of arbitrary callables as facto... | python|logging|python-2.7 | 12 |
7,251 | 52,618,190 | show coordinates on plot using PIL | <p>I'm sorry, I can't seem to find how to do this. This works, but I would love to have the coordinates plotted along the axis:</p>
<pre><code>from PIL import Image, ImageDraw
im = Image.new('RGBA', (250, 250), "white")
draw = ImageDraw.Draw(im)
draw.rectangle([(0, 0), (249, 249)], outline='black') # just here to cre... | <p>Here is a "brute force" way to do this. You could generalize it to better handle different x/y ranges. Maybe you could use matplotlib and potentially go off <a href="https://matplotlib.org/gallery/statistics/errorbars_and_boxes.html#sphx-glr-gallery-statistics-errorbars-and-boxes-py" rel="nofollow noreferrer">this e... | python|python-imaging-library|coordinate-systems | 2 |
7,252 | 52,761,595 | Restart Program When Ping Timesout Twice | <p>Is there a way to do a constant ping in the background and restart an application when the pings return "Request Timeout" more than twice?</p>
<p>We have a problem with wireless and when the connection times out it freezes out telnet sessions on our handheld scanners.</p>
<p>What I currently have is cobbled from o... | <p>I never worked with subprocess before and my code is solely based on the assumption that your posted code works.</p>
<p>You could try:</p>
<pre><code>import os
import subprocess
import time
def start_subprocess():
subprocess.Popen([r"C:\tester.exe"])
hostname = "google.com"
start_subprocess()
while True:
... | python | 0 |
7,253 | 52,539,262 | AttributeError: module 'networkx' has no attribute 'Graph' in vs code | <p>I installed networkx module for python in windows and tried running a simple program on it using vs code. But when tried to run it says "AttributeError: module 'networkx' has no attribute 'Graph'". Not just Graph, if I use other networkx function it still says that networkx doesn't have that particular attribute. I ... | <p>You can't name your file same as a module. Change the name of your file from networkx to something else.</p> | python|visual-studio-code | 2 |
7,254 | 47,802,772 | Tkinter Python: Moving multiple widgets at once | <p>If I have multiple widgets within a Frame, is there a way to shift all widget positions at once with a command? I am using the .place manager. Thanks!</p> | <p>I would define variables <code>ref_y</code> and <code>ref_y</code> and just add them to my current <code>x</code> and <code>y</code> value as in:</p>
<pre><code>import tkinter as tk
root = tk.Tk()
ref_x = 40
ref_y = 56
btn = tk.Button(root, text="Button")
lbl = tk.Label(root, text="Label")
btn.place(x=ref_x + 4... | python|tkinter | 1 |
7,255 | 47,607,971 | python script in microsoft ser | <p>
Hi everyone,</p>
<p>I'm trying to wrap my head around microsoft server 2017 and python script.
In general - I'm trying to store a table I took from a website (using bs4),
storing it in a panda df , and then simply put the results in a temp sql table.</p>
<p>I entered the following code (I'm skipping parts of the ... | <p>To use pip to install a Python package on SQL Server 2017: </p>
<ul>
<li>On the server, open a command prompt as administrator.</li>
<li>Then <code>cd</code> to <code>{instance directory}\PYTHON_SERVICES\Scripts</code><br>
(for example: <code>C:\Program Files\Microsoft SQL Server\MSSQL14.SQL2017\PYTHON_SERVICES\Scr... | python|sql-server | 0 |
7,256 | 37,149,955 | Find third occurring `<p>` tag using with Beautiful Soup | <p>As the title suggests, I'm trying to understand how to find the third occurring <code><p></code> of a website (as an example, I used the following website: <a href="http://www.musicmeter.nl/album/31759" rel="nofollow noreferrer">http://www.musicmeter.nl/album/31759</a>). </p>
<p>Using the answer to <a href="h... | <p>You are using <em>siblings</em> i.e plural so you are getting a <em>ResultSet/list</em> back which you cannot call <em>.find_next_siblings</em> on.</p>
<p>If you wanted each next paragraph you would use <strong>sibling</strong> not <strong>siblings</strong>:</p>
<pre><code>second_paragraph = first_paragraph.find_n... | python|html|beautifulsoup | 4 |
7,257 | 34,015,467 | String Matching Using Recurrent Neural Networks | <p>I have recently started exploring Recurrent Neural Networks. So far I have trained character level language model on tensorFlow using Andrej Karpathy's <a href="http://karpathy.github.io/2015/05/21/rnn-effectiveness/" rel="noreferrer">blog</a>. It works great.</p>
<p>I couldnt however find any study on using RNNs f... | <p>This paper may the thing you are looking for: </p>
<p><a href="https://arxiv.org/abs/1608.02214" rel="nofollow noreferrer">[1608.02214] Robsut Wrod Reocginiton via semi-Character Recurrent Neural Network</a></p>
<p>A Brief introduction:</p>
<p>The author of this paper demonstrated a method to recognize jumbled wo... | machine-learning|string-matching|tensorflow|recurrent-neural-network | 1 |
7,258 | 16,524,461 | How to make asynchronous HTTP POST requests | <p>I have this program which runs in a loop with <code>pythoncom.PumpMessages()</code>.
While this program runs, it takes input and stores it iternally.
When the input reaches a certain lenght, I'd like to send a HTTP POST request asynchronously to a database I have in the cloud so the program doesn't stop taking input... | <p>This can be done if you use python requests library to send post requests.
It has been answered here.
<a href="https://stackoverflow.com/questions/9110593/asynchronous-requests-with-python-requests">Asynchronous Requests with Python requests</a>
The example is for "GET" request but you can easily do post request as... | python|python-2.7 | 1 |
7,259 | 32,013,030 | Insert comma in an array | <p>I have got this result when I print my variable </p>
<pre><code>print a.output2.data
[ 4.72796516e+01 4.72796516e+01 8.85784539e-06 ..., -8.85784721e-06
0.00000000e+00 3.14159274e+00]
</code></pre>
<p>I would like to have an array with comma
something like this </p>
<pre><code>[ 4.72796516e+01 , 4.7... | <p><code>a.output2.data</code> is probably an <code>np.array</code>. Try <code>list(a.output2.data)</code></p> | python | 1 |
7,260 | 40,343,838 | pytest-bdd: how to get current scenario from @given? | <p>I need to get scenario name or other unique information about currently running test in @given method.</p>
<p>In my test I declare, that I have some resource. This resource is being extracted/created from web api like that:</p>
<pre><code>@given('I have a new article')
def new_article(vcr_fixture):
with vcr_fi... | <p>nAlthough what user2292262 suggested works, it doesn't work as one would have expected when start learning pytest-bdd (at least least what I'd have expected).</p>
<p>The solution AIUI is creating a fixture for each article you have among your tests, without automatisms (i.e. function that create for you the data yo... | python|pytest | 0 |
7,261 | 40,510,197 | Swap nested list Python 3 | <p>Having looked at the python 3 documentation I would like to attempt something similar</p>
<pre><code>nested_list = [
(1,4,7,10),
(2,5,8,11),
(3,6,9,12),
]
sorted(nested_list, key=lambda nes: nes[0])
print(nested_list)
</code></pre>
<p>I would like the list to output as:</p>
<pre><code>[(2, 5, 8, 11), (1, 4, 7, 1... | <p>The 'key' argument takes a function, and that function is passed each element of the array as an argument as it iterates through. The line </p>
<pre><code>sorted(nested_list, key=lambda nes: nes[0])
</code></pre>
<p>looks at each tuple in <code>nested_list</code>, assigns it to <code>nes</code> and sorts it by <co... | list|python-3.x|nested | 0 |
7,262 | 40,738,493 | Tensorflow matmul calculations on GPU are slower than on CPU | <p>I'm experimenting with GPU computations for the first time and was hoping for a big speed-up, of course. However with a basic example in tensorflow, it actually was worse:</p>
<p>On cpu:0, each of the ten runs takes on average 2 seconds, gpu:0 takes 2.7 seconds and gpu:1 is 50% worse than cpu:0 with 3 seconds.</p>
... | <p>The way you use to generate data is executed on CPU (<code>random.random()</code> is a regular python function and not TF-one). Also, executing it <code>10^6</code> times will be slower than requesting <code>10^6</code> random numbers in one run.
Change the code to:</p>
<pre><code>a = tf.random_uniform([1000, 1000]... | python|performance|tensorflow|gpu | 4 |
7,263 | 32,180,591 | How to run python script for QGIS from outside | <p>I have hundred shape files in a folder. I have following tasks</p>
<ol>
<li>Find out what are the fields in each shapefile</li>
<li>If there is no field 'City' in any of the shapefiles I have to add that field in those shapefile.</li>
</ol>
<p>I can access each layer in python console in QGIS using
iface.activeLay... | <p>In my humble opinion, if you want to execute python scripts without the QGIS GUI, you could use the OGR Python API directly.</p>
<p>There's an entire "cookbook" here: <a href="https://pcjericks.github.io/py-gdalogr-cookbook/" rel="nofollow">https://pcjericks.github.io/py-gdalogr-cookbook/</a></p>
<p>The official A... | python|qgis | 1 |
7,264 | 28,231,175 | How to find and replace/remove text after a specified delims with Python? | <p>I have a <strong>40GB</strong> text file contain lines as follow:</p>
<blockquote>
<p>55655653:foo</p>
<p>6654641:balh2</p>
</blockquote>
<p>I've written a batch script to find and replace/remove :foo and only keep the number before that.</p>
<p>Batch script :</p>
<pre><code> @echo on
((for /f "tokens=1... | <p>You can use <code>str.partition</code> to split the number before the first <code>:</code></p>
<pre><code>with open('data.txt') as fin, open('dataFinal.txt', 'w') as fout:
fout.writelines(line.partition(':')[0] + '\n' for line in fin)
</code></pre>
<p>Not we're using <code>with</code> here so files are automat... | python|windows|batch-file | 3 |
7,265 | 44,082,186 | Python - Why isn't this specific text being found by findall regex? | <p>EDIT: PLEASE DO NOT DOWNVOTE WITHOUT COMMENTING ON WHY YOU ARE DOWNVOTING. I AM TRYING MY BEST TO WRITE THIS PROPERLY! </p>
<p>I am trying to print all of the URL links of watches on a website. I have all of them printing fine except one, even though that one has the exact same regex conditions as the others. Can s... | <p>You can try this code with this pattern:</p>
<pre><code>from urllib2 import urlopen
import re
url = 'https://denissov.ru/en/'
data = urlopen(url).read()
sub_urls = re.findall('window.open\(\'(/.*?)\'', data)
# take everything without deleting dublicates
# final_urls = [k for k in b if '/history' not in k and k is ... | html|regex|python-2.7 | 0 |
7,266 | 44,287,093 | Is there a way to define a function through symbolic derivation? | <p>Is there a way to define a function through symbolic derivation? For example,</p>
<pre><code>def f(x):return x**x
def df(x) : return diff(f(x),x)
</code></pre>
<p>This code doesn't work, since <code>df(1)</code> would not be possible (<code>diff(f(1),1)</code> doesn't make sense.) But is there a way to take advant... | <p>Don't need Maple or Mathematica. Python has sympy.</p>
<pre><code>import numpy as np
from sympy import symbols, diff, lambdify
x = symbols('x')
def f(x):
return x**x
def df(x):
return diff(f(x))
print(df(x))
</code></pre>
<p>This returns the symbolic derivative, <code>x**x*(log(x) + 1)</code>. Now, it ... | python|function|diff|sympy | 1 |
7,267 | 13,936,347 | Creating sequential certificate numbers with postgres | <p>I have a table that holds certificate numbers. Each certificate consists of a series letter and a serial number. Certificates must be unique and no gaps are allowed, i.e. if A-1234 exists, also A-1233 <strong>must</strong> exist. Each series has its own serials, i.e. A-1234 and B-1234 can happily coexist.</p>
<p>Th... | <p>You're trying to create a gapless sequence. There's lots of info about it out there. <a href="https://stackoverflow.com/questions/9984196/rails-postgres-does-not-re-use-deleted-ids-but-mysql-does/9985219#9985219">Here's an answer I wrote on the topic a while ago</a> and another <a href="https://stackoverflow.com/a/1... | sql|postgresql|concurrency|python-3.x | 2 |
7,268 | 14,264,819 | How to change colors of multiple widgets after hovering in Tkinter? | <p>I´m trying to make a script, which will change the background and foreground color of widgets after hovering. </p>
<pre><code>from Tkinter import *
root=Tk()
Hover1=Button(root,text="Red color", bg="white")
Hover1.pack()
Hover2=Button(root,text="Yellow color", bg="white")
Hover2.pack()
Hover1.bind("<Enter>... | <p>You need to provide a callable function to bind to the event. Instead you are calling a function and passing its result. Fix it like this:</p>
<pre><code>Hover1.bind("<Enter>", lambda event, h=Hover1: h.configure(bg="red"))
</code></pre> | python|colors|background|widget|tkinter | 4 |
7,269 | 14,307,816 | Live recognition with Python and Pocketsphinx | <p>I have recently been working with pocket sphinx in python. I have successfully got the
example below to work recognising a recorded wav.</p>
<pre><code>#!/usr/bin/env python
import sys,os
def decodeSpeech(hmmd,lmdir,dictp,wavfile):
"""
Decodes a speech file
"""
try:
import pocketsph... | <p>The code for realtime recognition looks like <a href="https://github.com/cmusphinx/pocketsphinx/blob/master/swig/python/test/continuous_test.py" rel="nofollow">this</a>:</p>
<pre><code>config = Decoder.default_config()
config.set_string('-hmm', path.join(MODELDIR, 'en-us/en-us'))
config.set_string('-lm', path.join(... | python|cmusphinx | 4 |
7,270 | 34,599,881 | how to do a url_for in flask restful using blueprints? | <p>code:</p>
<p>blueprint:</p>
<pre><code>from flask import Blueprint
from flask_restful import Api
################################
### Local Imports ###
################################
profile_api = Blueprint('profile_api', __name__)
api = Api(profile_api)
from .views import *
</code></pre>
<p>views:</p>
<pr... | <p>I've got the answer.</p>
<p>Apparently when working with <code>blueprints</code></p>
<p>the way to access <code>flask_restful's</code> <code>url_for</code> is</p>
<p><code>url_for('blueprint_name.endpoint)</code></p>
<p>meaning an endpoint has to be specified on the resource</p>
<p>so using the example above:</... | python|flask | 6 |
7,271 | 34,446,009 | Clean up the Python installation | <p>It seems that python can be found in three different places in my Mac OS. See below. Is there anything wrong? Should I and how can I clean up my python installation without reinstalling the OS? In fact, I recently experience some strange behavior when using Python.</p>
<pre><code>'/usr/local/Cellar/python/2.7.9/... | <p>What you need to do is update the paths in your .bashrc (or more likely <strong>.profile</strong> as you are on mac). This should be accessible from your home directory. ~/.profile and can be edited using nano.</p>
<p>You can then tell your terminal which set of libraries and version of python to use by adding the ... | python|macos|installation | 2 |
7,272 | 27,045,285 | Calling .Net function from IronPython [VS2012] | <p>I'm trying to call a .Net function from IronPython(VS-2012)</p>
<p><strong>.NET Function:</strong></p>
<pre><code>public int GetData(uint numberOfSamples, float[] iBuffer, float[] qBuffer){..}
</code></pre>
<p><strong>IronPython:</strong></p>
<pre><code># Here's my code in IronPython
numSamples = 1024
from array... | <p>You can pass an array of <code>floats</code> (which are <code>System.Single</code>) like this:</p>
<pre><code>iData = System.Array[System.Single]([1.0, 2.0, 3.0])
qData = System.Array[System.Single]([4.0, 5.0, 6.0])
GetData(numSamples, iData, qData)
</code></pre>
<p>EDIT: In case you would like to preallocate arra... | .net|arrays|ironpython | 2 |
7,273 | 41,745,514 | Getting the href of <a> tag which is in <li> | <p>How to get the href of the all the tag that is under the class <code>"Subforum"</code> in the given code?</p>
<pre><code><li class="subforum">
<a href="Link1">Link1 Text</a>
</li>
<li class="subforum">
<a href="Link2">Link2 Text</a>
</li>
<li class="subforum">
... | <p>The <code>href</code> belongs to <code>a</code> tag, not <code>li</code> tag, use <code>li.a</code> to get <code>a</code> tag</p>
<p>Document: <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#navigating-using-tag-names" rel="noreferrer">Navigating using tag names</a></p>
<pre><code>import bs4
html ... | python|web-scraping|beautifulsoup|html-parsing | 15 |
7,274 | 41,777,563 | Windows .exe created with cx_Freeze returns 0xc000007b error | <p>I created a small script to test cx_Freeze, shown below:</p>
<p><strong>sqrt.py:</strong></p>
<pre><code>import math
sqrt = math.sqrt
x = float(input('Enter a number:'))
y = sqrt(x)
print(y)
input('Press ENTER to exit')
</code></pre>
<p>I also created a setup script: </p>
<p><strong>setup.py:</strong></p>
<pre>... | <p>You can load the exe file created with cx_freeze with <a href="http://www.dependencywalker.com/" rel="nofollow noreferrer">dependencywalker</a>.</p>
<p>It will show you what's wrong.</p>
<p>Maybe you are missing a library like <a href="http://cx-freeze.readthedocs.io/en/latest/faq.html#microsoft-visual-c-redistrib... | python|cmd|cx-freeze | 1 |
7,275 | 47,118,050 | Tensorflow: GPU util big difference when setting CUDA_VISIBLE_DIVICES to different values | <p>Linux: Ubuntu 16.04.3 LTS (GNU/Linux 4.10.0-38-generic x86_64)</p>
<p>Tensorflow: compile from source, 1.4</p>
<p>GPU: 4xP100</p>
<p>I am trying the new released object detection tutorial training program.
I noticed that there is big difference when I set CUDA_VISIBLE_DEVICES to different value. Specifically, whe... | <p><a href="https://stackoverflow.com/a/40938696/4189580">As this answer mentions</a> GPU-Util is a measure of usage/business of the computation of each GPU.</p>
<p>I'm not an expert, but from my experience GPU 0 is generally where most of your processes run by default. CUDA_VISIBLE_DEVICES sets the GPUs seen by the p... | object-detection|tensorflow | 0 |
7,276 | 70,855,257 | Execute a condition of a class automatically, without opening the file, and take the print of the result to use it in another condition? | <p>I have 3 files which are executable as an example: main.py, Page1.py and External_Class.py. In External_Class.py I have <code>2 + 2 == 4</code> which corresponds to print("Ok"). While in the Page1.py file I have a textbox in which I would like to display "The results is ok" after clicking on the ... | <p>Printing has nothing to do with return values, and you can't get values you've printed back into variable form unless you do nasty stuff with your stdout.</p>
<p>You could use a method that will evaluate the condition and return the value.</p>
<pre class="lang-py prettyprint-override"><code>class New:
def __init... | python|python-3.x|class|if-statement|tkinter | 0 |
7,277 | 46,876,147 | How do I add pieces of lists together all at once and use a while statement to replace my 'if' statement? | <p>Right now I have each piece[] of the list individually converted to int() and then I add them together one by one. I know I'm using a very inefficient method and was hoping for some feedback on how I should go about cleaning this up. </p>
<p>The goal is to take a number like 123 and separating each digit and then a... | <p>You can do this arithmetically, but I think the easiest way to do it is by getting the string representation of the number and working with that. </p>
<pre><code>def sum_digits(n):
s = sum(int(c) for c in str(n))
if s > 9:
return sum_digits(s)
return s
</code></pre> | python|list|math|python-3.6 | 4 |
7,278 | 46,785,846 | Why Docker container images become so large while deploying Python 3.6, Virtualenv, Flask, Gunicorn on Ubuntu 16.04? | <p>While deploying the flask application within virtualenv <code>python3 -m venv FLSK-ENV</code></p>
<p>Dockerfile:</p>
<pre><code> FROM appcontainers/ubuntu:xenial
MAINTAINER user <user>
RUN apt-get install -y software-properties-common \
&& add-apt-repository ppa:jonathonf/pyt... | <p>Try the following Dockerfile, it gets the size of the image down to 255 MB. "--no-install-recommends" ensures that only the required packages are installed and "rm -rf /var/lib/apt/lists/*" cleans up including any index files.</p>
<pre><code>FROM appcontainers/ubuntu:xenial
RUN apt-get update \
&&a... | python-3.x|docker|flask|dockerfile|gunicorn | 4 |
7,279 | 46,967,387 | How do I find the key of a value in a dictionary that closest to, but not more than, a variable? | <p>Let's say I have a dictionary, d.</p>
<pre><code>d = {"x": 4, "r" : 9, "p" : 18, "v" : 20}
</code></pre>
<p>and I have a variable, i. How do I find the key of the value that's closest to, but not more than, i?</p>
<p>for example, if i is 5, the function would return "x", but if i is 19, the function would return ... | <p>Something like this would work:</p>
<pre><code>d = {'a': 2, 'b': 1, 'c': 4}
x = 2
# subtract from all values
for k, v in d.items():
d[k] = v - x
# get the key with the largest value
largest = max(d, key=lambda k: d[k])
</code></pre>
<p>Given you're applying an integer offset (subtraction in this case) to all... | python|dictionary | 0 |
7,280 | 38,006,472 | Deployment error in Python-Google App Engine | <p>when i deployed the demo application of python in Google App engine,it works well in local host,when i am deploying the got the error,i also changed proxy_rdns=True,but it does not work,help me to solve. </p>
<pre><code>File "C:\Program Files\Google\google_appengine\lib\httplib2\httplib2\__init__.py", line 1275, in... | <p>I had a similar problem today, when trying to run <code>appcfg.py</code> to deploy my app to appengine</p>
<p>I then downgraded my google epp engine sdk from 1.9.40 to 1.9.37, rerun, everything was Ok (note that I am using app engine sdk for ubuntu)</p>
<p>So you may try to upgrade/downgrade your version and check... | python|google-app-engine | 0 |
7,281 | 67,741,295 | Name dataframe sequentially and dynamically when opening from csv - Python/Pandas | <p>I have a list of .csvs - They have been named in a very uniform fashion, say, BMW_year i.e. BMW_60, BMW_61 ... BMW_70 ... BMW_00.. and so on. I want to pull them into a pandas dataframe - which I can do using a pd.read_csv(..) function.</p>
<p>But there are many .csvs and I was hoping to do something more on the lin... | <p>have not testet yet, but I would try something like</p>
<pre><code>for i in range(70, 80):
fpath = 'BMW_%d.csv' %i
vname = 'BMW_%d' %i
exec("%s = pd.read_csv(%s)" % (vname, fpath))
</code></pre> | python|pandas|dataframe|dynamic|naming | 1 |
7,282 | 30,034,883 | anchor reference to <tr> tag in reStructuredText (rst) | <p>I have a script that automatically builds tables in rst using the simplified syntax, for example:</p>
<pre><code>.. list-table::
:widths: 5, 32
:header-rows: 1
* - Name
- Default Value
* - numVar
- 515
* - stringVar
- "Hello World"
* - arrayVar
-... | <p>Found it. This is the right syntax:</p>
<pre><code>.. list-table::
:widths: 5, 32
:header-rows: 1
* - Name
- Default Value
.. _numVarRow:
* - numVar
- 515
.. _stringVarRow:
* - stringVar
- "Hello World"
.. _arrayVarRow:
* ... | html|python-sphinx|restructuredtext | 2 |
7,283 | 29,950,956 | DRF: Simple foreign key assignment with nested serializers? | <p>With Django REST Framework, a standard ModelSerializer will allow ForeignKey model relationships to be assigned or changed by POSTing an ID as an Integer.</p>
<p>What's the <em>simplest</em> way to get this behavior out of a nested serializer?</p>
<p>Note, I am only talking about assigning existing database object... | <h1>Updated on July 05 2020</h1>
<p>This post is getting more attention and it indicates more people have a similar situation. So I decided to add a <em><strong>generic way</strong></em> to handle this problem. This generic way is best suitable for you if you have more serializers that need to change to this format<br>... | python|django|django-rest-framework | 117 |
7,284 | 72,400,867 | Installing Python on iSH | <p>Not long ago my computer broke and I am stuck on an iPad. I installed iSH from the AppStore. Now I want to download Python and <strong>make sure <code>pip</code> works</strong>.</p>
<p>I have tried apk add python, which lead to the pip issue, but pip installing is important for me. I have also found other ways using... | <p>According information that you provided <code>iSH</code> using virtual environment with Alpine Linux x86 under the hood (I little bit simplify explanation, so it is not 100% correct. You can see details <a href="https://jsmp.me/2020/05/05/c-development-on-ios" rel="nofollow noreferrer">here</a>).</p>
<p>So if you wa... | python | 2 |
7,285 | 43,151,651 | beautifulsoup get images and google forms | <p>I am trying to parse the following site using beautiful soup:
<a href="http://www.rishikumar.com/intern.html" rel="nofollow noreferrer">http://www.rishikumar.com/intern.html</a></p>
<p>I am then trying to send the entire webpage starting after the word "Subject" as the body of an email. I eventually want to automa... | <p><code>Img url</code>: </p>
<p><a href="http://www.rishikumar.com/uploads/3/3/0/6/3306532/background-images/1586008872.png" rel="nofollow noreferrer">http://www.rishikumar.com/uploads/3/3/0/6/3306532/background-images/1586008872.png</a></p>
<p><code>Google form url:</code></p>
<p><a href="https://docs.google.com/f... | python|image|beautifulsoup|google-forms | 1 |
7,286 | 20,127,194 | Get a List of Project Specific Apps in Django | <p>Is there a way to get a list of all the project-specific apps in a Django project? settings.INSTALLED_APPS will give me a list of all apps I have installed, but that includes things like django.contrib.auth. I just want the apps I have generated using the createapp command. </p>
<p>As a follow up question, is there... | <p>There's no flag that keeps track of which apps are generated by <code>startapp</code>. However you can separate <code>INSTALLED_APPS</code> into two lists:</p>
<pre><code>APPS = [
'django.contrib.auth',
# ...
]
MY_APPS = [
'myapp1',
# ...
]
INSTALLED_APPS = APPS + MY_APPS
</code></pre>
<p>You can... | python|django | 5 |
7,287 | 4,388,323 | Python Regex to parse apart Blackberry browser user agent | <p>I need to parse apart blackberry browser user agents so I can get what device and version it is using python 2.5. For example:</p>
<pre><code>BlackBerry9630/4.7.1.65 Profile/MIDP-2.0 Configuration/CLDC-1.1 VendorID/-1,gzip(gfe),gzip(gfe)
</code></pre>
<p>In the above user agent I would like to gather the following... | <p>Something like this will work for your case, but not necessarily all cases:</p>
<pre><code>'^(\D*)(\d*)/(\d*)\.(\d*)\.'
</code></pre>
<p><code>\D</code> means "any character that's not a decimal digit", and <code>\d</code> means "any decimal digit".</p> | python|regex | 1 |
7,288 | 48,334,865 | How to disable screenshots and javascript for PhantomJS in python selenium? | <p>I am scraping in a python/selenium framework using phantomJS on windows. First, I tried to disable javascript and screenhsots with selenium:</p>
<pre><code>driver = webdriver.PhantomJS("phantomjs.exe", desired_capabilities = dcap)
webdriver.DesiredCapabilities.PHANTOMJS["phantomjs.page.settings.javascriptEnabled"] ... | <p>You have raised quite a few queries in your question. Let me try to address them all. A simple workflow with <code>Selenium v3.8.1</code>, <code>ghostdriver v1.2.0</code> and <code>phantomjs v2.1.1 Browser</code> shows us that the following <strong>Session.negotiatedCapabilities</strong> are passed by default :</p>
... | javascript|python|selenium|web-scraping|phantomjs | 1 |
7,289 | 51,493,095 | How to elegantly make a custom assertion error? | <p>I made a bunch of functions that control a message-based instrument. I know how to use them but the functions should be fool-proof in case somebody else wants to code with it after I'm gone. Here is an example function:</p>
<pre><code>def AutoRange(self, Function, Source, Value):
"""Enable or disable the instru... | <p>Why not do what Python does?</p>
<p>Let's see an example:</p>
<pre><code>open("foo", "q")
# => ValueError: invalid mode: 'q'
</code></pre>
<p><code>open</code> is in C, but you can see how it looks like for e.g <a href="https://github.com/python/cpython/blob/6f0eb93183519024cb360162bdd81b9faec97ba6/Lib/lzma.py... | python|python-3.x|function | 3 |
7,290 | 51,484,997 | Replace emdash with double dash | <p>I want to replace ― back into --
I tried with the utf8 encodings but that doesn't work</p>
<pre><code>string = "blablabla -- blablabla ―"
</code></pre>
<p>I want to replace the long dash (if there is one) with double hyphens. I tried it the simple way but that didn't work:</p>
<pre><code>string= string.replace (... | <p>You are dealing with strings here. Strings are lists of characters. Replace the <em>character</em>, leave the encoding out of the equation.</p>
<pre><code>string = 'blablabla -- blablabla \u2014'
emdash = '\u2014'
hyphen = '\u002D'
string2 = string.replace(emdash, 2*hyphen)
</code></pre> | encoding|special-characters|python-3.6 | 3 |
7,291 | 73,705,756 | How to open txt file when it appears? | <p>I have the following code:</p>
<pre><code>with open('id.txt') as file:
urls = iter([line.strip() for line in file])
</code></pre>
<p>During the program's running, I need this code to run only when a file <code>"id.txt"</code> appears in the program folder. How can I set a rule so that this code will onl... | <p>The simple approach is to poll the directory. That mean's list the contents of the directory and if you don't see the file, sleep for a little while, then look again.</p>
<p>The more sophisticated solution (on linux) is to use the inotify facility of the kernel and subscribe to changes in the directory. This is a th... | python | 1 |
7,292 | 17,536,916 | Python/Django: how to assert that unit test result contains a certain string? | <p>In a python unit test (actually Django), what is the correct <code>assert</code> statement that will tell me if my test result contains a string of my choosing?</p>
<pre><code>self.assertContainsTheString(result, {"car" : ["toyota","honda"]})
</code></pre>
<p>I want to make sure that my <code>result</code> contain... | <p>To assert if a string is or is not a substring of another, you should use <code>assertIn</code> and <code>assertNotIn</code>:</p>
<pre class="lang-py prettyprint-override"><code># Passes
self.assertIn('bcd', 'abcde')
# AssertionError: 'bcd' unexpectedly found in 'abcde'
self.assertNotIn('bcd', 'abcde')
</code></pr... | python|json|django|unit-testing|assert | 153 |
7,293 | 69,743,756 | Confusion Matrix Value error, y_test is not equal to y_train | <p>I've been trying to run a confusion matrix on a Logistic Regression result, i have splited the data so i have size 8 for y_test and 67 for y_train and i can't print the matrix. I know that they have to be the same size but i can't find a way to to that. ERROR MSG: <code>ValueError: Found input variables with inconsi... | <p>The confusion matrix takes as inputs y_true (the correct target values) and y_pred (Estimated targets as returned by a classifier). In this case y_true and y_pred would have for sure the same size, but you are trying to run it using both the predictions from the test and from the train, which doesn't make sense besi... | python|matrix | 0 |
7,294 | 50,226,332 | Matplotlib Filled In Step Graph for Weights | <p>I have a DataFrame that contains the history of weight values for N items. The sum of the weights for all items is 1. The date is when the weights were set, and they stay the same until they are set again.</p>
<p>Here is the Dataframe.</p>
<pre><code> item2 item3 item4 item1
2018-03-26 0.33... | <p>I figured it out, <a href="https://matplotlib.org/api/_as_gen/matplotlib.pyplot.fill_between.html" rel="nofollow noreferrer">fill_between</a> has a step option.</p>
<pre><code>tot = np.zeros(len(weight_history))
for weight in weight_history:
axes[1].fill_between(x=weight_history.index, y1=weight_history[weight]... | python|pandas|numpy|matplotlib | 1 |
7,295 | 50,120,062 | Cutting numpy array based on index | <p>I have a 1D <code>numpy</code> array. The difference between two succeeding values in this array is either one or larger than one. I want to cut the array into parts for every occurrence that the difference is larger than one. Hence:</p>
<pre><code>arr = numpy.array([77, 78, 79, 80, 90, 91, 92, 100, 101, 102, 103, ... | <p>One Pythonic way would be -</p>
<pre><code>np.split(arr, np.flatnonzero(np.diff(arr)>1)+1)
</code></pre>
<p>Sample run -</p>
<pre><code>In [10]: arr
Out[10]: array([ 77, 78, 79, 80, 90, 91, 92, 100, 101, 102, 103, 104])
In [11]: np.split(arr, np.flatnonzero(np.diff(arr)>1)+1)
Out[11]:
[array([77, 78... | python|arrays|numpy|optimization | 2 |
7,296 | 53,214,644 | JupyterLab: Run all cells below | <p>In the Jupyter Notebook I could use the following command to automatically execute all cells below the current cell.</p>
<pre><code>from IPython.display import Javascript
display(Javascript('IPython.notebook.execute_cells_below()'))
</code></pre>
<p>However, this doesn't seem to work with JupyterLab. How can I mak... | <p>It is built-in. Click the run menu at the top-left and select <code>"Run Selected Cell and All Below".</code></p>
<p><a href="https://i.stack.imgur.com/y0rsx.png" rel="noreferrer"><img src="https://i.stack.imgur.com/y0rsx.png" alt="enter image description here"></a></p> | python|python-3.x|jupyter-lab | 15 |
7,297 | 68,477,414 | how to extract 1st page after converting a pdf file to an image with subprocess.Popen | <p>I'm trying to convert pdf files to images, and I'm doing it with subprocess. Now I need a way to extract only the first page without having to convert all of the images. In this case, for example, I only need to convert "out-1.png."</p>
<p><a href="https://i.stack.imgur.com/quVm3.png" rel="nofollow norefer... | <p>After looking into the <code>'"%s" -png "%s" out'</code>, I discovered that I can pass extra parameters to get the first page.
The first parameter to pass is <code>-f <int></code> which specifies the first page to convert; however, you must also pass <code>-l <int></code> to specify t... | python|subprocess | 0 |
7,298 | 62,791,977 | How to properly send file through selenium in python | <p>I work with selenium 3.141.0 and chromewebdriver 83.0.4103 .
All the selenium libraries are proprerly imported and my script is working fine until i got this error.
I'm currently trying to upload a json file to an input :</p>
<pre><code><input type="file" class="file" id="ext-gen1563"... | <pre><code>def base(request):
if request.method=="GET":
return render(request, 'base.html')
else:
title = request. POST.get('title')
file = request.POST.get('file')
data = models.base(title=title,file=file)
data.save()
return render(request,'base.html')
... | python|selenium | 0 |
7,299 | 62,834,912 | Mapping dict of dict values to create new result | <p>I am working on dict of dict dataset :</p>
<pre><code>data = {'box_1': {'total_packets': 20,
'packet_loss': 0.32,
'network_loss': 0.11,
'full_packets': [0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 0, 1, 0, 1],
'full_network': [0.77118516, 0.15721157, 0.99284172, 0.64352685, 0.43893093,
0.9065064... | <p>Here is a simple solution:</p>
<pre><code>_DATA = {'box_1': {'total_packets': 20,
'packet_loss': 0.32,
'network_loss': 0.11,
'full_packets': [0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 0, 1, 0, 1],
'full_network': [0.77118516, 0.15721157, 0.99284172, 0.64352685, 0.43893093,
0.90650645, 0.313441... | python|list|algorithm|dataframe|dictionary | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.