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
4,700
31,527,280
Incorrect Value being returned when counting the number of duplicate items in a list
<p>My function checks to see how many duplicates the first element of the list has within that list. </p> <pre><code>def duplicate(lst): count=0 length = len(lst) for i in range(1,length): if lst[0]== lst[i]: count+=1 print [(lst[i]),count] </code></pre> <p>For example:</p> <pre><c...
<p>You're returning the value from within the loop. You need to dedent the return statement. Your loop only executes once.</p>
python|list|loops
2
4,701
15,933,268
change images every 5 seconds - but images from server
<p>i am trying to change the users in every seven seconds. for this, i need to load all information of user from server. how can i do this using javascript? what is the efficient way? </p> <p>what i thought about is, i send every seven seconds an http request to server asking for user data with ajax. it is efficient ...
<p>the most efficient way is to use <a href="http://en.wikipedia.org/wiki/WebSocket" rel="nofollow">websockets</a> , you should document on them.</p> <p>Only thing is they are not always <a href="http://caniuse.com/#feat=websockets" rel="nofollow">suppoerted from browsers</a></p> <p>You can also do somenthing like:</...
jquery|python|html|django
2
4,702
59,791,553
Error with importing tensorflow and tflearn after installing with pip
<p>I have installed tensorflow and tflearn using pip on my windows machine. I am using pyhton 3.6 as it was asked by the tutorial because tflearn has some bug with python 3.7. I am trying to create a chatbot which reads data from a json fil and while testing my code, I ran into an issue with several exceptions given be...
<p>It's because tflearn has support for TensorFlow version up to 1.2 only. You can downgrade your TensorFlow version to use the above code.</p> <p>To downgrade:</p> <pre><code>pip uninstall protobuf pip uninstall tensorflow </code></pre> <p>To install TensorFlow 1.x:</p> <pre><code>pip install tensorflow==1.15 </code><...
python|tensorflow|deep-learning|neural-network|tflearn
2
4,703
24,978,442
return data from functions that accept optional named paramaters, **kwargs
<p>I'm just learning about **kwargs and I'm probably twisting up it's real use, so here goes...</p> <p>I have 1 main script, 3 functions and a dict: script.py, setup(), billing(), newCust(), data = {}</p> <p>setup() will call billing() and billing() will call newCust(), and newCust will return an id that will be used...
<p>There are several ways for a function to "return" data:</p> <ul> <li><p>using the return statement. If you have more that one value to return, user tuples (<code>return (a, b, c)</code>), or dicts (<code>return {'customer': c, 'customer_data': d, 'whatever': e}</code>)</p></li> <li><p>(I don't like this one) by exp...
python|parameters|parameter-passing|optional-parameters|keyword-argument
1
4,704
70,815,858
Pandas variable rounding of column
<pre><code>&gt;&gt;&gt; print(df) item value1 0 a 1.121 1 a 1.510 2 a 0.110 3 b 3.322 4 b 4.811 5 c 5.841 </code></pre> <p>This is my dummy pandas df.</p> <p>Below is how I truncate/round my column value1.</p> <pre><code>decimals = 2 df['value1'] = df['value1'].apply(lambda x:...
<p>Given the fact that trailing zeros are not significant, the best approach should be:</p> <pre><code>dec_dict = {'a' : 2, 'b': 3, 'l':3, 'default': 2} df['value1'] = (df.groupby('item')['value1'] .apply(lambda g: g.round(dec_dict.get(g.name, dec_dict['default'])) ) </code></pre> <p>...
pandas
1
4,705
2,400,492
How do I execute SQL_CALC_FOUND_ROWS in python MySQLDB
<pre><code>cursor.execute("SELECT SQL_CALC_FOUND_ROWS user_id FROM...limit 5") rows = cursor.fetchall() ... total_rows = cursor.execute("SELECT FOUND_ROWS()") #this doesn't work for some reason. </code></pre> <p>Edit: I tried SELECT FOUND_ROWS() FROM my_table...and the numbers are funky.</p>
<p>Seems to work here by fetching the result for the second cursor:</p> <pre><code>cursor.execute("SELECT SQL_CALC_FOUND_ROWS user_id FROM...limit 5") rows = cursor.fetchall() cursor.execute("SELECT FOUND_ROWS()") (total_rows,) = cursor.fetchone() </code></pre>
python|mysql|database|select
1
4,706
6,051,570
Iterator value not retained after 'any()' call
<p>I have the following snippet of code. I'm basically trying to get the index/iterator of a particular string in a list (aside from just knowing whether it is present). Is this possible at all, or should I be using a loop-with-an-if?</p> <p>bucket = ["alpha", "beta", "gamma"]</p> <p>content = ""</p> <p>if any(conte...
<p>Generator expressions do not leak the iterator. List comprehensions in 2.x do, but not in 3.x.</p>
python|iterator|scope
1
4,707
67,076,336
Optimize date index to convert to the day of the week
<p>I want to convert the <code>date index</code> of the <code>dataframe</code> to the day of the week. I have tried many methods. First convert the <code>date index</code> to a <code>column</code>, then convert the <code>column</code> to <code>datetime</code>, and then use the <code>datetime.dt.dayofweek</code> method ...
<p>By using <code>.strftime('%Y-%m-%d')</code> on returns of <code>pandas.date_range()</code>, you are changing the <code>DatetimeIndex</code> type to string. Your target format <code>%Y-%m-%d</code> is actually the same with default format, you needn't do this. Here is an example:</p> <pre class="lang-py prettyprint-o...
python|pandas|dataframe|datetime
1
4,708
63,867,110
Why does assigning a sliced numpy array to another variable keep slicing it?
<p>I've been experiencing some strange behavior with numpy arrays. Consider the code below:</p> <pre><code>import numpy as np # 1 a = [np.arange(16)] b = a print(f'b = {b}') # 2 b[0] = a[0][::2] print(f'b = {b}') # 3 b[0] = a[0][::2] print(f'b = {b}') </code></pre> <pre><code>b = [array([ 0, 1, 2, 3, 4, 5, 6, ...
<p>In your code, you have given <code>b = a</code> So <code>b</code> is just making a reference of <code>a</code>. Every time you change the value of <code>b</code>, you are also making a change to value of <code>a</code>. For more details on assignment vs copy vs deep copy, please refer to this <a href="https://mediu...
python|arrays|numpy|variables
1
4,709
66,366,664
Python Typing: TypedDict - What's the difference between TypedDict instance and TypedDict Class?
<p>I'm trying to use Type Hinting to prevent myself from accidentally using wrong <code>dict</code> keys, which is working fine. However, I haven't been able to understand the difference between these two behaviors:</p> <pre><code>someType = TypedDict('someName', {'key': type}) </code></pre> <p>and</p> <pre><code>class...
<p>The first syntax can be backported to older Python versions such as 3.5 and 2.7 that don't support the variable definition syntax. It resembles the traditional syntax for defining named tuples Difference: The semantics are equivalent to the class-based syntax. *<em>This syntax doesn't support inheritance</em></p> <p...
python|type-hinting
1
4,710
35,106,391
Game of life python - too many resources
<p>i have started programming and tried the 'game of life' and everything is fine on 20x20 boards, but if i take board sizes like 100 or more, after 100 generations the program needs 500mb of RAM and 25% of my CPU (and needs more for every gen), which i guess is bad. so i think, i have a logical error, which takes more...
<p>When you create a grid of size 150x150, you are creating 22,500 canvas items. <strong>Every time you call <code>print_grid</code> you are creating <em>another</em> 22,500 canvas items.</strong> Since you are calling <code>print_grid</code> 1000 times, you are creating over 22 <em>million</em> canvas items. While the...
python|tkinter|conways-game-of-life|tkinter-canvas
0
4,711
44,961,486
What is wrong with this package structure in python?
<p>I have the following structure:</p> <pre><code>/MyApp /Module_A __init__.py serviceFile.py /Module_B clientFile.py </code></pre> <p>I am trying to call a function in ServiceFile.py from ClientFile.py</p> <pre><code>From MyApp.Module_a import ServiceFile </code></pre> <p>but I am getting the error ...
<p>There's potentially 2 sources of error. The first, like @TomCho has already pointed out is if the <code>__init__.py</code> file is not properly in your modules. However, since it works in PyCharm, I'm guessing it's the second.</p> <p>The second is if your <code>PYTHONPATH</code> variable is not set up properly. The...
python|pycharm
2
4,712
61,273,178
Python vs Perl and byte count correctness
<p>The output I get from <code>wc</code> when trying to calculate a byte count on a string, differs from python and perl by one byte.</p> <p>Why is that?</p> <p>Is this problem exclusive to chars or can this arise in other types?</p> <p>If so, is there a known offset table for each type?</p> <pre><code>$ python -c ...
<p>Python <code>print "..."</code> is essentially the same as Perl <code>print "...\n"</code>, i.e. Python adds a newline by its own, Perl not (Perl <code>say</code> does though).</p>
python|perl
3
4,713
60,747,752
not be able to make a matrix 10x10 in python
<p>I wanted to write a simple script for create a matrix 10x10 with all the numbers from 1 to 99 appending to a list group of 10 element at each time. The result i expected was list[[1,2,3,4,5,6,7,8,9],[10,11,12,13,14,15,16,17,18,19],...] But the output is very strange:</p> <p><strong>here's the script:</strong></p> ...
<pre><code>lista = [] z = 0 for i in range(10): lista2 = [] for j in range(10): lista2.append(z) z += 1 lista.append(lista2) print(lista) </code></pre> <p>or just:</p> <pre><code>lista = [[10*i+j for j in range(10)] for i in range(10)] print(lista) </code></pre>
python
0
4,714
60,640,075
Returning class to itself in python
<p>Very simple question here, but I am new to python as an object oriented programming language. I am trying to write a class. Imagine it is organized as follows:</p> <pre><code>class myClass: def __init__(self,a,b,runit=True): self.a = a self.b = b if runit: self.run_func() ...
<p><code>run_func</code> should return <code>self</code>:</p> <pre class="lang-py prettyprint-override"><code> def run_func(self): self.c = self.a*self.b return self </code></pre> <p>stating <code>return</code> without a value following it, is the same as writing <code>return None</code>. You get t...
python|class
2
4,715
57,870,480
Python - how to pass a variable to a regular expression (re.match)
<p>I'm trying to pass a variable to a regular expression as the value which is being checked will change each time. So far, I can look for a given string which works but I'm not sure on the correct syntax when passing a variable.</p> <p>serial string: <code>"asdfID:13546537(0xCEB429)"</code></p> <p>var: <code>1354653...
<p>You were quite close. You can for example use <a href="https://www.python.org/dev/peps/pep-0498/" rel="nofollow noreferrer">f-strings</a> to place your variable inside the regex:</p> <pre><code>import re var = 13546537 serial = "asdfID:13546537(0xCEB429)" if re.search(fr"ID:{var}", serial): print("match found...
python|regex|python-3.x
0
4,716
57,798,048
Docx is not replacing texts that's extracted from pandas
<p>I'm creating a program to extract certain text and to change the name as well as the firm's to personalize the message. But when I pull out the names as well as the firm's names from the excel sheet, the printing function only prints out the unedited form. </p> <p>I tried using a different library, OpenPyXl. I also...
<p>You're most probably a victim of words splitted across <code>w:t</code>.</p> <h2>Explanation :</h2> <p>A typical <code>word/document.xml</code> looks like this :</p> <pre><code>&lt;w:body&gt; &lt;w:p w:rsidR="001A6335" w:rsidRPr="0059122C" w:rsidRDefault="0059122C" w:rsidP="0059122C"&gt; &lt;w:r&gt; &...
python|pandas|docx
0
4,717
69,321,816
From a test sub-directory, import module that inherits from a base abstract class
<p><strong>Context</strong></p> <p>I am trying to run unit tests using pytest, however, the test files are unable to find the modules because they inherit from an abstract class.</p> <p>More specifically, I have the following directory structure:</p> <pre><code>project |- __init__.py |- project.py |- JsonParser.py |- P...
<p>Looks like the trick was to execute in the following way:</p> <pre><code>Python -m pytest project/tests </code></pre> <p>Doing this adds the root directory to the search path. Running with only pytest does not include the root directory in the Python file search path. For example, when the test is executed with 'pyt...
python|python-import
1
4,718
69,314,682
Python input argument
<p>I'm using some existing code which specifies a hardware address used to fetch sensor data.</p> <p><code>ina260 = adafruit_ina260.INA260(i2c, address=0x45)</code></p> <p>(the 0x45 above is the address).</p> <p>I'm trying to pass the address as an input argument on the command line as follows:</p> <p><code>python3 sen...
<p>Your problem here is that <code>sys.argv</code> is a list of <em>strings</em>, whereas you are trying to interpret those strings as integers (which you have expressed in hex notation).</p> <p>So you convert them with int:</p> <pre class="lang-py prettyprint-override"><code>int(&quot;7&quot;) </code></pre> <p>But sin...
python|i2c
1
4,719
55,567,960
Reversing the order of rows and operation efficiency
<p>I know that to reverse the order of rows in a pandas data frame that I can use </p> <pre><code>df = df.iloc[::-1] </code></pre> <p>but my issue is doing more operations with it. For instance,</p> <pre><code>def transform (x) : x = x.iloc[::-1] x['a'] = x['a'] * 2 return x </code></pre> <p>for </p> <...
<p>I'm not quite sure that I understand what you're trying to do, but I'm going by the example you used in your question</p> <pre><code>x = pd.DataFrame({'a' : np.arange(5), 'b' : np.arange(5)}) </code></pre> <p>Result (first column is the index): </p> <pre><code>| | a | b | |----|-----|-----| | 0 | 0 | ...
python|pandas
1
4,720
42,331,808
Fast points in circle test with numpy
<p>I have a large number of <code>(x,y)</code> grid points with integer coordinates which i want to test if they are in small number of circles given by radius and center. The points are some marked parts of an image, which means there are a small number of irregular shaped blocks, which contain the points. There i wan...
<p>Taking advantage of coordinates being integers:</p> <p>create a lookup image</p> <pre><code>radius = max([circle.radius for circle in circles]) mask = np.zeros((image.shape[0] + 2*radius, image.shape[1] + 2*radius), dtype=int) for circle in circles: center = circle.center + radius mask[center[0]-circle.rad...
performance|numpy|scipy|geometry
3
4,721
54,165,065
python: how to turn my enumerated string into a dictionary?
<p>I'd like to send the output of my string enumerator into a dictionary to include both the output of the enumerator and its index...</p> <p>I've got this as a basis:</p> <pre><code>&gt;&gt;&gt; dictionary = dict() &gt;&gt;&gt; for i, c in enumerate('My Great String'): ... print("c"+str(i),c) ... c0 M c1 y c2 c3 G...
<p>Just assign each value to the dictionary using the respective key:</p> <h3>Code</h3> <pre><code>dictionary = dict() for i, c in enumerate('My Great String'): dictionary['c%d' % i] = c print(dictionary) </code></pre> <p>You can use a <strong>dictionary comprehension</strong> like this:</p> <h3>Code</h3> <pr...
python-3.x
1
4,722
54,228,999
Search exact string , match it .If no matched entry add parameter also if partial match modify python file
<p>I have a file /etc/sysctl.conf and want to search for below 2 strings. If no such strings found we need to append file with same . If no exact match found we need to correct it or delete line and add. If exact match found no action on file. I am unable to replace in file. Please guide. </p> <p>Search Strings :</p>...
<p>Here's a different approach using python data types instead of just string regex (it's too easy to mess up regex and ruin the structure of the file).</p> <p>Working with a fake example file:</p> <pre><code># hash comment ; colon comment one = 1 net.ipv4.ipfrag_low_thresh = 1234 another = ok </code></pre> <p>cod...
python|python-3.x
1
4,723
58,489,152
How do I put Inputs in a notepad and open and use those values in python2.7
<p>So, I need to use a notepad file for inputs.</p> <p>I can open the file and print the numbers out but can't seem to assign each line of the notepad to a variable that I can work with in the code</p> <pre class="lang-py prettyprint-override"><code>file = open(r"C:/Users/aryaa/Desktop/Base.txt", "r") text = file.rea...
<p>It's not clear exactly what you want, but this will read your file and use the text in each line as a key that can map to some value.</p> <pre><code>import random line_dict = {} file = open(r"sampleLines", "r") lines = file.readlines() for line in lines: var = line.strip()# get rid of \n line_dict[var] = ...
python|python-2.7|input|text-files
0
4,724
58,475,852
how to remove 'int' object is not callable
<p>how to resolve 'int' object is not callable</p> <p>I am new over here</p> <pre><code>-68+(((68)**2-4(34)(-510))**0.5)/(2*34) </code></pre> <blockquote> <p>Traceback (most recent call last):</p> <p>File "", line 1, in -68+(((68)**2-4(34)(-510))**0.5)/(2*34)</p> <p>TypeError: 'int' object is not ...
<p>Python does not support multiplication through parentheses (like <code>(34)(-510)</code> and <code>4(34)</code>). Change this to <code>(34) * (-510)</code>. So, your full line would be:</p> <pre><code>&gt;&gt;&gt; -68+(((68)**2-4*(34)*(-510))**0.5)/(2*34) -64.0 </code></pre> <p>When you say <code>4(34)</code>, you...
python-3.x
1
4,725
28,409,064
How to calculate how many standard deviations a number is from the mean?
<p>I have a matrix of size (61964, 25). Here is a sample:</p> <pre><code>array([[ 1., 0., 0., 4., 0., 1., 0., 0., 0., 0., 3., 0., 2., 1., 0., 0., 3., 0., 3., 0., 14., 0., 2., 0., 4.], [ 0., 0., 0., 1., 2., 0., 0., 0., 0., 0., 1...
<p><code>scipy.stats</code> has the function <a href="https://docs.scipy.org/doc/scipy-0.18.1/reference/generated/scipy.stats.zscore.html#scipy.stats.zscore" rel="nofollow noreferrer"><code>zscore</code></a> which allows you to calculate how many standard deviations a value is above the mean (often refered to as the <e...
python|arrays|numpy|scikit-learn|standard-deviation
5
4,726
28,427,310
How to implement a list of references in python?
<p>I'm trying to model a collection of objects in python (2). The collection should make a certain attribute (an integer, float or any immutable object) of the objects available via a list interface.</p> <p>(1)</p> <pre><code>&gt;&gt;&gt; print (collection.attrs) [1, 5, 3] &gt;&gt;&gt; collection.attrs = [4, 2, 3] &g...
<p>Just add another proxy inbetween:</p> <pre><code>class _ListProxy: def __init__(self, system): self._system = system def __getitem__(self, index): return self._system._components[index].attr def __setitem__(self, index, value): self._system._components[index].attr = value cla...
python|reference|pass-by-reference
2
4,727
28,861,394
Scipy interpolation of numpy large array fails when exceeding a certain number of elements
<p>I am trying to analyze data from a time series. I want to interpolate the original data and make them equally spaced in time, so i use scipy cubic splines for this. Everything is going ok until 10000 points (float numbers) but don't seem to work after this number of points . I have tried with 10001 points and interp...
<p>Spline fitting is a global process. Your splrep call tries to manipulate a 10000 by 10000 matrix. The underlying Fortran code plays some rather smart tricks, but still --- do you really need continuous differentiability? You might be better off using a piecewise polynomial interpolator (have a look at scipy.interpol...
python|numpy|scipy
0
4,728
14,442,514
Cluster numbers in big matrix
<p>I need to cluster all numbers (in one cluster can be numbers with same value, for example just 5) in matrix different than passed and return dictionary like </p> <pre><code> {number1:[[(3,4),(4,5)],[]..], number2:...}#I am using Python </code></pre> <p>I can iterate through rows and columns and when I find numb...
<p>Let's classify the cell values into <code>target value</code> and <code>replacement value(s)</code>, where the cells with <code>target value</code> are the ones you want to modify. You want to cluster the ones with <code>replacement value(s)</code>. In your example, these values happen to be 1, and (2,3) respectivel...
python|algorithm|matrix
1
4,729
14,907,457
How large data can memcached handle efficiently?
<p>How large values can I store and retrieve from <code>memcached</code> without degrading its performance? I am using memcached with python-memcached in a django based web application.</p>
<p>Read this one:</p> <p><a href="https://groups.google.com/forum/?fromgroups=#!topic/memcached/IaMLUeOGxWk" rel="nofollow">https://groups.google.com/forum/?fromgroups=#!topic/memcached/IaMLUeOGxWk</a></p> <p>You should not "store" anything in memcached.</p>
python|django|caching|memcached
3
4,730
41,234,875
How can I change a Django db to MySQL on pythonanywhere?
<p>I thought this would be simple because of this <a href="https://help.pythonanywhere.com/pages/UsingMySQL/" rel="nofollow noreferrer">MySQL tutorial by pythonanywhere</a>, but I'm still having trouble switching over from sqlite3. I'm a beginner to SQL databases, and I've been checking out other stackoverflow questio...
<p>It looks like something went wrong with the migration. I would recommend you to do following steps that re-create your db.</p> <ol> <li><p><strong>Make a backup of your data in the database!!!</strong></p></li> <li><p>Connect to your remote database:</p> <pre><code>$ mysql -h 3DPrince.mysql.pythonanywhere-services...
python|mysql|django|pythonanywhere|dev-to-production
2
4,731
6,984,965
Parsing SPARQL queries
<p>I need to test for a certain structural property of a couple million SPARQL queries, and for that I need the structure of the <code>WHERE</code> statement. I'm currently trying to use fyzz to do this, but unfortunately its documentation is not very useful. Parsing queries is easy, the problem is that i haven't been ...
<p>Another tool is <code>roqet</code> a tool that is packaged within <a href="http://librdf.org/rasqal/" rel="nofollow">rasqal</a>. It is a command line tool that returns the parsed tree. For instance:</p> <p><code>roqet -i laqrs -d structure -n -e "SELECT * WHERE {?x a ?y OPTIONAL {?x a ?z}}"</code></p> <p>would out...
python|parsing|grammar|bison|sparql
5
4,732
57,001,398
Using pandas to calculate a cumulative stock price index based on daily percentage returns
<p>I'm trying to calculate a financial stock price index that begins at 100 and cumulatively changes depending on the daily returns. Below is the current code I have to achieve this process; however, I was wondering if there was a more pythonic way to achieve the same result without using a for-loop approach.</p> <pre...
<p>please try not to use images in your question. We like to be able to copy data from the question to get to answers :)</p> <p>Grabbing some stocks from yahoo, filter for close and then adjust to percentage changed. Add 1 so that you have a percent you can properly multiply, </p> <pre><code>import yfinance as yf df ...
python|dataframe
1
4,733
61,868,587
How do i upgrade the default version of python used in docker?
<p>I have this Dockerfile containing these lines</p> <pre><code>FROM "ubuntu:bionic" RUN apt-get -o update RUN apt-get -o upgrade -y RUN apt-get -o install python3.7 -y RUN apt-get -o install sudo -y RUN sudo mkdir -p /tensorflow/models RUN apt-get -o install -y git python-pip RUN pip install --upgrade pip RUN pi...
<p>There are many ways to go around this issue. Even though you've installed python3.7, you have not installed a compatible version of pip.<br> To install pip that will work with python3, you should install <code>python3-pip</code> package and the run <code>pip3 install tensorflow==1.14</code>.</p> <p>As suggested by ...
python|docker|tensorflow|ubuntu
0
4,734
61,688,021
Why is Anaconda Navigator not opening?
<p>I have trouble with my anaconda3 navigator. I am using it with Python 3 and jupyter notebook. Today, because I had trouble with installing some packages, I updated everything and it worked fine. A few hours later, my anaconda navigator is not opening and when I open the PowerShell prompt I get the following error: <...
<p>I got the solution, okay it is not really a solution,but better than nothing :) You just have to uninstall Anaconda completely from your computer, also every folder with Anaconda things. Then you have to install it completely new, as if you never had Anaconda on your computer. For me, that helped - everything goes l...
python|powershell|jupyter-notebook|anaconda|conda
0
4,735
36,066,207
How to attach pdf to my mail generated by python 2.4.3 script?
<p>I've searched about attaching a pdf in my script but I found the answer, which is, correct me if I'm wrong, using MIMEApplication, not compatible with python 2.4.3. I couldn't import MIMEApplication, and didn't find it in the documentation. I don't have the option of upgrading my OS to accept newer version.</p> <p>...
<p>Like you are saying, it appears that <a href="https://docs.python.org/release/2.4.3/lib/module-email.html" rel="nofollow">the <code>email</code> module in Python 2.4.3</a> does not support <code>MIMEApplication()</code> for creating an <code>application/*</code> MIME part.</p> <p>I <em>think</em> you might be able ...
python
0
4,736
29,364,167
Get current page of pagination in view and manually set count of page
<ol> <li>I need to manually set count of page for pagination in view.py</li> <li><p>I need to get number of current page for processing it in function. I next view.py: </p> <pre><code>class VideoListView(ListView): template_name = "video/list.html" context_object_name = 'videos' paginate_by = 12 reques...
<p>The Django pagination is stored via <strong>GET</strong>, so in your <em>ListView</em> you need to access:</p> <pre><code># This will assume, if no page selected, it is on the first page actual_page = request.GET.get('page', 1) if actual_page: print actual_page </code></pre> <p>so in your list view code, depen...
python|django|pagination
3
4,737
29,604,164
How stop yasnippet field in emacs 24
<p>I use elpy and yasnippet to make emacs become a python editor.</p> <p>Then I use yasnipprt to build a class object, but I find I can't exit field as quickly as sublime text can, within double "return". That means I have to move cursor at the begin of line used tab or keyboard one by one at the end of class object, ...
<p>I think you're asking how to jump between fields in yasnippet.</p> <ul> <li>To jump to the next field press <code>TAB</code> (<code>yas-next-field-or-maybe-expand</code>)</li> <li>To jump to the previous field, press <code>S-TAB</code> (<code>yas-prev-field</code>)</li> <li>To delete a field and move to the next fi...
python|emacs|yasnippet
4
4,738
29,351,501
Why does struct.pack have such high variability in performance?
<p>I get the following result when testing the performance of <code>struct.pack</code>:</p> <pre><code>In [3]: %timeit pack('dddd', 1.0, 1.0, 1.0, 1.0) The slowest run took 578.59 times longer than the fastest. This could mean that an intermediate result is being cached 1000000 loops, best of 3: 197 ns per loop </cod...
<p>The IPython profiler is spot on. The result is indeed cached (at least in some python versions). For example in python 2.7.6 you can find the relevant code <a href="https://hg.python.org/cpython/file/3a1db0d2747e/Modules/_struct.c#l1795" rel="nofollow">here</a> where the <code>cache_struct</code> function is defined...
python|performance|struct
1
4,739
46,205,836
Add a column to a dataframe whose value is based on another field, but needs to increment
<p>I have a problem I've been wrestling with and I have to imagine there is a more elegant solution than looping through my dataframe row by row. I have a dataframe like the following:</p> <pre><code> EventTime | ConditionMet --------- --------- | -------- 2017-09-11 00:00:01 | 0 2017-09-11 00:00:02 | 0 201...
<p>I believe I found a solution to my problem, although I don't know how elegant it is. Essentially, I joined the dataset back to itself by the timestamp on the previous record (I supposed a lead() function could've helped me with this. From there, I could pass in the current condition and the next condition to deter...
python|apache-spark|dataframe|spark-dataframe|pyspark-sql
0
4,740
61,062,947
How to assign values in lambda function in Python?
<p>I am using lambda function to make my code optimize and faster. Below I have written some function.</p> <pre><code>a = [{"objId":"5c077187fe506f8dd3589ce6","userid":"absurana","firstName":"Null","usrRole":"Software Quality User","lastName":"Null","tiles":"Potential CFD","userType":"User"}, {"objId":"5d9d7ce6fe506f...
<p>A one-liner, concise, pythonic way:</p> <pre><code>mapping = {"userid": "UserId", "userType": "User Type", "usrRole": "Role", "tiles": "Tiles"} def rename(x): return [{mapping.get(k, k):v for (k,v) in d.items()} for d in x] </code></pre> <p>Please note that the usage of <code>lambda</code> is not providing any c...
python|lambda
4
4,741
70,171,437
Cannot import modules from parent folder
<p>I've been fighting with this for weeks, read so many (outdated) articles, tried so many different proposed solutions without success. And I still believe I'm not trying to do something difficult...</p> <p>I have the following folder structure</p> <pre><code>├── script.py ├── lib │ ├── lonlatboxes.py │ ├── util...
<p>All you need to do is change the second <code>import</code> in <code>utils.py</code> and make it relative to <code>script.py</code>'s location:</p> <h3><code>utils.py</code></h3> <pre><code>from sqlalchemy import create_engine # python package from .lonlatboxes import lonlatboxes # my module </code></pre>
python|python-import
1
4,742
53,670,492
XgBoost validate_features argument in predict method. What does validate_features do?
<p>Can anyone please help me to understand the significance of </p> <pre><code>validate_features </code></pre> <p>argument of predict method and how does it affect the predication from the tree. </p> <p>I am using python API for the Xgboost.</p>
<blockquote> <p>When this is <strong>True</strong>, validate that the Booster’s and data’s <strong>feature_names</strong> are <strong>identical</strong>. Otherwise, it is assumed that the <strong>feature_names</strong> are the <strong>same</strong>.</p> </blockquote>
python-3.x|machine-learning|data-science|xgboost
0
4,743
54,843,169
Thead.join() not helping in printing a string only after all the threads are finished
<p>I am currently trying to write a function which achieves the following:</p> <ul> <li>Takes all of the messages from the list 'messages', in random order, while making sure none of them are repeated.</li> <li>Prints them after a delay of a random amount of seconds in the range between 1 - 10 seconds.</li> <li>After ...
<p>The problem is that you wait only for the last thread to join (because 't' variable is holding the last created Thread object when the loop ends) so the join function returns when the last thread is completed and the program continues.</p> <p>I was able to reproduce this error even on option 2 by supplying:</p> <p...
python|python-3.x|multithreading|function|delay
1
4,744
33,445,841
How to work out average of scores from a text file Python
<p>I want to find out how to sort out averages of scores from a text file, the text file would look like this:</p> <pre><code>Matt 3 John 6 Gucci 7 </code></pre> <p>Notice there is only one space inbetween the Name and Score.</p> <p>From this text file i would like to work out the average of the entire files content...
<p>You dont have to do <code>f.readlines()</code> and <code>'avg'.lower()</code> does not look like what you are intending to do, <code>.lower()</code> must be used on the <code>option</code> variable. Also avoid <em>shadowing</em> builtin functions and keywords as you did with <code>list</code>.</p> <p>Sample code:</...
python
3
4,745
24,534,649
Python/SqlAlchemy 3-way circular dependency
<p>I am having an issue with creating a set of relationships among 3 of my tables. When I run the code to create the tables I get a circular dependency error. </p> <p>I tried fiddling around with <code>use_alter</code> and <code>post_update</code> based on responses to similar posts, but I wasn't able to solve the iss...
<p>You can probably get alembic to help you with a cyclic dependency in your schema, but I'm not going to help you with that. Instead, I'm going to strongly urge you to <em>break the cyclic dependency</em>.</p> <p>If i'm understanding your schema, you have the rooms or buildings in your model represented by <code>Lo...
python|sqlalchemy|circular-dependency
0
4,746
41,128,573
Python - Data Masking - Faker - fake.name error
<p>I'm trying to use Python faker and fake-factory for Data masking in my application. I have executed the following test python script but getting syntax error. Please help me out.</p> <pre><code>#faker script files # coding=utf-8 from faker import Factory fake=Factory.create() fake.name() fake.address() fake.text(...
<p>You are using the print syntax incorrectly. The reason this worked on 2.x and not 3.x is that the way print works changed across versions. The one of you currently have is the python 2.x method.</p> <p>Try :</p> <pre><code>for _ in range(0,10): print (fake.name()) # Put the call in parentheses </code></pre>
python|masking|faker|data-masking
0
4,747
38,118,900
Python Flask Swagger Flasgger Download Excel
<p>I am trying to return an excel file from Swagger API. Built that using Flask with a Swagger wrapper with Flasgger. Here's the code - </p> <pre><code>@app.route('/cluster', methods=['POST']) def index(): """ This API will help you generate clusters based on keywords present in unstructured text Call this...
<p>Try to use flasgger to download excel. You can change the response type to "application/octet-stream" to resolve it. <img src="https://i.stack.imgur.com/fj0jO.png" alt="Sample Image"></p>
python|flask|swagger|xlsx
1
4,748
31,170,783
Is python's hash() portable?
<p>Is python's <code>hash</code> function portable?</p> <p>By "portable" I mean, will it return the same results (for the same data) across python versions, platforms and implementations?</p> <p>If not, is there any alternative to it that provides such features (while still capable of hashing common data-structures)?...
<p>No, <code>hash()</code> is not guaranteed to be portable.</p> <p>Python 3.3 also uses <em>hash randomisation</em> by default, where certain types are hashed with a hash seed picked at start-up. Hash values then differ between Python interpreter invocations.</p> <p>From the <a href="https://docs.python.org/3/refere...
python|hash|cross-platform|portability
4
4,749
31,068,162
Removing a dictionary from a list of dictionaries in python
<p>So I have a list of dictionaries, where each dictionary has two key-value pairs. Something like</p> <pre><code>l1 = [{'key1':'value1','key2':'value2'}, {'key1':'value1','key2':'value2'}, ... ] </code></pre> <p>Now what I want is to remove a dictionary from this list just be checking first <code>ke...
<p>Given,</p> <pre><code>ds = [{'key1': 'value1', 'key2': 'value2'}, {'key1', 'value3', 'key2', 'value4'}, ...] </code></pre> <p>You can remove a dictionary with a unique key-value using a list comprehension:</p> <pre><code>ds = [d for d in ds if d['key1'] != 'value1'] </code></pre> <p>But then you are ...
python|list|dictionary
8
4,750
52,297,890
Finding max gradient of irregular data series from csv
<p>Python noob here, but I am attempting to find the max gradient of a dataset (reading from a csv file, with two columns: force and displacement, irregular intervals). I think I have done it correctly based on a simpler example I tested, but I want to check that I should be using diff or whether is there a better, mor...
<p>For calculating gradients you can always use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.gradient.html#numpy.gradient" rel="nofollow noreferrer"><code>np.gradient</code></a> instead of <code>np.diff</code>. That takes care of your boundary values as well.</p>
python|csv|numpy|gradient
0
4,751
52,094,791
Do Django filters increases ram consumption per user : Python
<p>I don't know where else I could have asked this question, thus asking it here. I want to know that if I impose multiple Django filters on a page which are using multiple db tables, will that effect ram consumption whenever a user visits this page because before the user only filtered data will get reflected. I'm usi...
<p>Django filter and query sets are lazy. What it actually means is you are not actually hitting the database until you <strong>evaluate</strong> them. Quoting official <a href="https://docs.djangoproject.com/en/2.1/ref/models/querysets/" rel="nofollow noreferrer">documentation</a> -</p> <blockquote> <p>Internally, ...
python|django|postgresql|filter|ram
2
4,752
51,731,972
How Do I Find a Specific Expression within a Dataframe Column?
<p>I have a dataframe with a column called "Description." I want to scan through all the text in this column, and identify those rows that have a description that contains a number that is at least 3 digits long. </p> <p>Here's where I'm at:</p> <pre><code>import re df['StrDesc'] = df['Description'].str.split() y=re...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.findall.html" rel="nofollow noreferrer"><code>str.findall</code></a>, <code>split</code> is not necessary :</p> <pre><code>y = df['Description'].str.findall('[0-9]{3}') </code></pre> <p>But with some testing <a href="https://stack...
python|regex
0
4,753
62,363,956
How to gather a dictionary value from a list name?
<p>So I have a dictionary:</p> <pre class="lang-py prettyprint-override"><code>a_dict = { "a": 1, "b": 2, "c": 3, "d": 4, "e": 5, "f": 6, "g": 7, "h": 8, "i": 9, "j": 1, "k": 2, "l": 3, "m": 4, "n": 5, "o": 6, "p": 7, "q": 8, "r": ...
<p>Here's a simple function that takes a string and a cipher dictionary and uses the dictionary to translate the string:</p> <pre><code>def encipher(message: str, cipher: dict) -&gt; str: """Substitute each letter of the message using the cipher dict.""" return ''.join( str(cipher[char]) for c...
python|dictionary
2
4,754
56,166,857
Can I reference project URLs in Django templates by providing the project name?
<p>I have a Django project called <code>reports</code> with apps <code>report_1</code>, <code>report_2</code> etc.</p> <p>For certain reasons, I want to treat the project as an app, so I have added <code>reports</code> to <code>INSTALLED_APPS</code> alongside <code>report_1</code> and <code>report_2</code> and also cr...
<p><code>app_name</code> does not work in the root url config. See <a href="https://code.djangoproject.com/ticket/28413" rel="nofollow noreferrer">ticket 28413</a> and <a href="https://groups.google.com/forum/#!msg/django-developers/5NJS_mI7png/PsIN5oneAAAJ" rel="nofollow noreferrer">this discussion</a> on the django-d...
python|django
1
4,755
63,658,388
How to get the content from my database in views.py? [Django]
<p>I am trying to print the <code>content</code> fields from my database, Here's my <code>models.py</code> file:</p> <pre><code>class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() read_time = models.TimeField(null=True, blank=True) view_count = models.IntegerF...
<p>Just query all objects and loop the queryset to manipulate them according to your needs like so:</p> <pre><code>def your_view(self, **kwargs): # Get all table entries of Model Post queryset = Post.objects.all() # Loop each object in the queryset for object in queryset: # Do some logic ...
python|django
1
4,756
36,359,210
Having pylint recognize custom module loader
<p>I have a custom module loader that basically does some redirection. I would like pylint to recognize this custom loader. This is my situation:</p> <pre><code>root/ __init__.py new/ __init__.py foo.py bar.py old/ __init__.py </code></pre> <p>I have a lot of clients import...
<p>from the <a href="https://docs.python.org/3/tutorial/modules.html#packages-in-multiple-directories" rel="nofollow">documentation on modules</a>:</p> <blockquote> <p>Packages support one more special attribute, <a href="https://docs.python.org/3/reference/import.html#__path__" rel="nofollow"><code>__path__</code><...
python|pylint
1
4,757
36,269,887
Reformatting my csv file by pandas (convert set of values to columns, matching another set to corresponding values)
<p>I have a dataset which I want to pre-process with pandas. This is a sample with two rows of that dataset:</p> <pre><code>| text | rank | date | provinces.0 | provinces.1 | provinces.2 | provinces.3 | provinces.4 | provinces.5 | provinces.6 | provinces.7 | provinces.8 ...
<p>This task was a little bit tricky:</p> <pre><code>import pandas as pd df = pd.read_csv(r'D:\download\Sheet1.csv') # `id_vars` helper list for `melt()` id_vars = df.columns[df.columns.str.contains('provinces\.')].tolist() # `value_vars` helper list for `melt()` val_vars = df.columns[df.columns.str.contains('provi...
python|numpy|pandas
2
4,758
43,894,387
Regex python remove colons and underscores
<p>I have a method that cleans tweets that I got from online, however I want to modify it so it will keep colons and underscores. I read the <a href="https://docs.python.org/2/library/re.html" rel="nofollow noreferrer">documentation</a> for regex in python and it seems the re.sub method is first finding the pattern, th...
<p>The ^ character has two meanings in regexps. It can be the beginning of the string or it can mean "not" if in between brackets ([]). In this case, it means not, which means all characters not specifically mentioned in that expression is removed. To have it <em>not</em> remove colon (:) you should add that to the mid...
python|regex
0
4,759
53,677,607
Error downloading pybluez on windows 10 with python 3.7 (64-bit)
<p>I was attempting to download the python module one windows 10 pybluez (using the cmd <code>pip install pybluez</code>, when I had this error:</p> <blockquote> <p>Collecting pybluez Using cached <a href="https://files.pythonhosted.org/packages/c1/98/3149481d508bee174335be6725880f00d297afebe75c15e917af8f6fe169/...
<p>First of all make sure that the location you are looking for is not hidden. In my case I had pip installed but the python directory wasn't showing up. Then make sure you have windows 10 SDK installed. You should have 19.0.3 v of pip in the python directory. If not then check: <a href="https://datatofish.com/upgrade-...
python|bluetooth|pip|pybluez
0
4,760
54,562,640
Capturing a SINGLE image from an rtsp H.264 video stream
<p>I'm trying to capture a single image on demand from an RTSP H.264 video frame. I'm using OpenCV with Python running on a Raspberry Pi. </p> <p>My understanding is that you can't simply capture an image, but rather must constantly read the stream of images from the video and discard all but the occasional one you ...
<p>The reason you have to read the stream is because H.264 has multiple kinds of frames (see <a href="https://en.wikipedia.org/wiki/Video_compression_picture_types" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/Video_compression_picture_types</a>) and P and B frames need context to be decoded. Only I-frames (...
python|opencv|raspberry-pi3|h.264|rtsp
2
4,761
54,449,128
How to specify a random number generator in numpy
<p>I'm building a monte carlo simulation using python, and have thus far been using numpy to generate my random variates. However, I've just learned that numpy uses the Mersenne Twister algorithm to produce its random numbers, which based on my limited understanding is not desireable in monte carlo simulations. I'd muc...
<p>Why don't you code it up yourself in python?</p> <p>I found an example implementation of the algorithm at <a href="http://simul.iro.umontreal.ca/rng/MRG32k3a.c" rel="nofollow noreferrer">http://simul.iro.umontreal.ca/rng/MRG32k3a.c</a> (with many others at <a href="http://www-labs.iro.umontreal.ca/~simul/rng" rel="...
python|numpy|random|montecarlo
1
4,762
9,057,645
Using ubuntu font on my web app
<p>I am planning to use Ubuntu font for my Django web app. I have downloaded the font here : <a href="http://font.ubuntu.com/" rel="nofollow">http://font.ubuntu.com/</a> . So far I managed to enable the font by putting link to Google API; by pasting this line of code in my html file <code>&lt;link rel="stylesheet" type...
<p>Which fonts from the typeface do you actually need?</p> <p>It is as simple as: <a href="http://fonts.googleapis.com/css?family=Ubuntu:regular,bold,italic" rel="nofollow">http://fonts.googleapis.com/css?family=Ubuntu:regular,bold,italic</a> returns:</p> <pre><code>@media screen { @font-face { font-family: 'Ubuntu...
python|django|ubuntu
2
4,763
39,238,340
python array inclusive slice index
<p>I wish to write a for loop that prints the tail of an array, <strong>including the whole array</strong> (denoted by i==0) Is this task possible without a branching logic, ie a <code>if i==0</code> statement inside the loop?</p> <p>This would be possible if there is a syntax for slicing with inclusive end index. </p...
<p>You can use <code>None</code>:</p> <pre><code>arr=[0,1,2,3,4,5] for i in range(0,3): print arr[:-i or None] </code></pre>
python|arrays|numpy
9
4,764
52,742,767
python takes my dictionary is taken for a tuple or a list
<p>I am trying to develop a personal finance program in python. My expenses are divided into categories, which in turn are divided into subcategories. I am using nested dictinaries to hold this data as shown below:</p> <pre><code>categorias_gastos = {'alimentacao_limpeza':{'almoco':0, ...
<p>One thing that looks like a problem: You have defined a global <code>categorias_gastos</code> twice. </p> <p>The second definition will overwrite the first, and it's a list of tuples rather than a dict. Use a different name for your radiobutton tuples, and/or hide it inside (say) a "make_radiobuttons" function.</p>
python|list|dictionary|callback|tuples
0
4,765
52,882,789
Python: [Errno 13] Permission Denied
<p>I am currently trying to get a random joke selector/ teller to get to work. I am kinda new to Python but have some scripting experience with other languages. I will now put the error Code:</p> <pre><code>&gt; Traceback (most recent call last): File "C:\Users\drkater\Desktop\Crap\Projekte\Voice Assitant\Jarvis.py"...
<p>You should change the permission on you file 'audio.mp3'. Check the permissions on your file with the shell commande <code>ls -l</code> and use <code>chmod a+rw audio.mp3</code> to make your file writable. You can find a question on a similar problem <a href="https://stackoverflow.com/questions/13207450/permissioner...
python|errno
1
4,766
47,960,757
My python script, which recursively renames files, fails
<p>I'm trying to recursively rename the files in a directory, so I wrote a python script to handle the renaming. So ideally, the script should be able to turn this</p> <pre><code>Nicholass-MacBook-Air-2:RenameXtalTest nick$ ls RM01_03_000_0213_Proj1_Clon1_RC_0000RC000870_010_171222_01_03_02_E0_00_031_001_RAI.jpg RM01_...
<p>A combination of the comments of @mooiamaduck and me gives this code:</p> <pre><code>for oldname in os.listdir("."): if len(oldname) &lt; 70: continue newname = oldname[36:44]+"-"+rowdic[oldname[59:61]]+coldic[oldname[56:58]]+"_"+subwdic[oldname[62:64]]+"-"+oldname[65:70]+".jpg" os.rename(oldna...
python|dictionary|for-loop|subprocess|substring
0
4,767
47,934,184
mortal kombat console game python2
<p>I just try to make a fighting game that work on console.It's almost finished but I have 2 problem.</p> <ol> <li><p>The game should finish when a user's hp decrease to 1.It doesn't finishing when hp is 0.It gives one more chance to other user.</p></li> <li><p>Other one is,after that the game finish,I wanna ask to us...
<ol> <li>you have to check <code>hp1</code> before you second player makes move.</li> <li>You have to put it in <code>while</code> loop which will: set <code>hp</code> to <code>100</code>, run game, ask if you want ot play again.</li> </ol> <p>I made other changes</p> <ul> <li><code>attack1</code> and <code>attack2</...
python|python-2.7
0
4,768
47,823,477
Write data in cell into csv file based on dictionary value
<p>I'm trying to write data to an CSV column based on a dictionary value. For instance, I have a for-loop which will generate one dictionary in each loop</p> <pre><code>{JLKJ: 1} {BNMM: 4} {HUGF: 5}... </code></pre> <p><a href="https://i.stack.imgur.com/9PNC6.jpg" rel="nofollow noreferrer">example</a></p> <p>My goal...
<p>I find this design a bit jarring. Is there a specific reason why you use only one key with a dictionary? What you could do instead is keep a single dictionary where each value is a list of elements for that particular key. So your code would look something like this:</p> <pre><code>from collections import defaultdi...
python|csv|dictionary
0
4,769
37,174,826
Running progress bar in a different thread - Pyside
<p>I would like to run a progress bar in a different thread from the rest of my code, but I would like to control how the progress bar updates from my main thread.</p> <p>Is this something which is possible?</p> <p>This is what I have so far:</p> <pre><code>import time from PySide import QtGui from PySide import QtC...
<p>I believe <a href="https://stackoverflow.com/questions/37174826/running-progress-bar-in-a-different-thread-pyside#comment61886252_37174826">bnaecker</a>, <a href="https://stackoverflow.com/questions/37174826/running-progress-bar-in-a-different-thread-pyside#comment61891350_37174826">Brendan Abel</a> and <a href="htt...
python|pyqt|pyside|qthread|nuke
2
4,770
66,022,520
PyQt5 QTableView Updating view on button click
<p>How do I get my QTableView to update when a button is pushed? Utilizing pandas dataframe and standard setup as source of data for table. I understand that it's not (addWidget(self.view) is only called once), but what do I need to change to have it update? (print(data) in code confirms the dataframe is being update...
<pre><code>class Tabs_Widget(QWidget): def __init__(self): super().__init__() self.setWindowTitle('Adjustments') self.df = pd.DataFrame() self.model = QModel(self.df) self.view = QTableView() self.view.setModel(self.model) self.view.setAlternatingRowColors(True) sel...
python|pyqt5|qtableview
0
4,771
7,481,338
Custom View on a table in the administration console
<p>I have a simple table in my Django app that looks like:</p> <pre><code>class Setting(models.Model): group = models.CharField(null=False, max_length=255) name = models.CharField(null=False, max_length=255) value= models.CharField(null=False, max_length=255) </code></pre> <p>For reasons, I'm storing the ...
<p>Simple solution - make the fields in admin's object <a href="https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_editable" rel="nofollow">list editable</a>:</p> <pre><code>class SettingsAdmin(admin.ModelAdmin): list_display = ('group', 'name', 'value') list_editable...
python|django|django-models|django-admin
0
4,772
7,572,901
Python/html- Combine multiple html's into one
<p>I've written a python script to convert a text file to html file. But that is kind of useless if I can't put them all together. What I'm supposed to do is display all the reports onto the website (the server part is not my problem). Now I can convert each file to an html but I just realize it's a huge library of fil...
<p>Create a list of tuples in Python. Then sort them in place. Then iterate over the list and produce your homepage HTML. Below an example. You need to fill in the URLs and the date for each report (either as a date object or as a string, example: '09-12-2011')</p> <pre><code>report_tuples = [ ('http://www.myrepor...
python|html
6
4,773
72,635,181
How do I properly format a SOAP request using Python's Zeep library?
<p>Here is the WSDL I'm using: <a href="http://sprws.sprich.com/sprws/StockCheck.php?wsdl" rel="nofollow noreferrer">http://sprws.sprich.com/sprws/StockCheck.php?wsdl</a> Using SoapUI the input looks like this:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div cla...
<p>I get an ERR_CONNECTION_TIMED_OUT error when trying to open the WSDL, but based on the comment you posted, the operation method looks like this:</p> <pre><code>StockCheck(input: ns0:StockCheckInputs) -&gt; return: ns0:StockCheckRsults </code></pre> <p>But you are trying to make a call like this:</p> <pre><code>clien...
python|soap|zeep
0
4,774
39,622,121
NLTK perceptron tagger "TypeError: 'LazySubsequence' object does not support item assignment"
<p>I would like to try and use the <code>PerceptronTagger</code> in the <code>nltk</code> package for Python 3.5, But I am getting the error <code>TypeError: 'LazySubsequence' object does not support item assignment</code></p> <p>I would like to train it with data from the brown corpus with the <code>universal</code> ...
<h1>Debugging</h1> <p>Doing some <code>grep</code>ing in the <code>nltk</code> source code found the answer.</p> <p>In the file <code>site-packages/nltk/util.py</code> the class is declared.</p> <pre><code>class LazySubsequence(AbstractLazySequence): """ ...
classification|nltk|anaconda|python-3.5|perceptron
5
4,775
16,470,127
Link Fetching List
<p>so I've asked many questions regarding this one subject, and I'm sorry. But this is it. </p> <p>So I have this code:</p> <pre><code>import urllib import urllib.request from bs4 import BeautifulSoup import sys from collections import defaultdict m_num=int(input('Enter number of monsters to look up: ')) for x in ra...
<p><code>link_lists</code> refers to a new dictionary on each iteration. You could exclude it: put <code>all_lists = []</code> before the <code>for x in range(m_num)</code> loop. And replace the last 3 line in the loop with: <code>all_lists.append([link.get("title") for link in links])</code> Note: you don't need to kn...
python|list|python-3.x|compare|wiki
1
4,776
16,088,279
Logging to specific error log file in scrapy
<p>I am running a log of scrapy by doing this:</p> <pre><code>from scrapy import log class MySpider(BaseSpider): name = "myspider" def __init__(self, name=None, **kwargs): LOG_FILE = "logs/spider.log" log.log.defaultObserver = log.log.DefaultObserver() log.log.defaultObserver.start() ...
<p>Just let <a href="http://docs.python.org/2/library/logging.html" rel="noreferrer">logging</a> do the job. Try to use <code>PythonLoggingObserver</code> instead of <code>DefaultObserver</code>:</p> <ul> <li>configure two loggers (one for <code>INFO</code> and one for <code>ERROR</code> messages) directly in python, ...
python|logging|web-scraping|scrapy|scrapy-spider
11
4,777
32,132,890
How to convert a list of tuples into different csv files
<p>I have a list of tuples like this:</p> <pre><code>List=[ ('1',['45','55','56','57']) , ('2',['200','202','202']) , ('3',['500','501','502'])] </code></pre> <p>As can be seen, three tuples of size 2.</p> <p>I want to convert this list into three different csv files. </p> <p>The output should be three different cs...
<p>While the files you want are valid CSV files, they're so trivial there's no need to use the <code>csv</code> module to create them (or read them).</p> <pre><code>data = [ ('1', ['45', '55', '56', '57']), ('2', ['200', '202', '202']), ('3', ['500', '501', '502']), ] for dataset_name, dataset in data...
python|list|csv
3
4,778
31,707,147
Python HTTP Error 429 with urllib2
<p>I am using the following code to resolve redirects to return a links final url</p> <pre><code>def resolve_redirects(url): return urllib2.urlopen(url).geturl() </code></pre> <p>Unfortunately I sometimes get <code>HTTPError: HTTP Error 429: Too Many Requests</code>. What is a good way to combat this? Is the foll...
<p>It would be better to make sure the HTTP code is actually 429 before re-trying.</p> <p>That can be done like this:</p> <pre><code>def resolve_redirects(url): try: return urllib2.urlopen(url).geturl() except HTTPError, e: if e.code == 429: time.sleep(5); return reso...
python|urllib|http-status-code-429
4
4,779
40,557,499
define shared array in GPU memory with Python?
<p>I am trying to use an array shared by multiple processes with Python. And I did a CPU version by defining the array with <code>multiprocessing.RawArray</code> and using the array with <code>numpy.frombuffer()</code>. When I tried to port the code to GPU with <code>chainer.cuda.to_gpu()</code>, I found that each pr...
<p>There may be a way to solve your problem.</p> <p>Just look here:</p> <pre><code>sudo nvidia-smi Mon Nov 14 16:14:48 2016 +------------------------------------------------------+ | NVIDIA-SMI 358.16 Driver Version: 358.16 | |--------------------------...
python|arrays|numpy|multiprocessing
1
4,780
1,517,778
Python Image Library ellipse with wide outline
<p>When creating an ellipse with PIL, is it possible to have a thicker/wider outline? Currently, I'm trying to do <code>canvas.ellipse(box, outline=colour, fill=None)</code>, but would like to be able to give the <code>outline</code> parameter a width.</p>
<p>You could use the <a href="http://effbot.org/zone/aggdraw-index.htm" rel="nofollow noreferrer">aggdraw</a> advanced-graphics add-on module to PIL -- with it, the method to draw an ellipse, like others, takes a <code>pen</code> object which you can make with your favorite width (as well as color and opacity).</p>
python|image|python-imaging-library
1
4,781
1,672,532
How to generate graphical sitemap of large website
<p>I would like to generate a graphical sitemap for my website. There are two stages, as far as I can tell:</p> <ol> <li>crawl the website and analyse the link relationship to extract the tree structure </li> <li>generate a visually pleasing render of the tree</li> </ol> <p>Does anyone have advice or experience with ...
<p>The only automatic way to create a sitemap is to know the structure of your site and write a program which builds on that knowledge. Just crawling the links won't usually work because links can be between any pages so you get a graph (i.e. connections between nodes). There is no way to convert a graph into a tree in...
python|web|sitemap|web-crawler
4
4,782
1,561,655
Google wave robot inline reply
<p>I've been working on my first robot for google wave recently, a vital part of what it does is to insert inline replies into a blip. I can't for the life of me figure out how to do this!</p> <p>The API docs have a function <a href="http://wave-robot-python-client.googlecode.com/svn/trunk/pydocs/waveapi.ops.OpBasedDo...
<p>If you look at the <a href="http://wave-robot-python-client.googlecode.com/svn/trunk/pydocs/waveapi.ops-pysrc.html#OpBasedDocument.InsertInlineBlip" rel="nofollow noreferrer">sourcecode</a> for <code>OpBasedDocument.InsertInlineBlip()</code> you will see the following:</p> <pre><code> 412 - def InsertInlineBlip(se...
python|google-wave
4
4,783
54,827,512
How to slice for loop correctly?
<p>I want to reverse a for loop such that it stops at a certain value the user inputted.</p> <p>For example, if there is a list <code>Hello = [1,2,3,4,5,6,7,8]</code> and the user inputs a 5 is there a way to get the output </p> <p>4</p> <p>5</p> <p>6</p> <p>7</p> <p>8</p> <p>I've tried </p> <pre><code>user_inp...
<p>This is a simple way:</p> <pre><code>user_input = int(input()) Hello = [1,2,3,4,5,6,7,8] print(Hello[-user_input:]) </code></pre> <blockquote> <p>output:</p> <p><code>[4, 5, 6, 7, 8]</code></p> </blockquote> <p>&nbsp;</p> <p>If you want every number to be printed on its own line, you can do it like this:...
python|python-3.x|list
5
4,784
44,027,343
Python: how to pollute namespace with Enum values
<p>Curious if someone else has done this before.</p> <p>I'd like to pollute my namespace with enum values.</p> <p>For example in my code I'd like to refer to RED, GREEN and BLUE instead of Color.RED, Color.GREEN, and Color.BLUE.</p> <p>The straightforward way would be to, after defining the enum, put <code>RED = Col...
<p>I'm not exactly sure <em>why</em> you would want to do this, but you can update <code>locals</code> in your module on the fly.</p> <p><strong>Note: Not recommended</strong> </p> <pre><code>import enum class Color(enum.Enum): RED = 1 GREEN = 2 BLUE = 3 locals().update({color.name: color for color in C...
python|enums
2
4,785
33,039,884
MiniBatchKMeans Python
<p>I am using the function MiniBatchKMeans() from scikitlearn. Well, in its documentation there are:</p> <blockquote> <p><strong>batch_size</strong> : int, optional, default: 100 Size of the mini batches.</p> <p><strong>init_size</strong> : int, optional, default: 3 * batch_size Number of samples to random...
<p>The batch size is defined by <code>batch_size</code>, period. Furthermore you can define <code>init_size</code> which is the size of samples taken to <strong>initiallize</strong> the process, and <strong>by default</strong> it is 3*<code>batch_size</code>. You can simply set <code>bath_size=100</code> and <code>init...
python|machine-learning|scikit-learn|cluster-computing
2
4,786
54,294,935
Comparing Python Dictionaries
<p>I created two dictionaries. Each is based on a different query of the same database. There is a key and four fields from the database in each dictionary. I want to find all rows of dict_x that are in are in dict_y.</p> <pre><code> for row in dict_x: if dict_y.values() not in dict_x.values(): del dict_x...
<p>The steps to solve the problem would be to </p> <blockquote> <ol> <li>Invert the key value pairs of the dictionaries</li> <li>Identify the common intersecting keys </li> <li>Loop through the keys and check if their values match</li> </ol> </blockquote> <p>The code could look something like below</p> ...
python|dictionary
0
4,787
34,780,253
Efficiently String searching in Python
<p>Let's say I had a database of like 2,000 keywords, which each map to a few common variations </p> <p>For example:</p> <pre><code> "Node" : ["node.js", "nodejs", "node js", "node"] "Ruby on Rails" : ["RoR", "Rails", "Ruby on Rails"] </code></pre> <p>and I want to search a string (ok, a document) and return a li...
<p>You can use a data-structure which inverts this dictionary of keywords - so that each of <code>["node.js", "nodejs", "node js", "node", "Node"]</code> is a key with the value "Node" - each other of the 10 or so variants for the other 2000 keywords points to one of the keywords - so a 20000 sized dictionary, which i...
python|regex|algorithm|elasticsearch|tags
5
4,788
27,408,929
I want to scrape all the text data from a page of website if that page contains some specific word.. But this code s showing errors
<p>I want to scrape all the text data from a website's page if that page contains some specific words.I have written this code to collect the data from a page if that page contains searchphrase.. but it id giving error after running..</p> <pre><code> import urllib2 from bs4 import BeautifulSoup import ...
<p>As discussed above this might not be exactly what the OP intended</p> <p>This program takes a start url. It then finds hrefs in the page. Does some pointless manipulation on the hrefs that ICBA to refactor :) and retrieves the objects that the hrefs point to.</p> <p>Finally, if the data in the object retrieved ...
python-2.7|beautifulsoup|web-crawler|urllib2|ubuntu-14.04
0
4,789
12,419,750
Testing Microphone Linux command or python
<p>I think this question might has been asked. But I can find it.</p> <p>My question is: I want to write a small program in python to run on Linux to record the user's voice with a record button. But I want to check if the microphone is detected than the record button is enable otherwise it will be disable.</p> <p>I ...
<p>If just a simple script then wrap arecord with <a href="http://docs.python.org/2/library/subprocess.html" rel="nofollow">subprocess</a></p> <p>Or if need something more robust try <a href="http://pyalsaaudio.sourceforge.net/pyalsaaudio.html" rel="nofollow">pyalsaaudio</a></p>
python|linux|microphone
0
4,790
12,592,501
Serialize MD5 computation-state and resume later?
<p>I want to serialize/deserialize md5 context. But I don't know how to do it in Python. Pseudocode of what I want to do.</p> <pre><code>import md5 # Start hash generation m = md5.new() m.update("Content") # Serialize m serialized_m = serialize(m) # In another function/machine, deserialize m # and continue hash gene...
<p>HASH objects are not serializable: <a href="https://stackoverflow.com/questions/8962523/how-to-serialize-hash-objects-in-python">How to serialize hash objects in Python</a></p> <p>Assuming you can pass around the unhashed data:</p> <pre><code>from Crypto.Hash import MD5 # generate hash m = MD5.new() s = "foo" m.u...
python|security|hash|md5
1
4,791
8,157,688
Specifying an index in QTableView with PyQt
<p>I have a table and I want to see the data at a specific coordinate- say Row 2, Column 5. I create a QPoint object with those values set, but when that gets translated into a QModelIndex object, I get Row 0 and Column 1.</p> <p>Here's the code:</p> <pre><code> myQPoint = QPoint() myQPoint.setX(2) myQPoin...
<p>If you want to get the contents of an index at a specified column and row, use <code>QTableView.model().index(row, column).data()</code>.</p> <p><code>QTableView.model(row, column)</code> returns a <code>QModelIndex</code> object ( <a href="http://doc.qt.nokia.com/latest/qmodelindex.html" rel="noreferrer">http://do...
python|pyqt
5
4,792
41,790,345
List index out of range,python troubleshooting
<pre><code>for i in range(0,len(text_list)): if (text_list[i] == "!" and text_list[i+1].isupper()): print "something" else: text_list.pop(i) </code></pre> <p><code>Traceback</code> (most recent call last):</p> <pre><code> File "test.py", line 12, in &lt;module&gt; if (text_list[i]=="!" an...
<p>When <code>i</code> becomes <code>len(text_list) - 1</code>, <code>i + i</code> is out of bounds. This is your first problem. The second problem is that you are popping within the for loop. This changes the size of the list.</p> <p>I suggest to save the indices to be removed in a separate list, and then pop them af...
python-2.7
0
4,793
47,442,953
How to gather all links from a webpage?
<p>How to gather links from "View More Campaigns" using Python 3? I wish to gather all 260604 links from this page? <a href="https://www.gofundme.com/mvc.php?route=category&amp;term=sport" rel="nofollow noreferrer">https://www.gofundme.com/mvc.php?route=category&amp;term=sport</a></p>
<p>When clicking on the <code>View More Campaigns</code> button, the browser requests the following URL:</p> <pre><code>https://www.gofundme.com/mvc.php?route=category/loadMoreTiles&amp;page=2&amp;term=sport&amp;country=GB&amp;initialTerm= </code></pre> <p>This could be used to request further pages as follows:</p> ...
python|python-3.x|web-scraping|beautifulsoup
2
4,794
47,205,303
How to fix the error message?
<p>This is the first time im writing a program with python and im trying to only allow the user to input 8 digits. I managed to do this and every time i enter more or less than 8 it gives the error message which is good but after that if i enter 8 digits it still gives the error message</p> <pre><code> value3 = inp...
<p>You should not use <code>While True:</code> in your <code>if</code> statements. </p> <p>You can do something like this:</p> <pre><code>value3 = input("please enter your card number: ") while True: if not value3.isdigit(): value3= input("please enter your card NUMBER, Only digits are allowed: ") ...
python
2
4,795
71,074,314
Pyinstaller EXE Files are not independent?
<p>I used pyinstaller to compile my pygame code into an exe file using this command: <code>pyinstaller --onefile -w gamename.py</code> But after moving it to a different directory and running it, it gives me file not found errors and file doesn't exist errors. ALL help is greatly appreciated. Thanks.</p>
<p>Possibly, you have some file locations in your code as strings. These external files are not part of your code, so they are not compiled into exe.</p> <p>Check <a href="https://stackoverflow.com/a/59710336/18176048">this answer</a> about adding files in pyinstaller</p>
python|pygame|pyinstaller
1
4,796
11,978,864
Django instances building up until crashes site (UPDATE: Redis deadlock HIGHLY suspected)
<p><strong>See EDIT#2 below for likely root cause</strong></p> <p>My Django threads/processes (same thing happens when using both 'method=threaded' and 'method=prefork'), every 10 mins or so, randomly build up like so: <a href="http://i.imgur.com/VyUAv.png" rel="nofollow">http://i.imgur.com/VyUAv.png</a> e.g lots of t...
<p>Threads and processes are two different things. The cause will most likely be threads if the entire site goes down. </p>
python|django|nginx|redis|deadlock
0
4,797
33,684,378
np array as optional arguments
<p>I have a function that can accept two optional <code>np.array</code> as arguments. In case <em>both</em> are passed the function should do perform some task.</p> <pre><code>def f(some_stuff, this=None, that=None): ...do something... if this and that: perform_the_task() </code></pre> <p>This works as...
<p>Firstly, you <em>can</em> assume that they will be the right type (especially if you're the only one using the code). Just add it to the documentation. <a href="https://stackoverflow.com/questions/734368/type-checking-of-arguments-python">Type checking of arguments Python</a> (the accepted answer even sighs as they ...
python|arrays|numpy
7
4,798
46,708,241
pandas groupby: how to calculate percentage of total?
<p>How can I calculate a column showing the % of total in a <code>groupby</code>?</p> <p>One way to do it is to calculate it manually after the <code>groupby</code>, as in the last line of this example:</p> <pre><code>import numpy as np import pandas as pd df= pd.DataFrame(np.random.randint(5,8,(10,4)), columns=['a','b...
<p>I think you need <code>lambda function</code> in <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.DataFrameGroupBy.agg.html" rel="nofollow noreferrer"><code>agg</code></a> and then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.replace.html" rel="no...
python|pandas
2
4,799
37,613,883
py.test passing results of one test to another
<p>Currently I have test looking like this:</p> <pre><code>@pytest.mark.parametrize("param", [1,2,3]) def test_two_services(param): id = check_service_one(param) check_service_two(id) </code></pre> <p>Is there any way to split this test in two, where a second test depends on a first?</p>
<p>Remember to test at the boundary. So if the the values of <code>id</code> depend solely on <code>param</code> and if <code>id</code> isn't some implementation detail, but a part of the defined behaviour of the system under test, split up your tests like so:</p> <pre><code>def test_service_one(param, id): assert...
python|python-2.7|unit-testing|automated-tests|pytest
2