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
6,700
52,682,585
How does keyword.iskeyword('if') works?
<p>I started the Python guides </p> <p>(<a href="https://www.techbeamers.com/python-keywords-identifiers-variables/#keywords-in-python" rel="nofollow noreferrer">https://www.techbeamers.com/python-keywords-identifiers-variables/#keywords-in-python</a>) </p> <p>and under the title <strong>"Testing If An Identifier Is ...
<p>This code is intended to be run from the interactive Python REPL:</p> <pre><code>me@host $ python Python 2.7.14+ (default, Mar 13 2018, 15:23:44) [GCC 7.3.0] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import keyword &gt;&gt;&gt; keyword.iskeyword('if') True </code>...
python|pycharm
2
6,701
47,668,564
Django Rest Framework: How to pass extra argument to django serializer?
<p>I have a variable named <code>email</code> in view.</p> <p>I want to access this in <code>ManageSerializer</code>.</p> <p>How can I pass this argument in serializer and get there?</p> <p><strong>views.py</strong></p> <pre><code>email = 'xyz@gmail.com' interviewData = Manage.objects. filter(catcher_id = user...
<p>Maybe pass it as kwargs: </p> <pre><code> ManageSerializers(interviewData, many = True, email= email) </code></pre> <p>You can access this in the init of the Serializer, using something like:<code>kwargs.pop('email')</code></p> <p>OR </p> <p>You can pass the context to the Serializer like this.</p> <pre><code> ...
python|django|serialization|django-rest-framework
6
6,702
37,500,369
peewee with bulk insert is very slow into sqlite db
<p>I'm trying to do a large scale bulk insert into a sqlite database with peewee. I'm using <code>atomic</code> but the performance is still terrible. I'm inserting the rows in blocks of ~ 2500 rows, and due to the <a href="https://stackoverflow.com/questions/35616602/peewee-operationalerror-too-many-sql-variables-on-u...
<p>Mobius was trying to be helpful in the comments but there's a lot of misinformation in there.</p> <ul> <li>Peewee creates indexes for foreign keys when you create the table. This happens for all database engines currently supported.</li> <li>Turning on the foreign key PRAGMA is going to slow things down, why would ...
python|performance|sqlite|database-performance|peewee
5
6,703
7,615,357
django querysets + memcached: best practices
<p>Trying to understand what happens during a django low-level cache.set() Particularly, details about what part of the queryset gets stored in memcached.</p> <p>First, am I interpreting the django docs correctly?</p> <ul> <li>a queryset (python object) has/maintains its own cache</li> <li>access to the database is l...
<p>Querysets are lazy, which means they don't call the database until they're evaluated. One way they could get evaluated would be to serialize them, which is what <code>cache.set</code> does behind the scenes. So no, this isn't a waste of time: the entire contents of your Tournament model will be cached, if that's wha...
python|django|django-cache
27
6,704
7,283,197
python multithreading synchronization
<p>I am having a synchronization problem while threading with cPython. I have two files, I parse them and return the desired result. However, the code below acts strangely and returns three times instead of two plus doesn't return in the order I put them into queue. Here's the code:</p> <pre><code>import Queue import ...
<blockquote> <p>I am threading because actually I will have to connect more than 10 places at a time and retrieve its results. I believe that threading is the most appropriate way to accomplish such a task</p> </blockquote> <p>Threading is actually one of the most error-prone ways to manage multiple concurrent conne...
python|multithreading|synchronization
2
6,705
39,645,396
Retrieve an ISO type date, convert into DateTime and find oldest date from a set of docs
<pre><code>{ id:ObjectID(12fgrh567d8vb9567890578192) . . . meta:{ 'date':ISO(1997-07-16T19:20:30.45+01:00) } } </code></pre> <p>I have this kind of about 500 documents, what I intend to do is define a function in using (pymongo) to retrieve the oldest date from all the docu...
<p>Use following query:</p> <pre><code>db.collectionname.find({}).sort({'meta.date': 1}).limit(1); </code></pre> <p>this will first sort all the documents with the meta date. and will return the oldest one.</p>
mongodb|python-2.7|pymongo
0
6,706
16,117,145
Output length mismatch in nested loops?
<p>I got a problem with the number of outputs from the loop.</p> <pre><code>neighbours=[]#this array will hold the distance to the k-th neighbour for i in range(0, len(selection)-1):#208 values in selection n2 =[]#this array will hold the distance to all the other 207 points for k in range(0, len(selecti...
<p>This line: </p> <pre><code>for i in range(0, len(selection)-1): </code></pre> <p>and</p> <pre><code>for k in range(0, len(selection)-1): </code></pre> <p>are probably the problems, <code>range</code> is exclusive of the stop parameter so the <code>- 1</code> is missing the last element. </p> <p>eg.</p> <pre><...
python|arrays|indexing|nested-loops
1
6,707
31,884,573
Django 1.7 Migrations hanging
<p>I have a django migration I am trying to apply. It gets made fine (it's small, it's only adding a <code>CharField</code> to two different Models. However when I run the actual migrate it hangs (no failure, no success, just sits).</p> <p>Through googling I've found that other open connections can mess with it so I...
<p>I was having this same problem today. I discovered that you can clear out any hanging transactions in PostgreSQL using the following SQL immediately before running your transaction:</p> <pre><code>-- View all the current activity -- SELECT * FROM pg_stat_activity; -- terminate other connections (make sure to add y...
python|django|database-migration
6
6,708
32,091,293
How to separate nested JSON
<p>I have a JSON data with structure like this:</p> <pre><code>{ "a":"1", "b":[{ "a":"4", "b":[{}], "c":"6"}] "c":"3" } </code></pre> <p>Here the key a is always unique even if nested.</p> <p>I want to separate my JSON data so that it should look like this:</p> <pre><code>{"a":"1" "b":[] "c"...
<p>I'd use an input and output stack:</p> <pre><code>x = { "a":1, "b":[ { "a":2, "b":[ { "a":3, }, { "a":4, } ] } ] } input_stack = [x] output_stack = [] while input_stack: # for the first element in the input stack front = input_stack.pop(0) b =...
python|json
4
6,709
38,598,300
systemd service audio output
<p>I want a python script started from a systemd service to output audio.</p> <p>I have a udev rule which starts a systemd service from a template. The template then starts a python script with two parameters (--device and the device path)</p> <p>multiupload@.service file:</p> <pre><code>[Unit] Description=Mutiuploa...
<p>Looks like some sort of permissions are needed for running the script since you are able to run it with logged in session. Can you please provide output of </p> <pre><code>systemctl status &lt;yourservicefilename&gt; </code></pre> <p>Also you can try setting <code>User=root</code> in your service file and provide ...
python|linux|python-3.x|systemd
0
6,710
10,021,570
Why I get 'dict' has no attribute 'sort' error in my concordance program in Python
<p>The task is to write a program which prompts for a filename and then produces a concordance of that file. Ex. A concordance is an alphabetical index that shows the lines in a document where each word occurs. For example, a concordance for this paragraph might appear as:</p> <pre><code>Word Line Number a ...
<p>I think it makes sense to use a dict, but you'll have to add a key along with each value you add to the dict. For example:</p> <pre><code>&gt;&gt;&gt; dict = {} &gt;&gt;&gt; dict["apple"] = "red" &gt;&gt;&gt; dict["banana"] = "yellow" &gt;&gt;&gt; dict {'apple': 'red', 'banana': 'yellow'} </code></pre> <p>In this...
python|python-2.7
3
6,711
63,111,948
Sink processed stream data into a database using Apache-flink
<p>Is it possible to sink processed stream data into a database using pyflink? All methods to write processed data are limited to save them in the txt, csv or Json formats and there is no way to sink data with database.</p>
<p>You could use SQL DDL within pyflink to define a JDBC table sink that you can then insert into. That will look something like this</p> <pre class="lang-py prettyprint-override"><code>my_sink_ddl = &quot;&quot;&quot; CREATE TABLE MyUserTable ( id BIGINT, name STRING, age INT, status BOOLEAN, PRIMARY KEY (id...
python|apache-flink|flink-streaming|pyflink
2
6,712
63,131,139
Python setuptools/pip packing data files into your package
<p>I have this git repo structure:</p> <pre><code>.gitignore JSONs/subdirA/some.json JSONs/subdirB/other.json MyPackage/__init__.py MyPackage/myModule.py </code></pre> <p>How do I properly pack the <code>JSONs</code> folder into <code>MyPackage/JSONs</code>, without moving it there permanently (mostly because customers...
<p>Something like the following could help:</p> <p>First we need to make sure that the <em>json</em> files are added to the <em>source distribution</em>.</p> <p><code>MANIFEST.in</code>:</p> <pre><code>recursive-include JSONs *.json </code></pre> <p>Then in the actual <em>setup</em> script, the list of <em>packages</em...
python|pip|setuptools
4
6,713
32,146,859
Conditionally pair list items in python
<p>I have a list like this:</p> <pre><code>[u'1.9', u'comment', u'1.11', u'1.5', u'another comment'] </code></pre> <p>I want to split it into tuples such that number strings (for which <code>isdigit(item[0])</code> is <code>True</code>) are paired with either the comment that comes immediately after them, or with an ...
<p>Your best bet is to use a generator function to do the pairing:</p> <pre><code>def number_paired(items): items = iter(items) number = next(items) while number is not None: comment = next(items, None) if comment is None or comment[0].isdigit(): # really a number, or end of the...
python|list|for-loop|list-comprehension
2
6,714
28,312,360
Finding the path for a Python module without importing it
<p>How can I find the path for a Python module without importing it?</p> <p>It seems like it should be obvious but I can't find a function to do this. (Yes I double-checked the docs for <code>imp</code>).</p> <p>Note: I can't import the module. Also this is a python2 specific issue, so I can't use <code>importlib.fi...
<p>Something like this maybe:</p> <pre><code>import imp print imp.find_module("mymodule") </code></pre>
python
0
6,715
44,013,915
Pygame code lags out with a flickering mouse
<p>So I'm trying to create a button that will simply set the background images(by blitting one over the other). But, I think this code should work:</p> <pre><code>place = True action = None def startup(action): while place == True: gameDisplay.blit(imgstr, (0, 0)) mouse = pygame.mouse.get_pos() click =...
<p>I have successfully solved the problem with the following code, if anyone was wondering:</p> <pre><code>import pygame pygame.init() screen = pygame.display.set_mode([852,441]) pygame.display.set_caption("test") keep_going = True mousedown = True background_image = pygame.image.load("start.jpg") main_img = pyg...
python|pygame|python-3.6
0
6,716
44,057,473
Icebreaker Game python
<p>I'm going to create a python game by using a modules called graphics. I have created a board with ice and I'm confusing how to create the position for the player in the beginning. link to the graphics modules: <a href="http://mcsp.wartburg.edu/zelle/python/graphics.py" rel="nofollow noreferrer">http://mcsp.wartburg....
<p>I don't know anything about the Icebreaker game but I'm hoping the additional logic I provided you below gives you enough to move forward:</p> <pre><code>from graphics import * COLUMN, ROW = 7, 10 WIN_W, WIN_H = 455, 320 WIN_SZ, GAP = 40, 5 COLORS = ['blue', 'white'] CIRCLE, RECTANGLE, COLOR = range(3) player...
python|zelle-graphics
1
6,717
14,341,549
Passing a set of NumPy arrays into C function for input and output
<p>Let's assume we have a C function that takes a set of one or more input arrays, processes them, and writes its output into a set of output arrays. The signature looks as follows (with <code>count</code> representing the number of array elements to be processed):</p> <pre class="lang-c prettyprint-override"><code>vo...
<p>To do this specifically with Numpy arrays, you could use:</p> <pre><code>import numpy as np import ctypes count = 5 size = 1000 #create some arrays arrays = [np.arange(size,dtype="float32") for ii in range(count)] #get ctypes handles ctypes_arrays = [np.ctypeslib.as_ctypes(array) for array in arrays] #Pack int...
python|c|numpy|ctypes|ffi
9
6,718
27,119,851
Can Python Generators be used in Django Views?
<h2>Question:</h2> <p>Essentially I want to return a unique result from the database everytime a view is called (until I run out of unique objects and have to start over). I was thinking that a simple and elegant solution would be to use a generator to handle this. Is this possible and if so how can this be approach...
<p>As Django is synchronous wsgi, you have to process each request as stand alone, your python environment can be killed or switched to an other at any time.</p> <p>Still if you have no fear and a single process, you can make a file scope dictionary with session ids and iterators that you'll consume each time</p> <pr...
python|django|django-views|django-orm
3
6,719
27,183,073
How to write a function to edit raw input in an array?
<p>I'm writing a program that takes the user input and saves it in an array. I'm currently trying to write a function that edits the data in the array. So far I have:</p> <pre><code>data = [] user_input = int(raw_input('How many Subject do you wish to add? : ')) for i in range (0, user_input): x = raw_input('Enter...
<p>From what I understood I have this code for you. </p> <pre><code>data = [] user_input = int(raw_input('How many Subject do you wish to add? : ')) for i in range (0, user_input): x = raw_input('Enter Subject: ') data.append(x) print(data) yes = 1 no = 2 print "would you like to add/remove any items in list"...
python|arrays|python-3.x|edit
-2
6,720
12,509,420
Regex for matching any occurrence of ABC following XYZ anywhere in the string
<p>I am trying to write a regular expression which would match any occurrence of ABC following XYZ anywhere in the string :</p> <p>Ex. text - "Some ABC text followed by XYZ followed by multiple ABC, more ABC, more ABC"</p> <p>i.e., the regex should match three ABC's coming after XYZ.</p> <p>Any clues?</p>
<p>Just match the literal <code>XYZ</code> and group on the repeated <code>ABC</code>:</p> <pre><code>r'XYZ((?:ABC)+)' </code></pre> <p>The <code>(?:ABC)+</code> pattern matches a set of literal characters at least once, and the whole group is preceded by a literal XYZ.</p> <p>This is quite basic regular expression ...
python|regex
1
6,721
23,009,664
CSV write multiple items in a single list in single csv field
<p>I have a multiple lists which i want to write in each csv field. One of the list contains multiple items. I want to write the items in that list in a single csv field. But i'm unable to do that.My code is:</p> <pre><code>def __init__(self): self.myCSV = csv.writer(open('office-ves_04112014.csv', 'wb'),dialect="...
<p>Your last argument to the csv writer sends it a list of items instead of a string. I'm guessing this is because you don't know how long the list will be. No problem: you are already sending it a list, so just add the two lists together, ideally after encoding all the elements of the second list:</p> <pre><code>def ...
python|csv|scrapy
1
6,722
1,058,986
Mule vs ActiveMQ for Python
<p>I need to manged several servers, network services, appalication server (Apache, Tomcat) and manage them (start stop, install software).</p> <p>I would like to use Python, since C++ seems to complex and less productive for thing task. In am not sure which middleware to use. ActiveMQ and Mule seem to be a good choic...
<p><strong>An example python "script" that manages various services on multiple remote servers:</strong></p> <p>What follows is a hacked together script that can be used to manage various services on servers that you have SSH access to.</p> <p>You will ideally want to have an ssh-agent running, or you will be typing ...
python|messaging
1
6,723
782,605
Implementing a 'function-calling function'
<p>I would like to write a bit of code that calls a function specified by a given argument. EG:</p> <pre><code>def caller(func): return func() </code></pre> <p>However what I would also like to do is specify optional arguments to the 'caller' function so that 'caller' calls 'func' with the arguments specified (i...
<p>You can do this by using <a href="http://docs.python.org/tutorial/controlflow.html#arbitrary-argument-lists" rel="nofollow noreferrer">arbitrary argument lists</a> and <a href="http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists" rel="nofollow noreferrer">unpacking argument lists</a>.</p> <pre...
function|functional-programming|python
12
6,724
47,200,625
How to make ttk.Scale behave more like tk.Scale?
<p>Several Tk widgets also exist in Ttk versions. Usually they have the same general behaviour, but use "styles" and "themes" rather than per-instance appearance attributes (such as <code>bg</code>, etc...). This is good, as the Ttk widgets take the "standard appearance" of the OS's window manager by default, without n...
<p>You can place in an automated way both the ticks and the label showing the value using <code>place</code> and their position x (in pixels) given by the formula:</p> <pre><code>x = ((value - start) / extent) * (width - sliderlength) + sliderlength / 2 </code></pre> <p>with:</p> <ul> <li><code>value</code>: the value ...
python|python-3.x|tkinter|ttk
5
6,725
47,437,716
Using "in" operator compare/convert a string to an int
<p>I need to find if an integer is found in a list of strings.</p> <p>context = ['4', '6', '78']</p> <pre><code>if category.id in context: </code></pre> <p>The code above is not working because I compare int(category id) with strings.</p> <p>I can't use int(context) because context is a list and will give an error....
<p>You could also consider using a list comprehension to convert <code>context</code> to a list of integers.</p> <pre><code>context_ints = [int(i) for i in context] if category.id in context_ints: ... do stuff ... </code></pre> <p>If <code>context</code> is guaranteed to be a list of strings that can sensibly be ...
python|python-3.x|for-in-loop
3
6,726
70,850,015
OSError: You seem to have cloned a repository without having git-lfs installed. Please install git-lfs and run git lfs install followed by git lfs pul
<p>I'm using Jupyter Labs on AWS SageMaker.</p> <p>Kernel: <code>conda_pytorch_p36</code> and did Restart &amp; Run All.</p> <p>I <code>git cloned</code> this <a href="https://huggingface.co/textattack/albert-base-v2-MRPC/tree/main" rel="nofollow noreferrer">repo</a>.</p> <p>Attempt at installing <code>git-lfs</code>:<...
<p>I've now <strong>installed and initialised GIT LFS in cloned folder</strong>.</p> <p>Terminal:</p> <pre><code>sh-4.2$ git lfs install Git LFS initialized. sh-4.2$ git clone https://huggingface.co/textattack/albert-base-v2-MRPC Cloning into 'albert-base-v2-MRPC'... remote: Enumerating objects: 27, done. remote: Count...
python|git|huggingface-transformers|git-lfs|oserror
0
6,727
33,533,251
Threading an endless while loop in Python 2
<p>I'm not sure why this does not work. The thread starts as soon as it is defined and seems to not be in an actual thread... Maybe I'm missing something.</p> <pre><code>import threading import time def endless_loop1(): while True: print('EndlessLoop1:'+str(time.time())) time.sleep(2) def endless...
<p>You need to give <code>target=</code> a <em>callable object</em>.</p> <pre><code>target=endless_loop1() </code></pre> <p>Here you're <em>actually calling</em> <code>endless_loop1()</code>, so it gets executed in your main thread right away. What you want to do is:</p> <pre><code>target=endless_loop1 </code></pre>...
python|multithreading|python-2.7
6
6,728
46,654,971
Adding rows in dataframe based on values of another dataframe
<p>I have the following two dataframes. Please note that 'amt' is grouped by 'id' in both dataframes.</p> <pre><code> df1 id code amt 0 A 1 5 1 A 2 5 2 B 3 10 3 C 4 6 4 D 5 8 5 E 6 11 df2 id code amt 0 B 1 9 1 C 12 10 </code></pre> <p>I wan...
<p>By using <code>pd.concat</code></p> <pre><code>df=df1.drop('code',1).drop_duplicates() df[~df.id.isin(df2.id)] pd.concat([df2,df[~df.id.isin(df2.id)]],axis=0).rename(columns={'amt':'name'}).reset_index(drop=True) Out[481]: name code id 0 9 1.0 B 1 10 12.0 C 2 5 NaN A 3 8 NaN D 4 11...
python|pandas|dataframe
3
6,729
46,765,425
Python 3.x - Mapping dictionary with multiple tuples as keys
<p>I have a dictionary containing multiple tuple as keys:</p> <pre><code>dictionary = {('Paris', 'Monaco', 'Marseille'): 'France', ('Milan', 'Juventus', 'Roma'): 'Italy', ('Manchester', 'Liverpool', 'London'): 'England'} </code></pre> <p>How to mapping list with lot of city names to the ...
<p>I suggest you flatten the dictionary keys. Duplicating values across keys isn't an issue:</p> <pre><code>dictionary = {k: v for tup, v in dictionary.items() for k in tup} </code></pre> <p>Then use the new dictionary to <em>easily</em> build your list:</p> <pre><code>countries = [dictionary[city] for city in lst] ...
python|list|dictionary|mapping
1
6,730
37,903,444
Advantages to implement LDA(latent dirichlet allocation) with tensorflow
<p>I wanted to implement LDA with tensorflow as a practice, and I think the tensorflow version may have the advantages below:</p> <ul> <li>Fast. If I can use the built-in ops to express the sampling process.</li> <li>Easy to parallelize. Many ops have been implemented with optimizations for parallelization, so this ld...
<p>There are many related answers to this on the broader question of how <a href="http://probabilistic-programming.org" rel="noreferrer">probabilistic programming</a> benefits from <a href="https://arxiv.org/abs/1701.03757" rel="noreferrer">deep probabilistic programming</a> systems.</p> <p>I can give one pointed answ...
tensorflow|lda
6
6,731
67,893,554
Keras ImageDataGenerator Predicts More Than The Prediction Set
<p>I am trying to make a CNN model that classifies American Sign Language. I already created and trained my model. Now I am trying to predict classes. My prediction set has 7250 unlabeled images however when I do the prediction, the model performs 587250 predictions while I need it to do 7250 predictions. I am providin...
<p>There is very limited documentation for predict_classes. It may not work if you are using a generator based on the documentation shown below</p> <pre><code>x: input data, as a Numpy array or list of Numpy arrays (if the model has multiple inputs). </code></pre> <p>so I do not think it works with a generator. So you ...
python|tensorflow|machine-learning|keras|conv-neural-network
0
6,732
43,150,921
SyntaxError: invalid syntax when opening a file
<pre><code>import re fhand = open('sum.txt','r') number = re.findall('[0-9]'+, fhand) print number </code></pre> <p>I am getting syntax error as</p> <pre><code> number = re.findall('[0-9]'+, fhand) ^ SyntaxError: invalid syntax </code></pre> <p>Not sure what's going on. Can anybod...
<p>Read the file contents and declare the entire pattern inside a string literal.</p> <p>Here is an example:</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; fhand = open(r'D:\2\_1.txt','r') &gt;&gt;&gt; fhand &lt;open file 'D:\\2\\_1.txt', mode 'r' at 0x0282B230&gt; &gt;&gt;&gt; number = re.findall('[0-9]+', fhand...
regex|python-2.7
1
6,733
43,170,283
python beautifulsoup attribute exist returns None
<p>when trying to select elements that have the attribute "data-server" it returns none here is the code</p> <pre><code>&gt;&gt;&gt; psoup.select_one(".server &gt; .serverslist") &lt;div class="serverslist " data-server="aHR0cDovL3d3dy5jbG91ZHkuZWMvZW1iZWQucGhwP2lkPWExYWU0NjkwZmZmYjQ="&gt;cloudy&lt;/div&gt; &gt;&gt;&...
<p>BeautifulSoup's CSS selectors are fairly limited. Attribute selectiors (<code>[...]</code>) can only be combined with a tag selector, not with other selectors (like the class selector you used):</p> <pre><code>&gt;&gt;&gt; from bs4 import BeautifulSoup &gt;&gt;&gt; psoup = BeautifulSoup( ... '&lt;div class="ser...
python-3.x|beautifulsoup
1
6,734
43,386,311
Turtle clashing with Tkinter
<p>I have to files: one is called curve, and the other one main. In main i am trying to open a button window, then whenever the button is pressed. it starts drawing something over in curve using turtle. This is the simplified script:</p> <p>main:</p> <pre><code> import tkinter master = tkinter.Toplevel() de...
<p>Since turtle is implemented with tkinter, you're walking a tightrope when you mix the two. This rework of your code seems to do what you describe, including the <code>bgpic()</code> call:</p> <p><strong>main.py</strong></p> <pre><code>import tkinter import turtle turtle.Screen() root = tkinter.Toplevel() def ca...
tkinter|python-3.4|turtle-graphics
0
6,735
37,030,067
Replace a double backslash with a single backslash in a string in python
<p>I know that variants of this topic have been discussed elsewhere, but none of the other threads were helpful.</p> <p>I want to hand over a string from python to sql. It might however happen that apostrophes (') occur in the string. I want to escape them with a backslash.</p> <pre><code>sql = "update tf_data set au...
<p>Simply don't.<br> Also don't concatenate sql queries as these are prone to sql injections.</p> <p>Instead, use a parameterized query:</p> <pre><code>sql = "update tf_data set authors=%(authors)s where tf_data_id=%(data_id)s" # or :authors and :data_id, I get confused with all those sql dialects out there authors...
python|str-replace|pymysql
6
6,736
20,338,425
sorting python heaps and lists
<p>I'm trying to do the following problem</p> <p>purpose: Implementation of the quicheSort algorithm (not in place), It first uses quickSort, using the median-of-3 pivot, until it reaches a recursion limit bounded by int(math.log(N,2)). Here, N is the length of the initial list to sort. ...
<pre><code> limit = float(log(len(lst),[2])) </code></pre> <p><code>[2]</code> is a 1-element list. Why are you making a 1-element list? You just want <code>2</code> here. I'd think maybe that was supposed to be mathematical notation for a floor, but flooring 2 doesn't make much sense either.</p>
python|list|sorting|heap
2
6,737
48,306,528
Python - socket.error: Cannot assign requested address
<p>I have written a chat server but I cannot bind my socket to an IP address:</p> <pre><code>import sys import os import socket HOST = "194.118.168.131" SOCKET_LIST = [] RECV_BUFFER = 4096 PORT = 9009 def chat_server(): server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.setsock...
<p>By checking <em>errno.h</em>, errno 99 is <em>EADDRNOTAVAIL</em>. The man page <em>bind(2)</em> says:</p> <blockquote> <p>EADDRNOTAVAIL A nonexistent interface was requested or the requested address was not local.</p> </blockquote> <p>It is often caused by a wrong IP address. You can use the command <em>ifconfi...
python|sockets|networking
8
6,738
48,190,020
Saving pytest logs in a file
<p>I've seen this question: <a href="https://stackoverflow.com/questions/24892396/py-test-logging-messages-and-test-results-assertions-into-a-single-file">py.test logging messages and test results/assertions into a single file</a> I've also read documentation here: <a href="https://docs.pytest.org/en/latest/logging.htm...
<p>You can use <code>--junit-xml=xml-path</code> switch to generate junit logs. If you want the report in html format, you can use pytest-html plugin. Similarly, you can use pytest-excel plugin to generate report in excel format. </p> <p>You can use tee to pipe logs to two different processes. example: <code>pytest --...
python|logging|pytest
2
6,739
51,243,809
How to find XPath for button within iframe using python?
<p>I have the following html object inside an iframe:</p> <p><a href="https://i.stack.imgur.com/pe3rZ.png" rel="nofollow noreferrer">html code for 'SUBMIT' button</a></p> <p>I need to find it's XPath in order to click on the "SUBMIT" button but cannot find it. XPath helper only shows "//iframe".</p> <p>So far, I've ...
<p>All content, which is inside a <code>frame</code> or <code>iframe</code> cannot be accesed without switching to <code>iframe/frame</code>. So firstly switch to <code>frame</code> content:</p> <pre><code>driver.switch_to.frame(driver.find_element_by_name("frame_name")) </code></pre> <p>or</p> <pre><code>driver.swi...
python|selenium|xpath
1
6,740
51,228,500
Removing empty strings from a re.findall command
<pre><code>import re name = 'propane' a = [] Alkane = re.findall('(\d+\W+)*(methyl|ethyl|propyl|butyl)*(meth|eth|prop|but|pent|hex)(ane)', name) if Alkane != a: print(Alkane) </code></pre> <p>As you can see when the regular express takes in propane it will output two empty strings. </p> <pre><code>[('', '', 'prop...
<p>You can use <code>str.split()</code> and <code>str.join()</code> to remove empty strings from your output:</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; name = 'propane' &gt;&gt;&gt; Alkane = re.findall('(\d+\W+)*(methyl|ethyl|propyl|butyl)*(meth|eth|prop|but|pent|hex)(ane)', name) &gt;&gt;&gt; Alkane [('', ''...
python|regex
1
6,741
69,682,127
How to find arc length / curve length reparameterization of b-spline curve?
<p>I'm trying to generate a quadratic b-spline curve from a set of controlpoints and a knot vector. How can I reparametrize the curve so that it is parameterized according to the arc / curve length? For example, if the curve is parameterized for t=0 to t=1, inputting t=0.2 should give the curve coordinate that occurs w...
<p>Unfortunately, what you are asking for <strong>cannot be done</strong> in general. A spline curve is a piecewise polynomial parametric curve and <a href="https://pages.mtu.edu/%7Eshene/COURSES/cs3621/NOTES/INT-APP/PARA-chord-length.html" rel="nofollow noreferrer">as noted for example here</a>:</p> <p><em>&quot;..it ...
python|curve|spline|bspline
2
6,742
73,122,752
How to get a json response with scrapy?
<p>I am trying to replicate this same block of code with scrapy's default request library as it faster and much more efficient. I am trying to retrieve data from the steamstore api:</p> <pre><code>import requests import json url = &quot;http://store.steampowered.com/api/appdetails/&quot; appid = 10 name = &quot;Counte...
<p>Actually, scrapy didn't know what's params? meaning it can't take params as parameter.So alternatively, you can do that is to inject the entire api url in scrapy Request method.</p> <p><strong>Example:</strong></p> <pre><code>import scrapy import json from scrapy.crawler import CrawlerProcess class TestSpider(scrapy...
python|json|python-requests|scrapy
1
6,743
73,272,102
How do I access binary data via python registry?
<p>The data in the registry key looks like:</p> <pre><code>Name Type Value Data REG_BINARY 60 D0 DB 9E 2D 47 Cf 01 </code></pre> <p>The data represent 8 bytes (QWORD little endian) filetime value. So why they chose to use binary rather than REG_QWORD is anyones guess.</p> <p>If the python 2.7 code I can see ...
<p>I figured out the type of the value64.value() was a 'str' so then I used simple character indexing to reference each of the 8 bytes and converted the value to a float.</p> <pre><code>def bin_to_longlong(binval): return ord(binval[7])*(2**56) + ord(binval[6])*(2**48) + ord(binval[5])*(2**40) + ord(binval[4])*(2**...
python-2.7|casting|registry|filetime
0
6,744
49,841,793
Increasing GitHub's X-Ratelimit-limit from 60 to 5000
<p>I'm trying to get bitcoin GitHub API using URLs with Python.</p> <p>There are numerous pages, but I can only access 60 pages in an hour so need to repeat it again and again. Is there any way to increase "X-RateLimit-Limit: 60" to 5000 (or else)?</p> <p>This is my Python code:</p> <pre><code>import urllib.request ...
<p>You'll need to <a href="https://developer.github.com/v3/#rate-limiting" rel="nofollow noreferrer">authenticate if you want to have a limit of 5000 requests per hour</a>:</p> <blockquote> <p>For API requests using Basic Authentication or OAuth, you can make up to 5000 requests per hour. Authenticated requests are ass...
python|api|github|bitcoin
0
6,745
61,917,907
Comparison Operator in Python Not Working as Expected
<p>I am working on getting more familiar with python. To do this I am working on a rock, paper, scissors game. I have a class to handle the comparison of the values to determine a winner. The trouble is whenever I do the comparison using an overloaded greater than operator, the result is wrong only when rock is involve...
<p>It's a simple issue: the comparison <code>if p1.value &gt; p2.value</code> compares the strings <code>"rock"</code>, etc. that are assigned in each <code>RcpValue</code> instance, so the <code>__gt__()</code> method is never being called.</p> <p>All you need to do is replace that line with <code>if p1 &gt; p2</code...
python|class|operator-overloading
1
6,746
61,881,569
use global reference inside nested functions
<p>I got an error at the while, that the name 'start' is not defined, although I declared it as global inside the nested one, I know that there is another approach is to changed the signature of the function of BS to take the start and end variables, but I need to know how to solve it using the global approach, Thanks!...
<p>Use <code>nonlocal</code>, so something like:</p> <pre><code>class math: def search(self,nums,x): start = 0 end = len(nums) def BS(): nonlocal start nonlocal end while(start&lt;=end): pass # use pass if you want to leave it empty! ...
python
5
6,747
60,359,157
ValueError: set_wakeup_fd only works in main thread on Windows on Python 3.8 with Django 3.0.2 or Flask 2.0.0
<p>When I run my Django Web application with Apache2.4.41 + Python 3.8.1 + Django 3.0.2 + MySQL 8.0.19 on Windows 10 Professional version it throws Value Error at /. set_wakeup_fd only works in main thread.</p> <p>This issue was a result of regression in Python 3.8 and was fixed in November in later builds of Python. F...
<p>I have exactly the same bug. I opened the <a href="https://github.com/django/asgiref/issues/143" rel="nofollow noreferrer">issue</a>.</p> <p>If you want to stay on the current Python version I have found the temporal solution which is to add following lines to <code>asgiref\__init__.py</code> (as it was suggested i...
python|django|flask|python-asyncio|asgi
4
6,748
70,076,938
Get the lines of txt file which not the first part or not exist in another file's lines in python
<p>I have two txt files and need to get the output in a new txt file :</p> <p>one file has the below (named f.txt):</p> <pre><code>interface Eth-Trunk50 interface Eth-Trunk51 interface Eth-Trunk60 interface Eth-Trunk60.2535 interface Eth-Trunk100 interface GigabitEthernet0/0/0 interface GigabitEthernet1/1/1 interface G...
<ol> <li><p>read all line from both files</p> </li> <li><p>remove the last <code>'\n'</code> of each line</p> </li> <li><p>check whether the line is valid, use a <code>valid</code> flag here :</p> </li> </ol> <ul> <li><p>initialize <code>valide</code> flag as 'True'</p> </li> <li><p>if any line is start with the checki...
python|txt
0
6,749
70,160,389
Code using to convert time is taking too long
<p>I have a dataframe as follows (reproducible data):</p> <pre><code>np.random.seed(365) rows = 17000 data = np.random.uniform(20.25, 23.625, size=(rows, 1)) df = pd.DataFrame(data , columns=['Ta']) 'Set index' Epoch_Start=1636757999 Epoch_End=1636844395 time = np.arange(Epoch_Start,Epoch_End,5) df['Epoch']=pd.DataF...
<p>You can use the <code>dt</code> (date accessors) to eliminate the loops:</p> <pre><code>df2 = df.copy() df2['date'] = df.index.values df2['date'] = pd.to_datetime(df2['date'], unit='s') df2['hour'] = df2['date'].dt.hour df2['fecha'] = df2['date'].dt.strftime('%Y%m%d') df2['dates'] = df2['date'].dt.strftime('%Y%m%d%...
python|pandas|datetime
1
6,750
70,218,098
Unexpected space inserted by readline
<p>I'm facing an issue when I try to read and print lines from two files. These files are similar but a space is always inserted in the second line printed. Of course no one exists in my files.</p> <pre><code>file1 = open(&quot;compare1&quot;, &quot;r&quot;) file2 = open(&quot;compare2&quot;, &quot;r&quot;) while 1: ...
<p>Each line within a text file implicitly ends with a newline (<code>\n</code>). When you are printing out <code>line1</code> and <code>line2</code>, it effectively becomes:</p> <pre><code>Salut je m'appelle Yohan\n Salut je m'appelle Yohan </code></pre> <p>Which outputs as</p> <pre><code>Salut je m'appelle Yohan Sal...
python|readline
1
6,751
63,716,198
Plotly/Dash callbacks called by dcc.Interval get backed up when the interval is more frequent than the time it takes for the callback to complete
<p>I want to make a callback to update the graph as quickly as is possible. I'm currently using <code>dcc.Interval(...)</code>.</p> <p>It commonly takes 1-3 seconds for the callback to compete (it updates the graph).</p> <p>If I set <code>dcc.Interval(id='myid', interval=1000)</code> then the callbacks happen too fast ...
<p>A plotly forum post addresses this question:</p> <p><a href="https://community.plotly.com/t/prevent-re-entrant-callbacks/17393" rel="nofollow noreferrer">https://community.plotly.com/t/prevent-re-entrant-callbacks/17393</a></p> <p>In summary, it uses the plotly exception <code>PreventUpdate</code> and <a href="https...
plotly|plotly-dash|plotly-python
0
6,752
65,977,705
Build list from dictionary values
<br> I have a dictionary which have key value pairs like: <pre><code>dict = {'a11': 1, 'a21': 0, 'a12': 1, 'a14': 2, 'a41': 1 . . . . . .. . 'a67':99, 'a23':98, 'a19':99} </code></pre> <p>all they key values are in form of a11, a12, a13 and so on and the values are from 0 to 99.</p> <p>Now from the dict, I want to bui...
<p>You can achieve this using <code>defaultdict</code>.</p> <pre class="lang-py prettyprint-override"><code>from collections import defaultdict container_dict = defaultdict(list) for key, value in my_dict.items(): container_dict[value].append(key) </code></pre> <p>The result is this, which you can access with the...
python|list|dictionary
0
6,753
59,359,057
Error converting tensorflow estimator to SavedModel
<p>I succesfully trained a TensowFlow boosted tree estimator. Now I want save it as a SavedModel. The problem is that I get the error below. <code>ValueError: All feature_columns must be _FeatureColumn instances. Given: [NumericColumn(key='fcoeffvariation_Result', shape=(1,), default_value=None, dtype=tf.float32, norm...
<p>You would need to convert your features into a format that Tensorflow can accept. Try to convert your columns into feature column before fitting the model. More info here: <a href="https://www.tensorflow.org/tutorials/structured_data/feature_columns" rel="nofollow noreferrer">https://www.tensorflow.org/tutorials/str...
python|tensorflow|tensorflow-estimator
0
6,754
63,059,482
I tried programming with Python Pillow, but I don't get my output image
<p>Following is the code and the output:</p> <pre><code>from PIL import Image mac=open(&quot;example.jpg&quot;) mac win=open(&quot;pencils.jpg&quot;) win </code></pre> <p><a href="https://i.stack.imgur.com/xB4qw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xB4qw.png" alt="enter image descripti...
<p>try <code>Image.open</code>. Your code is using the default <code>open</code> method from Python which is used to open any file.</p>
python|python-imaging-library
1
6,755
62,067,369
What is the hierarchy for Python module imports?
<p>Lets assume I have Python module in a directory and in the same directory I have a Python script that uses this module somehow.</p> <pre><code>wdir ├── module │   └── module_stuff └── script.py </code></pre> <p>If I execute this file in a python environment where the module is not installed everything works fine a...
<p>It seems to depend on <code>sys.path</code></p> <p>Quoting <a href="https://docs.python.org/3/tutorial/modules.html#the-module-search-path" rel="nofollow noreferrer">https://docs.python.org/3/tutorial/modules.html#the-module-search-path</a>:</p> <blockquote> <p>When a module named spam is imported, the interpreter f...
python
1
6,756
50,263,155
How do I display an extremly long image in Tkinter? (how to get around canvas max limit)
<p>I've tried multiple ways of displaying large images with tkinter<a href="https://i.stack.imgur.com/pGIbr.jpg" rel="nofollow noreferrer">really long image</a> No matter what I've tried, there doesn't seem to be any code that works. The main issue is that Canvas has a maximum height limit of around 30,000 pixels. </p>...
<p>This is a rather unattractive answer, but an answer non-the-less. This divides up extremely long images into "tiles" of 1000 pixel lengths. It does not divide the width. I've spliced together code from several sources until I got it all to work. If someone could make this with a scroll-bar functionality, that would ...
python|image|tkinter|tkinter-canvas
0
6,757
61,379,059
Why Django Query for Two DateTimeFields Equality Does Not Work?
<p>I have a model:</p> <pre class="lang-py prettyprint-override"><code>class Host(models.Model): create_date = models.DateTimeField(auto_now_add=True) update_date = models.DateTimeField(auto_now=True) </code></pre> <p>I would like to filter out all objects that have create_date.date() == update_date.date(), s...
<p>You can try the equality operation by using queryset constraint (Q objects)</p> <pre><code>Host.objects.filter(Q(create_date__date=F("update_date__date"))).count() </code></pre> <p>This should select all instances for which the date equals.</p> <p>Another workable solution would be to use both <code>gt</code> and...
python|django|django-models
0
6,758
53,947,017
How to run the same function in parallel with different arguments?
<p>I want to run the same function multiple times, each time with different arguments whilst using multithreading or multiprocessing. This is my code so far:</p> <pre><code>import threading import time def infiniteloop1(a): while True: print(a) time.sleep(1) thread1 = threading.Thread(target=in...
<p><code>threading.Thread(target=infiniteloop1('aaa'))</code> does not call <code>infiniteloop1</code> on a separate thread. </p> <p><code>threading.Thread</code>'s <code>target</code> argument should be a callable. Instead, <code>infiniteloop1('aaa')</code> evaluates (=calls) <code>infiniteloop1</code> even before <c...
python
5
6,759
53,901,718
Plot bar and line in same plot, different y-axes using matplotlib (no pandas)
<p>Data for bar chart:</p> <pre><code>sum_values = {2000: 258004, 2001: 243411, 2002: 234801, 2003: 231303, 2004: 235103, 2005: 234102, 2006: 236045, 2007: 262238, 2008: 317133, 2009: 337785, 2010: 379818, 2011: 425237, 2012: 446610} </code></pre> <p>Data for line chart:</p> <pre><code>avg_values = {'2006': 29034, '...
<p>The only problem is, that the keys in your barchart data are of type <code>string</code>. Besides that, you don't provide x values for your line plot, so <code>avg_values</code> is plotted simply over its indices.<br> So assumed you fix the data type issue, this code should work: </p> <pre><code>plt.figure(1, figs...
python|matplotlib|bar-chart|linechart
3
6,760
38,360,952
Playing audio on different devices?
<p>I have a USB headphones connected to system. So now my system has two different audio output devices (one internal speakers and other is USB headphone). Though it is possible t choose the default the output device. What i am interested is play different audio on each of the device at the same time. In other words i ...
<p>If you use <a href="http://python-sounddevice.readthedocs.io/en/latest/#sounddevice.play" rel="nofollow">sounddevice.play()</a>, you can simply specify the desired <code>device</code> with each call.</p> <p>You can either use the device ID (e.g. <code>device=3</code>) or a substring of the device name (e.g. <code>d...
audio|python-sounddevice
4
6,761
52,867,403
Heroku: App not compatible with buildpack:
<pre><code>Enumerating objects: 88, done. Counting objects: 100% (88/88), done. Delta compression using up to 8 threads. Compressing objects: 100% (40/40), done. Writing objects: 100% (88/88), 24.46 KiB | 6.12 MiB/s, done. Total 88 (delta 42), reused 88 (delta 42) remote: Compressing source files... done. remote: Build...
<p>It worked for me after adding requirements.txt and runtime.txt in the root folder of my Git Repo. Please make sure you have these files added.</p>
python|git|heroku
1
6,762
48,461,562
Snowboy and Python - when testing demo.py bash chooses wrong file directory?
<p>I'm trying to use the simple python demo.py snowboy.udml on bash and it constantly says it cant find my file - that's because the directory its suggesting doesn't exist - how can i change this on bash so it leads to the correct working directory with my demos inside it??</p>
<p>To move to your script directory just use the <code>cd</code> command:</p> <pre><code>cd directoryname </code></pre> <p>Otherwise, you can specify the path to the files like this:</p> <pre><code>python /path/demo.py /path/snowboy.udml </code></pre> <p>I can't say more because I'm not sure of what you're asking, ...
python
0
6,763
64,474,396
How do I turn this data from an SQL database table into a dict?
<p>The SQL table is simple, 3 columns.</p> <pre><code>id | guild | word </code></pre> <p><code>id</code> is just your usual db counter that I'm not interested in, the others are strings.</p> <p>Multiple <code>word</code>s belong to one <code>guild</code>, e.g.</p> <pre><code>1 | 5597 | egg 2 | 5597 | cheese 3 | ...
<p>You can use <a href="https://docs.python.org/3/library/collections.html#collections.defaultdict" rel="nofollow noreferrer">defaultdict</a> and iterate on the cursor directly</p> <pre><code>d = defaultdict(list) for row in c: d[row[0]].append(row[1]) </code></pre> <p>To make it more readable change the loop to</p...
python|sqlite|dictionary
2
6,764
70,386,188
cannot parse datetime in pandas dataframe
<p>Column Name: dateAdded</p> <p>format: 2017-03-03T16:56:05Z</p> <p>I am trying this code</p> <pre><code>df = pd.read_csv ('amazon.csv') df['dateAdded'] = pd.to_datetime(df['dateAdded'], format= '%Y-%d-%mT%H:%M:%S%Z') </code></pre> <p>Error:</p> <blockquote> <p><strong>time data '2017-03-03T16:56:05Z' does not ma...
<p><code>Z</code>, or <code>Military Time</code> is not supported in <code>Datetime</code>. The solution is to either remove the <code>Z</code> or replace it with <code>+00:00</code>. Your code becomes:</p> <pre><code>df['dateAdded'] = pd.to_datetime(df['dateAdded'].rsplit('Z', 1)[0], format= '%Y-%d-%mT%H:%M:%S') ...
python|pandas|dataframe
0
6,765
66,348,861
Grouping lines in a text file using python
<p>I have a huge set of data that im trying to analyze (the data is in a text file)</p> <p>heres an example:</p> <pre><code>0000:name=max age=19 grade= 90 hair color= brown eyes color= blue end 0001:name=jack age=18 grade= 91 hair color= black eyes color= blue end 0002...
<p>Is this want you want?</p> <pre><code>import pandas as pd with open(&quot;file.txt&quot;) as f: lines = [ line.strip().rsplit(&quot;=&quot;)[-1].strip() for line in f.readlines() if line.strip() != &quot;end&quot; ] pd.DataFrame( [lines[i:i + 5] for i in range(0, len(lines), 5)]...
python|text
0
6,766
66,363,833
How To Fix or Clean Corrupted JSON Files
<p>I have a corrupted JSON file for a public tweet as such:</p> <pre><code>&quot;{\&quot;created_at\&quot;:\&quot;Thu Feb 25 05:05:41 +0000 2021\&quot;,\&quot;id\&quot;:1364803731678715907,\&quot;id_str\&quot;:\&quot;1364803731678715907\&quot;,\&quot;text\&quot;:\&quot;\\u201cMe solta crlh\\u201d\&quot;,\&quot;source\&...
<p>If what you mean is that you've accidentally saved a <code>repr()</code> of the JSON into a file, you can un-<code>repr()</code> it with <code>ast.literal_eval()</code>:</p> <pre><code>import ast import json file = ... json_string = ast.literal_eval(file.read()) json_data = json.loads(json_string) assert isinstance...
python|json|twitter
0
6,767
64,788,026
Can't open and read content of an uploaded zip file with FastAPI
<p>I am currently developing a little backend project for myself with the Python Framework FastAPI. I made an endpoint, where the user should be able to upload 2 files, while the first one is a zip-file (which contains X .xmls) and the latter a normal .xml file.</p> <p>The code is as follows:</p> <pre><code>@router.pos...
<p>This is a <a href="https://bugs.python.org/issue26175" rel="nofollow noreferrer">known Python bug</a>:</p> <blockquote> <p>SpooledTemporaryFile does not fully satisfy the abstract for IOBase. Namely, <code>seekable</code>, <code>readable</code>, and <code>writable</code> are missing.</p> <p>This was discovered when ...
python|api|rest|multipartform-data|fastapi
4
6,768
63,917,111
Inverse logarithmic scale [0,0.9,0.99,0.999]
<p>I'm trying to plot the equivalent of a <a href="http://hdrhistogram.org" rel="nofollow noreferrer">hdrhistogram</a>, to analyse some latency data, however it seems non-trivial to do so since it requires what is essentially the inverse of a logarithmic scale.</p> <p>I.e what I am trying to get is a scale that has tic...
<p>There is no easy way to do this in Altair, because it's not supported in Vega (see the two-year-old feature request here: <a href="https://github.com/vega/vega/issues/1277" rel="nofollow noreferrer">https://github.com/vega/vega/issues/1277</a>)</p> <p>But you can hack around it by transforming your data, using a sta...
python|altair|vega-lite|vega
2
6,769
63,807,110
Scrape clickable link or xpath
<p>I have this html tree in a web app: <a href="https://i.stack.imgur.com/HCLec.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HCLec.png" alt="enter image description here" /></a></p> <p>I have scraped all the text for all the league names.</p> <p>But I also need a XPATH or any indicator so that I c...
<p><code>li</code> node doesn't have <code>text</code>, <code>href</code> or <code>xpath</code> (I don't think its a valid HTML attribute). You can scrape and parse <code>@style</code>.</p> <p>Try to use this approach to extract background-image URL</p> <pre><code>leagues.append(xpath.get_attribute('style').strip('back...
python|selenium|xpath|web-scraping|linked-list
1
6,770
63,952,211
Print value at a specific id() in Python?
<p><em>(The idea is simple but I don't know if it is possible or how to do it in Python)</em> Like:</p> <pre><code>x = 5 y = id(x) print(#value_at_y) </code></pre> <p>print should return <em><strong><code>5</code></strong></em>, which is the value at address y i.e. id(x)</p>
<p>You must use a dictionary. See below:</p> <pre><code>y={} </code></pre> <p>for each x add x and its id(x) to y, like below:</p> <pre><code>y[x]=id(x) </code></pre> <p>And you can call them later with</p> <pre><code>y[x] </code></pre>
python|pointers|memory-address
1
6,771
53,041,173
How do I keep track of Python enum values internally?
<p>My end goal really is to create a helper method in my Enum class that always returns an Enum member and never raises an exception, given whatever possible value, e.g.</p> <pre><code>Color.from_value('red') </code></pre> <p>In case the value is not part of the enum, the helper method will return a default one, say ...
<p>You can create the method and check for the values in the class:</p> <pre><code>import enum class Color(enum.Enum): RED = 'red' BLUE = 'blue' GREEN = 'green' UNKNOWN = "unknown" @classmethod def from_value(cls, value): try: return {item.value: item for item in cls}[value] ...
python|python-3.x|enums
2
6,772
68,575,172
How to correctly use colormaps for plotly express line mapbox?
<p>I have trouble getting <code>plotly.express.line_mapbox()</code> present the lines with correct colors. The lines have a value 0..100%, which represents the usage of each line. From other SO questions and websites I am approaching it like this:</p> <pre><code>norm = matplotlib.colors.Normalize(0, 100) colors = [[nor...
<p>So i managed to solve my problem and would like to share my findings, in case anyone stumbles on this question. Here you find the <a href="https://plotly.com/python-api-reference/generated/plotly.express.line_mapbox.html#plotly.express.line_mapbox" rel="nofollow noreferrer">docs</a>.</p> <p><strong>TL;DR</strong> an...
python|express|plotly|mapbox|colormap
1
6,773
61,625,316
How do I execute options within loops - Python?
<p>I am new with Python and I am trying to get my code to run properly but I've been googling all day and cant find the fix. I am hoping someone can help me. I have my code (see below) and when I run it, It goes well until I select the option to add a transaction. Once I add my transaction amount, and choose any numbe...
<p>You've got an issue here. There is a typo in your spelling of valid in get_transaction_value().</p> <pre><code>if not verify_chain(): &lt;ipython-input-2-358b629c0a68&gt; in verify_chain() 33 break 34 index += 1 ---&gt; 35 return valid 36 37 tx_amount = get_transaction_...
python|for-loop|while-loop
1
6,774
67,307,943
Web Scraping Selenium and Beautiful soup - unable to export into csv file
<p>I am trying to web scrape the data (price + brand) from this website. The code actually works but I can only see the data on my sublime text editor and cannot convert it into a CSV file. Additionally, I get this error message:</p> <pre><code>AttributeError: 'NoneType' object has no attribute 'div' </code></pre> <p>H...
<p>To get items from second page, replace <code>#</code> in URL for <code>?</code>:</p> <pre><code>import requests import pandas as pd from bs4 import BeautifulSoup url = &quot;https://www.yoox.com/de/damen/kleidung/shoponline/michael%20kors_md?/Md=403&amp;d=10321&amp;dept=clothingwomen&amp;gender=D&amp;page=2&amp;se...
python|selenium|web-scraping|beautifulsoup|export-csv
1
6,775
67,448,435
How do i get the text boxes to fit the text inside it
<p>I im using Tkinter to create a simple interface however I cant get the boxes to fit to the size of the text inside them when I use the insert function</p> <pre><code>root = Tk() sub_name = Entry(root) num = Entry(root) search_type = Entry(root) flair_name = Entry(root) comments = Entry(root) sub_name.insert(0,&quot...
<p>Does this work for you?</p> <pre><code>sub_name = Text(root) num = Text(root) search_type = Text(root) flair_name = Text(root) comments = Text(root) sub_name.insert(‘end’,&quot;Enter the name of a subreddit&quot;) num.insert(‘end’,&quot;enter how many posts you want to check for a specific flair”) search_type.insert...
python|tkinter
0
6,776
67,424,309
How to reset\reload env variable when using pytest parametrize?
<p>I got the following project</p> <pre><code>project │ README.md │ │ └───workers │ └───func │ │ func.py │ └───tests │ └───__init__,py │ └───func │ │ test_foo.py </code></pre> <p>func.py :</p> <pre><code>import os AUTH_DOMAIN = os.getenv(&quot;AUTH_DOMAIN&quot;) assert AUTH_DOMAIN def ...
<p>Looks like you can find answer here: <a href="https://stackoverflow.com/questions/1254370/reimport-a-module-in-python-while-interactive">Reimport a module in python while interactive</a>. You can reload module using <code>reload</code> function in python</p>
python-3.x|pytest
0
6,777
67,481,891
how to use multiprocessing inside class have to attribute are object and dict?
<p>I have a class:</p> <pre><code># myclass.py class MyClass(object): def __init__(self,*args): self.env = args[0] self.mydict = args[1] def run(self): list_data = [1,2,3,4,5,6,7,8,9,10] pool = mp.Pool(3) for _ in tqdm(pool.imap_unordered(self.exefunction, list_data), t...
<p>Each process runs in its own address space and therefore needs its own DB connection pool. So:</p> <ol> <li>Class <code>MyEnv</code> should not explicitly call method <code>create_pool</code> from its <code>__init__</code> method; this pool-creation needs to be postponed until later.</li> <li>Each process in the mul...
python|python-3.x|class|multiprocessing
0
6,778
60,668,676
Python: get previous list entry(relative to a variable assigned to a current list position)
<p>I am putting together a very simple text-based game in Python which contains 5 rooms that the player can move between. </p> <p>The player starts in the central room, gameMap[2]. </p> <p>Below is the code that provides the player's location. </p> <pre><code>gameMap = ['room0','room1','room2','room3','room4'] play...
<p>What you can do in this case is have a variable which is used as the point in which the player is at; for example:</p> <p><code>current = 0</code></p> <p>then do whatever calculations you must and call <code>playerLocation = gameMap[current]</code></p> <p>If you wanted to go back a level, you can just do:</p> <p...
python|list|iterable
1
6,779
71,285,856
How to correct subplot image size with colorbars in matplotlib python?
<p>I want to make a 3x2 subplot image in python. With the images in third row I have added a colorbar. But it the image size gets small as compared to the top rows. Is there anyway to fix the image size the same as of top two rows while having a colorbar in the third row?</p> <p>Here's my python code</p> <pre><code>#Im...
<p>Matplotlib steals space from the host axes. However, you can specify more than one axes to steal space from. So above you can easily do:</p> <pre class="lang-py prettyprint-override"><code>import matplotlib.pyplot as plt import numpy as np import matplotlib as mpl fig, axs = plt.subplots(3, 2) for ax in axs.flat: ...
python|image|matplotlib|jupyter-notebook|colorbar
0
6,780
70,305,935
Python function to get a JSON value based on optional number of arguments
<p>How can I create python function which is able to get specific value from json based on provided arguments? The number of provided arguments should be optional as I cannot know in advance how deep into the json structer I will need to go for the value.</p> <pre><code> def json_get_value(respond, *args): ...
<p>A possible solution is to use your variable <code>value</code> to keep the current level in the JSON tree in which you are:</p> <pre class="lang-py prettyprint-override"><code>try: value = my_json for arg in args: value = value[arg] return value except KeyError: return &quot;None&quot; </cod...
python|json|function|args
1
6,781
70,538,830
Split a string with bracketed elements
<p>I am solving a problem from codewars and I'm stuck on a step</p> <p>I have a strings like this <code>defr[fr]i##abde[fgh]ijk</code> and i want add separatar between element ,but that should be the case for elements inside brackets , so the output should be <code>[d,e,f,r,[fr],i,#,#,a,b,d,e,[fgh],i,j,k]</code></p> <...
<p>Here is the working code</p> <pre><code>str = &quot;defr[fr]i##abde[fgh]ijk&quot; arr = [] in_the_bracket = False for i in str: if i == '[': in_the_bracket = True chr = '' if in_the_bracket: chr = chr + i else: arr.append(i) if i == ']': in_the_bracket = False...
python|python-3.x|string|list|split
0
6,782
55,924,094
Decompose a list of integers into lists of increasing sequences
<p>Assume no consecutive integers are in the list.</p> <p>I've tried using NumPy (<code>np.diff</code>) for the difference between each element, but haven't been able to use that to achieve the answer. Two examples of the input (first line) and expected output (second line) are below.</p> <pre><code>[6, 0, 4, 8, 7, 6] ...
<p>You could use <a href="https://docs.python.org/3/library/itertools.html#itertools.zip_longest" rel="nofollow noreferrer"><code>itertools.zip_longest</code></a> to enable iteration over sequential element pairs in your list along with <code>enumerate</code> to keep track of index values where the sequences are not in...
python
4
6,783
69,771,753
How do I strip data from a row in Pandas?
<p>I have a Pandas dataframe and I need to strip out components.schema.Person.properties and just call it id.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">column</th> <th>data_type</th> <th>data_description</th> </tr> </thead> <tbody> <tr> <td style="text-align:...
<p>Like this?</p> <pre class="lang-py prettyprint-override"><code>df['column'] = df['column'].apply(lambda x: x.split('.')[-1]) </code></pre> <p>or more compact <a href="https://stackoverflow.com/questions/69771753/how-do-i-strip-data-from-a-row-in-pandas#comment123329869_69771753">solution by @Chris Adams</a>:</p> <pr...
python|pandas
1
6,784
17,901,341
Django - How to make a variable available to all templates?
<p>I would like to know how to pass a variable to all my templates, without repeating the same code on every method in my views.py file? </p> <p>In the example below I would like to make categories (an array of category objects) available to all templates in the web app.</p> <pre><code>Eg: I would like to avoid writi...
<p>What you want is a context processor, and it's very easy to create one. Assuming you have an app named <code>custom_app</code>, follow the next steps:</p> <ul> <li>Add <code>custom_app</code> to <code>INSTALLED_APPS</code> in <code>settings.py</code> (you've done it already, right?);</li> <li>Create a <code>contex...
python|django|django-nonrel
146
6,785
17,891,443
How to delete everything after a certain character in a string?
<p>How would I delete everything after a certain character of a string in python? For example I have a string containing a file path and some extra characters. How would I delete everything after .zip? I've tried <code>rsplit</code> and <code>split</code> , but neither included the .zip when deleting extra characters.<...
<p>Just take the first portion of the split, and add <code>'.zip'</code> back:</p> <pre><code>s = 'test.zip.zyz' s = s.split('.zip', 1)[0] + '.zip' </code></pre> <p>Alternatively you could use slicing, here is a solution where you don't need to add <code>'.zip'</code> back to the result (the <code>4</code> comes from...
python|string|character|python-3.3
21
6,786
60,868,404
find specific string in spark sql--pyspark
<p>Im trying to find an exact string match in a dataframe column from employee dataframe</p> <pre><code>Employee days_present Alex 1,2,11,23, John 21,23,25,28 </code></pre> <p>Need to find which employees are present on 2nd based on days_present column expected output: Alex</p> <p>below is what i have tri...
<p>We can use <strong><code>array_intersect</code></strong> function starting from Spark-2.4+ and then check the array size if <strong><code>size &gt;=2</code></strong></p> <p><strong><code>Example:</code></strong></p> <pre><code>df.show() +--------+------------+ |Employee|days_present| +--------+------------+ | A...
pandas|apache-spark|pyspark-sql
2
6,787
66,174,906
Pre-commit not finding python packages
<p>Im using <em>pyenv</em> to support having different versions of python.</p> <p>In a project using python <strong>3.7</strong> I also want linting with <strong>pre-commit</strong> to run when doing code changes.</p> <p>But when the lint rules run, pre-commit seem to be looking in a cache folder under the user for pyt...
<p>pre-commit installs isolated environments for each of the tools such that they don't interfere with local development. It sounds like you're missing dependencies in that environment</p> <p>Running <code>pip install</code> inside the cache environments is very not supported and you are likely to break pre-commit by ...
python|pyenv|pre-commit|pre-commit.com
7
6,788
68,927,807
CSV file: Change the position of column to row and reorganize dataset
<p>INTRODUCTION: I have a CSV file (<a href="https://gitlab.com/sysuin/datasets/-/blob/main/fossil-fuel-input.csv" rel="nofollow noreferrer">fossil-fuel-input.csv</a>) that contains the data on fossil fuels utilization by country and year. The layout of data (order of rows and columns) in this CSV is not in a proper wa...
<p>You can do this with pandas by creating a pivot table:</p> <pre><code>import pandas as pd df = pd.read_csv('https://gitlab.com/sysuin/datasets/-/raw/main/fossil-fuel-input.csv?inline=false') df = df.pivot_table(values='Fossil Fuels (TWh)', index='Entity', columns='Year', aggfunc='first') df.to_csv('output.csv') </co...
python|excel|csv
2
6,789
62,196,759
Youtube + Selenium ChromeDriver (Python) - How to loop youtube video?
<p>Already searched related questions but can't get solution.</p> <p>How to use Python Selenium ChromeDriver to loop Youtube video?</p> <p>Thanks a lot!</p>
<p>It MIGHT be useful for your purposes since it's not quite clear.</p> <p>Once the video starts playing, right-click on the video screen and selects the option <code>Loop</code>.</p> <p>As follows: <a href="https://giphy.com/gifs/xUSGPLMaJQaEnkcwTR/html5" rel="nofollow noreferrer">https://giphy.com/gifs/xUSGPLMaJQaEnk...
python|selenium|loops
0
6,790
62,386,150
groupby by many columns in pandas and add it into one dataframe
<p>I have a dataframe that I made from stackoverflow survey 2018 and 2019. I have a column that is the salary for this specific respondent and I call it 'usd' and many columns of programming languages names - c,c++,c#, etc - 43 of them, so total 44 columns - 1 is salary and the others are programming languages. Each ro...
<p>Here you go.. you have to group them by the language column value and take the mean of the 'usd' column</p> <p>Sample dataset:</p> <pre><code> usd java python c 0 10 1 0 1 1 20 0 1 1 2 30 1 1 0 3 40 0 0 1 4 50 1 1 0 </code></pre> <p>Code</p> <pr...
pandas
0
6,791
59,678,348
Encrypt with CryptoJS, decrypt with PyCrypto (adjusting CryptoJS to PyCrypto defaults)
<p>I am trying to decrypt on CryptoJS and encrypt in PyCrypto.</p> <p>I saw <a href="https://stackoverflow.com/questions/36762098/how-to-decrypt-password-from-javascript-cryptojs-aes-encryptpassword-passphras">this</a> excellent answer which works like charm, the only problem is that it adjusts PyCrypto to work with C...
<ul> <li><p>On the CryptoJS-side, key and IV must be passed as <code>WordArray</code>-objects <a href="https://cryptojs.gitbook.io/docs/#the-cipher-input" rel="nofollow noreferrer">[1]</a>. CryptoJS provides encoders for the conversion of strings into <code>WordArray</code>-objects and vice versa <a href="https://crypt...
javascript|python|aes|cryptojs|pycrypto
2
6,792
59,808,194
Load Media Files in Django
<p>I'm trying to create a home media server using Django. For this I want it to be in such a way that my media files are stored in an external USB. Now from my code when I try to load the video, it doesn't work. I even tried hard coding a path to see if it works. When I run through Django, It doesn't work but when I di...
<p>If you post your settings.py it will be helpful in determining your problem.</p> <p>You are trying to serve static media from your Django project. You need to properly specify which directory you want to use as your media root, i.e. your USB drive. Additionally I don't see any non-trivial way to enable the django a...
python|html|django|python-3.x
1
6,793
59,707,906
how save or extract Attachments file from MSG file with python?
<p>How can I download,save or extract Attachments file from MSG file in python? There is so many Library for extract sender name or ... but for extract msg files not working.</p>
<p>For extract files from MSG files of Outlook use this code:</p> <pre><code>import win32com.client,os outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI") msg = outlook.OpenSharedItem('C:/Users/aa/test.msg') for att in msg.Attachments: print(att.FileName) print(msg.Attachmen...
python|outlook|attachment|email-attachments
0
6,794
59,823,495
INFO:tensorflow:Error reported to Coordinator: <class 'tensorflow.python.framework.errors_impl.InvalidArgumentError'>, 2 root error(s) found
<p>I am trying to run a object detection model using tensorflow objection detection API. My purpose for running object detection is trying to solve captcha problem using object detection. I following the one tutorial for that. System configuration: virtual machine on Azure GPU - nivida tesla k80 RAM - 56 tensorflow ver...
<p>You get this error when the tensors passed to <code>tf.concat</code> are of different dimensions. Below is the code to reproduce the error you are facing.</p> <p><strong>Code to reproduce the error -</strong></p> <pre><code>import tensorflow as tf t1 = tf.constant([[1, 2, 3], [4, 5, 6]]) t2 = tf.constant([[7, 8, 9...
python|tensorflow|gpu|faster-rcnn
0
6,795
70,857,710
Iterate through directory and return DataFrame with number of lines per file
<p>I have a directory containing several excel files. I want to create a DataFrame with a list of the filenames, a count of the number of rows in each file, and a min and max column.</p> <p>Example file 1:</p> <p><a href="https://i.stack.imgur.com/M1YoD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.co...
<p>You're using <code>str</code> wrong. It is a function in Python, but you don't need it at all. Here, you just mean to write <code>file.startswith</code>. Now, to store the data, at each iteration you'll want to append to a list. What you can do is use dictionaries to create the data:</p> <pre><code>import pandas as ...
python|pandas|dataframe
2
6,796
60,283,116
GroupBy and Change the values of one columns
<p><a href="https://i.stack.imgur.com/DhasS.png" rel="nofollow noreferrer">dataframe</a></p> <p>Hi dear coders, I need help from you as I don't know how to deal with it. As you can see on my dataframe i have a column description and a column title. I want for a same description , my title to be all the same. I want to...
<p>Here's a solution with some dummy data using <code>pandas.DataFrame.transform</code>:</p> <pre><code>import pandas as pd df = pd.DataFrame({'title': ['t1', 't2', 't3', 't4', 't5'], 'description': ['d1', 'd1', 'd1', 'd2', 'd2']}) description title 0 d1 t1 1 d1 t2 2 ...
python|pandas
2
6,797
59,940,722
Python 'int' object is not iterable when using len on a list from beautifulsoup
<p>So far I have the following code, I'm including all of it in case it helps</p> <pre><code>import requests from bs4 import BeautifulSoup URL = 'https://projects.fivethirtyeight.com/2020-nba-predictions/games/' page = requests.get(URL) soup = BeautifulSoup(page.content, 'html.parser') todays_games = soup.find('div'...
<p><code>len(list(todays_games.children))</code> evaluates to an integer - 5, 6, etc. You can't iterate directly over an integer with a for loop.</p> <p>You can use the built-in function <code>range</code> to loop a set number of times if you'd need, but you should iterator directly over <code>todays_games.children</c...
python|beautifulsoup|python-requests
2
6,798
3,006,132
Correct way to protect a private API Key when versioning a python application on a public git repo
<p>I would like to open-source a python project on Github but it contains an API key that should not be distributed.<br> I guess there's something better than removing the key each time a "push" is committed to the repo.</p> <p>Imagine a simplified <code>foomodule.py</code> :</p> <pre><code>import urllib2 API_KEY = '...
<p>One way would be to make it an explicit part of the interface. Make it an argument for your object constructors, for example. Or require the client to extend your class and provide a method, returning the key. It sucks when one needs to edit your module before she can use it.</p>
python|version-control|configuration
1
6,799
2,952,790
Problems trying to format currency with Python (Django)
<p>I have the following code in Django:</p> <pre><code>import locale locale.setlocale( locale.LC_ALL, '' ) def format_currency(i): return locale.currency(float(i), grouping=True) </code></pre> <p>It work on some computers in dev mode, but as soon as I try to deploy it on production I get this error:</p> <pre><...
<p>On the production server, try</p> <pre><code>locale.setlocale( locale.LC_ALL, 'en_CA.UTF-8' ) </code></pre> <p>instead of</p> <pre><code>locale.setlocale( locale.LC_ALL, '' ) </code></pre> <p>When you use <code>''</code>, the locale is set to the user's default (usually specified by the <code>LANG</code> environ...
python|django
38