title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags list |
|---|---|---|---|---|---|---|---|---|---|
Fastest way to merge 2 dictionaries, if one dict's key equals to the other dict's values? | 40,069,059 | <p>Suppose I have 2 dictionaries</p>
<pre><code>dict1 = {(1,1,1) : ('abc'), (2,2,2) : ('def')}
dict2 = {('abc') : (1,2,3), ('def') : (4,5,6)}
</code></pre>
<p>What is the fastest way to produce a dict 3 such that</p>
<p><code>dict3 = {(1,1,1):(1,2,3), (2,2,2):(4,5,6)}</code>?</p>
| 0 | 2016-10-16T10:01:51Z | 40,069,123 | <p>You can use a dictionary comprehension:</p>
<pre><code>dict1 = {(1,1,1) : ('abc'), (2,2,2) : ('def')}
dict2 = {('abc') : (1,2,3), ('def') : (4,5,6)}
dict3 = {k: dict2[dict1[k]] for k in dict1}
>>> print dict3
{(2, 2, 2): (4, 5, 6), (1, 1, 1): (1, 2, 3)}
</code></pre>
<p>This iterates over the <em>keys</... | 2 | 2016-10-16T10:11:18Z | [
"python",
"dictionary"
] |
count the number of groups of consecutive digits in a series of strings | 40,069,151 | <p>consider the <code>pd.Series</code> <code>s</code></p>
<pre><code>import pandas as pd
import numpy as np
np.random.seed([3,1415])
p = (.35, .35, .1, .1, .1)
s = pd.DataFrame(np.random.choice(['', 1] + list('abc'), (10, 20), p=p)).sum(1)
s
0 11111bbaacbbca1
1 1bab111aaaaca1a
2 11aaa1b11a11a11
3 1ca11... | 3 | 2016-10-16T10:14:38Z | 40,069,177 | <p><strong>UPDATE:</strong> the idea is first to replace all consecutive groups of digist with single <code>1</code> and then delete everything which is not <code>1</code> and finally get the length of the changed string:</p>
<pre><code>In [159]: s.replace(['\d+', '[^1]+'], ['1', ''], regex=True).str.len()
Out[159]:
0... | 4 | 2016-10-16T10:18:01Z | [
"python",
"pandas"
] |
count the number of groups of consecutive digits in a series of strings | 40,069,151 | <p>consider the <code>pd.Series</code> <code>s</code></p>
<pre><code>import pandas as pd
import numpy as np
np.random.seed([3,1415])
p = (.35, .35, .1, .1, .1)
s = pd.DataFrame(np.random.choice(['', 1] + list('abc'), (10, 20), p=p)).sum(1)
s
0 11111bbaacbbca1
1 1bab111aaaaca1a
2 11aaa1b11a11a11
3 1ca11... | 3 | 2016-10-16T10:14:38Z | 40,069,202 | <p>This was my solution</p>
<pre><code>s.str.replace(r'\D+', ' ').str.strip().str.split().str.len()
</code></pre>
<p><strong><em>100,000 rows</em></strong></p>
<pre><code>np.random.seed([3,1415])
p = (.35, .35, .1, .1, .1)
s = pd.DataFrame(np.random.choice(['', 1] + list('abc'), (100000, 20), p=p)).sum(1)
</code></p... | 2 | 2016-10-16T10:21:00Z | [
"python",
"pandas"
] |
count the number of groups of consecutive digits in a series of strings | 40,069,151 | <p>consider the <code>pd.Series</code> <code>s</code></p>
<pre><code>import pandas as pd
import numpy as np
np.random.seed([3,1415])
p = (.35, .35, .1, .1, .1)
s = pd.DataFrame(np.random.choice(['', 1] + list('abc'), (10, 20), p=p)).sum(1)
s
0 11111bbaacbbca1
1 1bab111aaaaca1a
2 11aaa1b11a11a11
3 1ca11... | 3 | 2016-10-16T10:14:38Z | 40,069,408 | <p>PiRSquared and MaxU solutions are great.</p>
<p>However, I noticed <code>apply</code> is usually a bit faster than using multiple string methods.</p>
<pre><code>In [142]: %timeit s.apply(lambda x: len(re.sub('\D+', ' ', x).strip().split()))
1 loop, best of 3: 367 ms per loop
In [143]: %timeit s.str.replace(r'\D+'... | 4 | 2016-10-16T10:46:29Z | [
"python",
"pandas"
] |
Setting diagonal mirroring via Jython (user to set points) | 40,069,185 | <p>Trying to get my my head around this program we need to create
What is needed is as per the notes:
create a function named
arbitraryMirror() that allows the user to place a mirror at an arbitrary angle, causing an intersect and therefore mirror the image.</p>
<p>This will need to be done on either a square or recta... | 2 | 2016-10-16T10:18:28Z | 40,079,399 | <p>I do not have an answer for you but would love to know myself</p>
| 1 | 2016-10-17T05:59:38Z | [
"python",
"jython",
"jes"
] |
Setting diagonal mirroring via Jython (user to set points) | 40,069,185 | <p>Trying to get my my head around this program we need to create
What is needed is as per the notes:
create a function named
arbitraryMirror() that allows the user to place a mirror at an arbitrary angle, causing an intersect and therefore mirror the image.</p>
<p>This will need to be done on either a square or recta... | 2 | 2016-10-16T10:18:28Z | 40,079,852 | <p>The key formulas are (python):</p>
<pre><code># (x0, y0) and (x1, y1) are two points on the mirroring line
# dx, dy, L is the vector and lenght
dx, dy = x1 - x0, y1 - y0
L = (dx**2 + dy**2) ** 0.5
# Tangent (tx, ty) and normal (nx, ny) basis unit vectors
tx, ty = dx / L, dy / L
nx, ny = -dy / L, dx / L
# For each... | 1 | 2016-10-17T06:33:19Z | [
"python",
"jython",
"jes"
] |
Is there a more Pythonic/elegant way to expand the dimensions of a Numpy Array? | 40,069,220 | <p>What I am trying to do right now is:</p>
<pre><code>x = x[:, None, None, None, None, None, None, None, None, None]
</code></pre>
<p>Basically, I want to expand my Numpy array by 9 dimensions. Or some N number of dimensions where N might not be known in advance!</p>
<p>Is there a better way to do this?</p>... | 1 | 2016-10-16T10:23:24Z | 40,069,249 | <p>One alternative approach could be with <code>reshaping</code> -</p>
<pre><code>x.reshape((-1,) + (1,)*N) # N is no. of dims to be appended
</code></pre>
<p>So, basically for the <code>None's</code> that correspond to singleton dimensions, we are using a shape of length <code>1</code> along those dims. For the fir... | 0 | 2016-10-16T10:26:49Z | [
"python",
"arrays",
"numpy",
"multidimensional-array"
] |
getting an int from a list (pygame) | 40,069,295 | <p>i am trying to make a 'snake'-like game in python.
My problem right now is that I can't use the defined values from my 'coinlist' in my for-loop. This is the error that i receive if i execute it: TypeError: 'int' object is not subscriptable. Thanks for your help. </p>
<pre><code>import pygame
import random
pygame.... | 0 | 2016-10-16T10:32:25Z | 40,069,353 | <p>You're appending ints to coinlist (rx and ry are random ints from 10 to 790/590) and later on you're trying to access elements within coinlist as if they are arrays.</p>
<p>Consider doing something like replacing</p>
<pre><code>coinlist.append(rx)
coinlist.append(ry)
</code></pre>
<p>with</p>
<pre><code>coinlist... | 3 | 2016-10-16T10:39:18Z | [
"python",
"for-loop",
"pygame"
] |
Pandas: sep in read_csv doesn't work | 40,069,307 | <p>I try to <code>read_csv</code> </p>
<pre><code>e29bea24f74b7fb26cb9c14ef8c3b10b,ozon.ru/context/detail/id/33849562,2016-03-27 01:08:43,16,,Р СâºÐ  Рâ¦Ð  Ð»Р Ð°Р вââÐ Â Ð â¦-Р СР Ð°Р СâÐ Â Ð°Р Ð·Р СâÐ Â Ð â¦
e29bea24f74b7fb26cb9c14ef8c3b10b,ozon.ru/context/detail/id/2474... | -1 | 2016-10-16T10:33:17Z | 40,079,302 | <p>It works on my laptop.</p>
<p>What's your pandas version? Is your file encoded as UTF-8? Can you try if this work?</p>
<pre><code>df = pd.read_csv(
'pv-lena11.csv', sep=',', header=None, names=names,
quoting=0, encoding='utf8')
</code></pre>
| 0 | 2016-10-17T05:49:59Z | [
"python",
"pandas"
] |
cv2.imread() gives diffrent results on Mac and Linux | 40,069,346 | <p><code>cv2.imread(JPG_IMAGE_PATH)</code> gives different arrays on Mac and Linux. </p>
<p>This may be because of the reason described <a href="http://docs.opencv.org/2.4/modules/highgui/doc/reading_and_writing_images_and_video.html?highlight=imread#imread" rel="nofollow">here</a> (see Note).</p>
<p>Is there any sol... | 1 | 2016-10-16T10:38:55Z | 40,069,673 | <p>you can build opencv & libjpg from source in both linux & mac. Using cmake you can build opencv with libjpg support (from source code). Hope this will give you same result.</p>
<pre><code>cmake -DWITH_JPEG=ON -DBUILD_JPEG=OFF -DJPEG_INCLUDE_DIR=/path/to/libjepeg-turbo/include/ -DJPEG_LIBRARY=/path/to/libjpe... | 0 | 2016-10-16T11:21:36Z | [
"python",
"opencv"
] |
I can not parse html using xpath and lxml library | 40,069,358 | <p>I`m using Python 3.5.
I want to get a list of synonyms from the site, with the help of XPATH, but I do not get the required html code and get "[]".</p>
<pre><code>import lxml.html
word=input("Input your word: ")
url = "http://www.thesaurus.com/browse/{word}?s=t.html".format(word=word)
html = lxml.html.parse(url)
sy... | -1 | 2016-10-16T10:39:35Z | 40,069,541 | <p>Just imagining you need Synonyms extracted :</p>
<pre><code>import requests
from lxml import html
source = html.fromstring(((requests.get('http://www.thesaurus.com/browse/wordy?s=t.html')).text).encode('utf-8'))
print (source.xpath('//div[@class="synonym-description"]//text()')[3].strip())
</code></pre>
| -1 | 2016-10-16T11:04:16Z | [
"python",
"python-3.x",
"parsing",
"xpath",
"lxml"
] |
I can not parse html using xpath and lxml library | 40,069,358 | <p>I`m using Python 3.5.
I want to get a list of synonyms from the site, with the help of XPATH, but I do not get the required html code and get "[]".</p>
<pre><code>import lxml.html
word=input("Input your word: ")
url = "http://www.thesaurus.com/browse/{word}?s=t.html".format(word=word)
html = lxml.html.parse(url)
sy... | -1 | 2016-10-16T10:39:35Z | 40,069,572 | <p>The xpath-syntax is case sensitive:</p>
<pre><code>syn = html.xpath("//div[@id='filters-0']")
print(syn)
</code></pre>
| 0 | 2016-10-16T11:08:31Z | [
"python",
"python-3.x",
"parsing",
"xpath",
"lxml"
] |
Pywin32 Working directly with Columns and Rows like it would be done in VBA | 40,069,371 | <p>I am starting to migrate some of my VBA code into Python, because it gives me more resources. However I am having troubles to work in similar way.</p>
<p>I wanted to clear some Columns, however I cannot work directly with the attribute Columns of the worksheet. And I have to do turnarounds like this (full code):</p... | 0 | 2016-10-16T10:41:36Z | 40,072,190 | <p>Simply run: <code>sh.Columns("A:D").Clear</code>. It should be noted that you are not translating VBA code to Python. Both languages are doing the same thing in making a COM interface to the Excel Object library. Because the Office applications ships with VBA, it is often believed that VBA <em>is</em> the language f... | 1 | 2016-10-16T15:50:22Z | [
"python",
"excel",
"win32com"
] |
How to accept only 5 possible inputs | 40,069,487 | <p>In my program I have a menu that looks like this:</p>
<pre><code>MenuChoice = ''
while MenuChoice != 'x':
print("Type 1 to enter the first option")
print("Type 2 to enter the second option")
print("Type 3 to enter the third option")
print("Type 4 to enter the fourth option")
print("Press x to quit")
try:
Menu... | -2 | 2016-10-16T10:58:01Z | 40,069,593 | <p>You're right to use a <code>while</code> loop, but think of what condition you want. You want only the numbers 1-5 right? So it would make sense to do:</p>
<pre><code>MenuChoice = 0
print("Type 1 to enter the first option")
print("Type 2 to enter the second option")
print("Type 3 to enter the third option")
print("... | 1 | 2016-10-16T11:10:31Z | [
"python",
"error-handling",
"menu"
] |
How to accept only 5 possible inputs | 40,069,487 | <p>In my program I have a menu that looks like this:</p>
<pre><code>MenuChoice = ''
while MenuChoice != 'x':
print("Type 1 to enter the first option")
print("Type 2 to enter the second option")
print("Type 3 to enter the third option")
print("Type 4 to enter the fourth option")
print("Press x to quit")
try:
Menu... | -2 | 2016-10-16T10:58:01Z | 40,069,888 | <p>I think he needs a While true loop . Did using python 2.X</p>
<pre><code>import time
print("Type 1 to enter the first option")
print("Type 2 to enter the second option")
print("Type 3 to enter the third option")
print("Type 4 to enter the fourth option")
print("Press x to quit")
while True:
try:
print ... | 0 | 2016-10-16T11:48:36Z | [
"python",
"error-handling",
"menu"
] |
I am taking Selenium error | 40,069,518 | <pre><code>Using 1 seconds of delay
Traceback (most recent call last):
File "instaBrute.py", line 142, in <module>
main()
File "instaBrute.py", line 136, in main
driver = webdriver.Firefox(profile)
File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/firefox/webdriver.py", line 135, in __... | -3 | 2016-10-16T11:02:00Z | 40,069,955 | <p>Choose appropriate version of the driver from <a href="https://github.com/mozilla/geckodriver/releases" rel="nofollow">this page</a>, download and unarchive it, then place to the directory your script is located at.</p>
| 0 | 2016-10-16T11:55:37Z | [
"python",
"selenium"
] |
How to save split data in panda in reverse order? | 40,069,551 | <p>You can use this to create the dataframe:</p>
<pre><code>xyz = pd.DataFrame({'release' : ['7 June 2013', '2012', '31 January 2013',
'February 2008', '17 June 2014', '2013']})
</code></pre>
<p>I am trying to split the data and save, them into 3 columns named "day, month and year", u... | 1 | 2016-10-16T11:05:54Z | 40,069,602 | <p>Try reversing the result. </p>
<pre><code>dataframe[['year','month','day']] = dataframe['release'].str.rsplit(expand=True).reverse()
</code></pre>
| 0 | 2016-10-16T11:11:26Z | [
"python",
"pandas"
] |
How to save split data in panda in reverse order? | 40,069,551 | <p>You can use this to create the dataframe:</p>
<pre><code>xyz = pd.DataFrame({'release' : ['7 June 2013', '2012', '31 January 2013',
'February 2008', '17 June 2014', '2013']})
</code></pre>
<p>I am trying to split the data and save, them into 3 columns named "day, month and year", u... | 1 | 2016-10-16T11:05:54Z | 40,069,615 | <p>You could </p>
<pre><code>In [17]: dataframe[['year', 'month', 'day']] = dataframe['release'].apply(
lambda x: pd.Series(x.split()[::-1]))
In [18]: dataframe
Out[18]:
release year month day
0 7 June 2013 2013 June 7
1 201... | 2 | 2016-10-16T11:13:41Z | [
"python",
"pandas"
] |
how can i fix AttributeError: 'dict_values' object has no attribute 'count'? | 40,069,585 | <p>here is my <a href="http://pastebin.com/tzPpqE97" rel="nofollow">code</a> and the text file is <a href="http://www.dropbox.com/s/2bklv7p4ylq8wur/web-graph.zip?dl=0http://" rel="nofollow">here</a></p>
<pre><code>import networkx as nx
import pylab as plt
webg = nx.read_edgelist('web-graph.txt',create_using=nx.DiGrap... | -1 | 2016-10-16T11:09:38Z | 40,069,610 | <p>The error is obvious <code>dict_values</code> object has no attribute <code>count</code>. If you want to count the number of unique values, the best way to go is using a <code>collections.Counter</code></p>
<pre><code>from collections import Counter
in_hist = Counter(in_degrees.values())
</code></pre>
| 0 | 2016-10-16T11:13:05Z | [
"python",
"python-3.x",
"networkx"
] |
how can i fix AttributeError: 'dict_values' object has no attribute 'count'? | 40,069,585 | <p>here is my <a href="http://pastebin.com/tzPpqE97" rel="nofollow">code</a> and the text file is <a href="http://www.dropbox.com/s/2bklv7p4ylq8wur/web-graph.zip?dl=0http://" rel="nofollow">here</a></p>
<pre><code>import networkx as nx
import pylab as plt
webg = nx.read_edgelist('web-graph.txt',create_using=nx.DiGrap... | -1 | 2016-10-16T11:09:38Z | 40,070,648 | <p>If you want to count dictionary values you can do it like this:</p>
<pre><code>len(list(dict.values()))
</code></pre>
<p>same method works for keys</p>
<pre><code>len(list(dict.keys()))
</code></pre>
<p>Also keep in mind if you want to get all keys or values in list just use <code>list(dict.values())</code></p>
| -1 | 2016-10-16T13:13:17Z | [
"python",
"python-3.x",
"networkx"
] |
Python Loop In HTML | 40,069,601 | <p>I have the following row within a table:</p>
<pre><code><TR>
<TD style="text-align:center;width:50px">{% for z in recentResultHistory %} {{ z.0 }} {% endfor %}</TD>
<TD style="text-align:center;width:100px"></TD>
<TD style="text-align:center;width:50px">V</TD>
... | 0 | 2016-10-16T11:11:25Z | 40,069,804 | <p>I should be using list(cursor) rather than cursor.fetchall(). Daniel and dkasak gave me the inspiration to look and I found the following which solved my issue:</p>
<p><a href="http://stackoverflow.com/questions/17861152/cursor-fetchall-vs-listcursor-in-python">cursor.fetchall() vs list(cursor) in Python</a></p>
| 0 | 2016-10-16T11:38:24Z | [
"python",
"html",
"for-loop"
] |
One Character "lag" in Python 3 Curses Program | 40,069,621 | <p>I'm attempting to create a roguelike using Python3 and curses. I've got everything displaying the way I want it to, but I've come across a strange bug in the code. There is a 1 key stroke delay in processing the commands. So, assuming traditional roguelike commands, pressing "k" should move you 1 square to the right... | -1 | 2016-10-16T11:14:22Z | 40,070,349 | <p>I found the problem and it wasn't in the code I posted. It was inside my render_all() function. I needed to add call to the window's refresh() function after making the changes I was making. I must say, I really don't like curses!</p>
| 0 | 2016-10-16T12:39:48Z | [
"python",
"python-3.x",
"curses"
] |
Matplotlib specific representation | 40,069,683 | <p>I am studying the influence of diverse factors on the distribution of bikes throughout a bike- sharing system called Velib in paris. I have 1222 bike stations with their occupation rate, their latitude and their longitude. I would like to make a map like this :
(<a href="http://images.google.fr/imgres?imgurl=http%3... | 0 | 2016-10-16T11:22:50Z | 40,070,057 | <p>It seems like you need:</p>
<pre><code>matplotlib.pyplot.contour(x, y, z)
matplotlib.pyplot.contourf(x, y, z)
</code></pre>
<p>with arguments x - latitude, y - longitude and z - occupation rate. </p>
| 0 | 2016-10-16T12:05:47Z | [
"python",
"matplotlib"
] |
âHelp me!, I would like to find split where the split sums are close to each other? | 40,069,689 | <p>I have a list is</p>
<blockquote>
<p>test = [10,20,30,40,50,60,70,80,90,100]</p>
</blockquote>
<p>âand I would like to find split where the split sums are close to each other by number of splits = 3 that âall possible combinations and select the split where the sum differences are smallest.</p>
<p>please ex... | -4 | 2016-10-16T11:23:27Z | 40,085,007 | <p>This first script uses a double <code>for</code> loop to split the input list into all possible triplets of lists. For each triplet it calculates the sum of each list in the triplet, then creates a sorted list named <code>diffs</code> of the absolute differences of those sums. It saves a tuple consisting of <code>di... | 0 | 2016-10-17T11:17:11Z | [
"python",
"python-2.7",
"python-3.x",
"recursion",
"split"
] |
Changing the value of groups with few members in a pandas data frame | 40,069,694 | <p>I have a data frame which represent different classes with their values. for example:</p>
<pre><code>df=pd.DataFrame(
{'label':['a','a','b','a','b','b','a','c','c','d','e','c'],
'date':[1,2,3,4,3,7,12,18,11,2,5,3],'value':np.random.randn(12)})
</code></pre>
<p>I want to choose the labels with values_counts less t... | 2 | 2016-10-16T11:23:47Z | 40,069,736 | <p>You can use groupby.transform to get the value counts aligned with the original index, then use it as a boolean index:</p>
<pre><code>df.loc[df.groupby('label')['label'].transform('count') <= threshold, 'label'] = 'zero'
df
Out:
date label value
0 1 a -0.587957
1 2 a 0.341551
2 ... | 2 | 2016-10-16T11:30:08Z | [
"python",
"pandas"
] |
Changing the value of groups with few members in a pandas data frame | 40,069,694 | <p>I have a data frame which represent different classes with their values. for example:</p>
<pre><code>df=pd.DataFrame(
{'label':['a','a','b','a','b','b','a','c','c','d','e','c'],
'date':[1,2,3,4,3,7,12,18,11,2,5,3],'value':np.random.randn(12)})
</code></pre>
<p>I want to choose the labels with values_counts less t... | 2 | 2016-10-16T11:23:47Z | 40,069,790 | <p>You could do</p>
<pre><code>In [59]: df.loc[df['label'].isin(value_count[value_count.values<=threshold].index),
'label'] = 'zero'
In [60]: df
Out[60]:
date label value
0 1 a -0.132887
1 2 a -1.306601
2 3 zero -1.431952
3 4 a 0.928743
4 3 zero 0.278955
5 7 ... | 1 | 2016-10-16T11:36:25Z | [
"python",
"pandas"
] |
Python selenium skips over necessary elements | 40,069,726 | <p>PLEASE DONT DOWNVOTE, THIS QUESTION IS DIFFERENT FROM PREVIOUS ONE, IM USING DIFFERENT LOGIC HERE</p>
<p>Im trying to iterate over all user reviews("partial_entry" class) from this page <a href="https://www.tripadvisor.com/Airline_Review-d8729164-Reviews-Cheap-Flights-or560-TAP-Portugal#REVIEWS" rel="nofollow">http... | 0 | 2016-10-16T11:29:00Z | 40,072,314 | <p>One tip for removing chromedriver path in every script.Put chromedriver.exe in C:\Python27\Scripts than you don't have to put the chromedriver path in every script than just use <code>driver = webdriver.Chrome()</code></p>
<p>I am running this code:</p>
<pre><code>from selenium import webdriver
from selenium.webdr... | 2 | 2016-10-16T16:02:53Z | [
"python",
"selenium",
"web-scraping"
] |
How do I check if a function is called in a function or not, in python? No mock or unittest. | 40,069,786 | <p>I just want to check whether a particular function is called by other function or not. If yes then I have to store it in a different category and the function that does not call a particular function will be stored in different category.
I have 3 .py files with classes and functions in them. I need to check each an... | 1 | 2016-10-16T11:35:40Z | 40,069,815 | <p>I have no idea what you are asking, but even if it is be <a href="http://stackoverflow.com/questions/2654113/python-how-to-get-the-callers-method-name-in-the-called-method">technically possible</a>, the one and only answer: don't do that.</p>
<p>If your design is as such that method A needs to know whether it was c... | 0 | 2016-10-16T11:39:41Z | [
"python"
] |
Can a class method change a variable in another class as an unforseen side effect? | 40,069,808 | <p>I'm having some problem with two classes. This is what I write in my main loop</p>
<pre><code>print(player1.getPosSize())
ball.setPos(windowWidth, [player1.getPosSize(), player2.getPosSize()],
[player1.getSpeed(), player2.getSpeed()])
print(player1.getPosSize())
</code></pre>
<p>Here are the method def... | 0 | 2016-10-16T11:38:43Z | 40,069,958 | <p>Any <code>mutable</code> object such as <code>list</code> can be changed by anything that has access to it. Ie. if your <code>getPosSize()</code> method is returning the<code>list</code> itself, you can make changes that will affect the same list.</p>
<pre><code>class One(object):
CLS_LST = [1, 2, 3]
def __... | 0 | 2016-10-16T11:55:52Z | [
"python",
"class",
"variables",
"methods"
] |
Can a class method change a variable in another class as an unforseen side effect? | 40,069,808 | <p>I'm having some problem with two classes. This is what I write in my main loop</p>
<pre><code>print(player1.getPosSize())
ball.setPos(windowWidth, [player1.getPosSize(), player2.getPosSize()],
[player1.getSpeed(), player2.getSpeed()])
print(player1.getPosSize())
</code></pre>
<p>Here are the method def... | 0 | 2016-10-16T11:38:43Z | 40,070,030 | <p>It looks like two variables in your code link to the same list, so changing one of them will change the other.</p>
<p>Didn't you do anything like <code>ball.posSize = player1.posSize</code>?</p>
<p>If yes, you created a second reference to the same list.</p>
<p>To fix this, change <code>ball.posSize = player1.pos... | 0 | 2016-10-16T12:03:04Z | [
"python",
"class",
"variables",
"methods"
] |
i got error 10061 in python | 40,069,822 | <p>im trying to send a message to myself in python but the client code gives me error 10061 the server works properly it worked just fine but than it suddenly started giving me the error. i tried changing the port but it still gives me the same error</p>
<p>the server </p>
<pre><code>from socket import *
from dateti... | -1 | 2016-10-16T11:40:12Z | 40,069,945 | <p>10061 error occurs when the target machine refuses a connection.
In your case the most likely reason is the "IP" in s.bind and s.connect try putting an actual IP or 127.0.0.1. It should work</p>
| 0 | 2016-10-16T11:54:32Z | [
"python",
"sockets",
"server"
] |
i got error 10061 in python | 40,069,822 | <p>im trying to send a message to myself in python but the client code gives me error 10061 the server works properly it worked just fine but than it suddenly started giving me the error. i tried changing the port but it still gives me the same error</p>
<p>the server </p>
<pre><code>from socket import *
from dateti... | -1 | 2016-10-16T11:40:12Z | 40,070,298 | <p>never mind i fixed it the problem was that the input was before the listen and it stalled the program thanks everyone </p>
| 0 | 2016-10-16T12:33:27Z | [
"python",
"sockets",
"server"
] |
Plot each unique element of a column in a dataframe with partially overlapping y-Values | 40,069,845 | <p>I hope I can explain this properly as I am new to pandas. I have the following dataframe in pandas.</p>
<pre><code>import numpy as np
plant1 = {'Date' : pd.date_range('1/1/2011', periods=10, freq='D'),
'Plant' : pd.Series(["Plant1"]*10),
'Output' : pd.Series(abs(np.random.randn(10)))}
plant2 = {'Date' : ... | 0 | 2016-10-16T11:42:44Z | 40,069,990 | <p>A user in the chat made me aware of the pivot-function.</p>
<pre><code>test = pd.pivot_table(sample, index='Date', columns='Plant', values='Output')
test = test.fillna(method='pad')
test = test.fillna(method='bfill')
plt.figure(); test.plot(kind='area')
</code></pre>
<p><a href... | 0 | 2016-10-16T11:59:20Z | [
"python",
"pandas"
] |
numba jit: 'DataFlowAnalysis' object has no attribute 'op_STORE_DEREF' | 40,069,898 | <p>I'm trying to run the following code with numba but get an error:</p>
<pre><code>from numba import jit
@jit(nopython=True)
def create_card_deck():
values = "23456789TJQKA"
suites = "CDHS"
Deck = []
[Deck.append(x + y) for x in values for y in suites]
return Deck
create_card_deck()
</code></pre... | 1 | 2016-10-16T11:49:34Z | 40,070,239 | <p>There are two problems here - the more fundamental one is that <code>numba</code> doesn't support strings in <code>nopython</code> mode</p>
<pre><code>@jit(nopython=True)
def create_card_deck():
values = "23456789TJQKA"
suites = "CDHS"
return values
In [4]: create_card_deck()
--------------------------... | 2 | 2016-10-16T12:26:49Z | [
"python",
"jit",
"numba"
] |
Python. Best way to match dictionary value if condition true | 40,069,960 | <p>I'm trying to build a parser now part of my code is looks like this:</p>
<pre><code> azeri_nums = {k:v for k,v in zip(range(1,10),("bir","iki","uc","dord","beÅ","altı","yeddi","sÉkkiz","doqquz"))}
russian_nums = {k:v for k,v in zip(range(1,10),("один","два","ÑÑи","ÑеÑÑÑе","пÑÑÑ","Ñ... | 0 | 2016-10-16T11:55:54Z | 40,070,043 | <p>Change your dict to be</p>
<pre><code>azeri_nums = {v.lower():k for k,v in zip(range(1,10),("bir","iki","uc","dord","beÅ","altı","yeddi","sÉkkiz","doqquz"))}
russian_nums = {v.lower():k for k,v in zip(range(1,10),("один","два","ÑÑи","ÑеÑÑÑе","пÑÑÑ","ÑеÑÑÑ","ÑемÑ","воÑемÑ","дÐ... | 1 | 2016-10-16T12:04:16Z | [
"python",
"dictionary"
] |
Url argument with Django | 40,070,006 | <p>I'm having some problem with my url in Django (1.9)</p>
<p>Tried many way to solve it, but still the same type of error</p>
<pre><code>Reverse for 'elus' with arguments '()' and keyword arguments '{u'council': u'CFVU'}' not found. 1 pattern(s) tried: ['elus/(?P<council>[A-B]+)$']
</code></pre>
<p>The actual... | 0 | 2016-10-16T12:00:32Z | 40,070,069 | <p>You have <code>[A-B]</code> will only match the letters A and B. </p>
<p>If you only want to match uppercase letters you could do:</p>
<pre><code>url(r'^elus/(?P<council>[A-Z]+)$
</code></pre>
<p>Or, a common approach is to use <code>[\w-]+</code>, which will match upper case A-Z, lowercase a-z, digits 0-9,... | 1 | 2016-10-16T12:07:01Z | [
"python",
"django",
"url"
] |
Add a legend (like a matplotlib legend) to an image | 40,070,037 | <p><strong>Problem : Add a legend (like a matplotlib legend) to an image</strong></p>
<p><strong>Description:</strong></p>
<p>I have an image as a numpy array uint8.
I want to add a legend to it, exactly as matplotlib does with its plots.</p>
<p>My image has , basically, this shape :</p>
<pre><code>output_image = n... | 2 | 2016-10-16T12:03:56Z | 40,070,971 | <p>Your question itself makes it clear that you know how to make an image in a numpy array. Now make your legend using the same techniques in a smaller numpy array.</p>
<p>Finally, use the facilities in numpy to replace part of the plot array with the legend array, as discussed in <a href="http://stackoverflow.com/que... | 1 | 2016-10-16T13:45:29Z | [
"python",
"numpy",
"matplotlib"
] |
Tensorflow Logistic Regression | 40,070,064 | <p>I am trying to implement: <a href="https://www.tensorflow.org/versions/r0.11/tutorials/wide/index.html" rel="nofollow">https://www.tensorflow.org/versions/r0.11/tutorials/wide/index.html</a>
on my dataset.</p>
<p>I am basically trying to do a binary classification (0 or 1) based on some continuous and categorical f... | 0 | 2016-10-16T12:06:48Z | 40,130,207 | <p>When you train the model you are passing it the list <code>FEATURE_COLUMNS</code> which I believe you have as a list of strings. When tensor flow loops over this list it is trying to access the key property on a string which fails. you probably want to pass it a list of your tensorflow variables i.e. define a new li... | 0 | 2016-10-19T11:29:51Z | [
"python",
"machine-learning",
"tensorflow",
"logistic-regression"
] |
GridSpec on Seaborn Subplots | 40,070,093 | <p>I currently have 2 subplots using seaborn:</p>
<pre><code>import matplotlib.pyplot as plt
import seaborn.apionly as sns
f, (ax1, ax2) = plt.subplots(2, sharex=True)
sns.distplot(df['Difference'].values, ax=ax1) #array, top subplot
sns.boxplot(df['Difference'].values, ax=ax2, width=.4) #bottom subplot
sns.strippl... | 0 | 2016-10-16T12:09:51Z | 40,074,723 | <p>As @dnalow mentioned, <code>seaborn</code> has no impact on <code>GridSpec</code>, as you pass a reference to the <code>Axes</code> object to the function. Like so:</p>
<pre><code>import matplotlib.pyplot as plt
import seaborn.apionly as sns
import matplotlib.gridspec as gridspec
tips = sns.load_dataset("tips")
g... | 0 | 2016-10-16T19:49:11Z | [
"python",
"matplotlib",
"seaborn",
"subplot"
] |
Separate sentences on each new line from paragraph using python | 40,070,194 | <p>I have paragraph as:</p>
<p><strong>INPUT :--</strong></p>
<p>"However, there is generally a lack of local, regional, and national land use and land cover data of sufficient reliability and temporal and geographic detail for providing accurate estimates of landscape change. The U.S. Geological Survey's EROS Data C... | -1 | 2016-10-16T12:21:54Z | 40,070,504 | <p>Using <code>nltk</code> is definately a good approach. The sentances could be enumerated as follows:</p>
<pre><code>import nltk
text = "However, there is generally a lack of local, regional, and national land use and land cover data of sufficient reliability and temporal and geographic detail for providing accurat... | 0 | 2016-10-16T12:58:24Z | [
"python",
"parsing"
] |
Serverless Framework v1.0.0 GA - Environment variables within Python Handlers | 40,070,216 | <p>What is the best practice in regards to env variable with serverless framework. </p>
<p>Ive heard some discussion on the python dotenv environment, but Im not too experience with python so looking for guidance on setting this up and using (an example would be good!)</p>
<p>For example, I want to have an environme... | 0 | 2016-10-16T12:24:04Z | 40,103,231 | <p>You can use the <a href="https://www.npmjs.com/package/serverless-plugin-write-env-vars" rel="nofollow">serverless-plugin-write-env-vars</a> plugin to define environment variables in <code>serverless.yml</code>, like this:</p>
<pre><code>service: my-service
custom:
writeEnvVars:
DB_ARN: "ec2-xx-xx-xx-xxx.... | 0 | 2016-10-18T08:27:57Z | [
"python",
"aws-lambda",
"serverless-framework"
] |
Data transfer between C++ and Python | 40,070,249 | <p>I would like to share memory between C++ and Python.</p>
<p>My problem:</p>
<ol>
<li>I am working with big data sets (up to 6 GB of RAM) in C++. All calculations are done in c++.</li>
<li>Then, I want to "paste" all my results to a Python program. But I can only write my data on disk, and then read that file from ... | 2 | 2016-10-16T12:27:32Z | 40,070,781 | <p><strong>First path</strong>: I think the more appropriate way for you to go is <a href="https://docs.python.org/3.4/library/ctypes.html" rel="nofollow">ctypes</a>. You can create a shared library, and then load the functions of the shared library in Python, and fill all the data containers you want in Python.</p>
<... | 2 | 2016-10-16T13:26:05Z | [
"python",
"c++",
"data-transfer"
] |
Python tornado gen.coroutine blocks request | 40,070,259 | <p>I am newbie on tornado and python. A couple days ago i started to write a non-blocking rest api, but i couldn't accomplish the mission yet. When i send two request to this endpoint "localhost:8080/async" at the same time, the second request takes response after 20 seconds! That explains i am doing something wrong.</... | 0 | 2016-10-16T12:28:21Z | 40,072,378 | <p>Never use <code>time.sleep</code> in Tornado code! Use IOLoop.add_timeout to schedule a callback later, or in a coroutine <code>yield gen.sleep(n)</code>.</p>
<p><a href="http://www.tornadoweb.org/en/latest/faq.html#why-isn-t-this-example-with-time-sleep-running-in-parallel" rel="nofollow">http://www.tornadoweb.org... | 0 | 2016-10-16T16:08:21Z | [
"python",
"tornado",
"python-3.5"
] |
Python tornado gen.coroutine blocks request | 40,070,259 | <p>I am newbie on tornado and python. A couple days ago i started to write a non-blocking rest api, but i couldn't accomplish the mission yet. When i send two request to this endpoint "localhost:8080/async" at the same time, the second request takes response after 20 seconds! That explains i am doing something wrong.</... | 0 | 2016-10-16T12:28:21Z | 40,079,713 | <p>That's strange that returning the <code>ThreadPoolExecutor</code> future, essentially blocks tornado's event loop. If anyone from the tornado team reads this and knows why that is, can they please give an explaination? I had planned to do some stuff with threads in tornado but after dealing with this question, I see... | 0 | 2016-10-17T06:22:53Z | [
"python",
"tornado",
"python-3.5"
] |
Python itertools.product freezes with higher numbers | 40,070,289 | <p>I have 6 variables with different ranges. I want to create possibilities pool with my code. In this example i gave 10 range for every variable but i have to give them about 200 range. But whenever i'm trying to exceed 20 range (for example 30 range) Python kills itself, and sometimes it freezes computer. Is there an... | 0 | 2016-10-16T12:32:25Z | 40,070,342 | <p>Use the cartesian_product function from <a href="http://stackoverflow.com/a/11146645/5714445">here</a>Â for an almost 60x speed up from <code>itertools.product()</code></p>
<pre><code>def cartesian_product2(arrays):
la = len(arrays)
arr = np.empty([len(a) for a in arrays] + [la])
for i, a in enumerate... | 0 | 2016-10-16T12:38:47Z | [
"python",
"python-3.x",
"itertools"
] |
Python itertools.product freezes with higher numbers | 40,070,289 | <p>I have 6 variables with different ranges. I want to create possibilities pool with my code. In this example i gave 10 range for every variable but i have to give them about 200 range. But whenever i'm trying to exceed 20 range (for example 30 range) Python kills itself, and sometimes it freezes computer. Is there an... | 0 | 2016-10-16T12:32:25Z | 40,070,432 | <p>There are 6 lists of 11 elements each: <code>[400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410]</code>.</p>
<p>A cartesian product of 6 such lists is a list of 11<sup>6</sup> tuples of 6 integers each (the first tuple is: <code>(400, 400, 400, 400, 400, 400)</code>).</p>
<p>The size of each tuple is 6*8 bytes... | 3 | 2016-10-16T12:49:33Z | [
"python",
"python-3.x",
"itertools"
] |
Python itertools.product freezes with higher numbers | 40,070,289 | <p>I have 6 variables with different ranges. I want to create possibilities pool with my code. In this example i gave 10 range for every variable but i have to give them about 200 range. But whenever i'm trying to exceed 20 range (for example 30 range) Python kills itself, and sometimes it freezes computer. Is there an... | 0 | 2016-10-16T12:32:25Z | 40,076,955 | <p>Maybe instead of doing all of it one-go, you can try doing the product in successive steps. For example,</p>
<pre><code>import itertools as itt
a = [1, 2, 3]
b = [4, 5, 6]
c = [7, 8, 9]
fl = lambda x: x
s1 = filter(fl, itt.product(a, b))
s2 = filter(fl, itt.product(s1, c))
print(list(s2))
</code></pre>
<p>But ... | 1 | 2016-10-17T00:26:07Z | [
"python",
"python-3.x",
"itertools"
] |
Python itertools.product freezes with higher numbers | 40,070,289 | <p>I have 6 variables with different ranges. I want to create possibilities pool with my code. In this example i gave 10 range for every variable but i have to give them about 200 range. But whenever i'm trying to exceed 20 range (for example 30 range) Python kills itself, and sometimes it freezes computer. Is there an... | 0 | 2016-10-16T12:32:25Z | 40,085,857 | <p>Thanks everyone for your answers. While searching for a better solution, i found an answer on Python documentation. There is an example on documentation for using itertools.product as generator instead of list. Yet, i still can't find any good idea to make it faster. This will help you too if your going to use produ... | 0 | 2016-10-17T12:01:03Z | [
"python",
"python-3.x",
"itertools"
] |
Searching Elements of a List | 40,070,357 | <p>I am trying to search a array of previous usernames used in a game, for the username currently used by the gamer (allowing all the previous game scores under the username to be displayed). This list has been imported from an external text file.</p>
<pre><code>for x in range(0, len(lis)):
if username == lis[x]:
... | 0 | 2016-10-16T12:41:36Z | 40,070,385 | <pre><code>if username in lis:
</code></pre>
<p>Should do the trick of searching through a list</p>
<p>If the code you have written is not working, check if the strings are formatted the same way</p>
<pre><code>if username.strip().lower() == lis[x].strip().lower():
</code></pre>
| 0 | 2016-10-16T12:45:16Z | [
"python",
"list"
] |
Searching Elements of a List | 40,070,357 | <p>I am trying to search a array of previous usernames used in a game, for the username currently used by the gamer (allowing all the previous game scores under the username to be displayed). This list has been imported from an external text file.</p>
<pre><code>for x in range(0, len(lis)):
if username == lis[x]:
... | 0 | 2016-10-16T12:41:36Z | 40,070,415 | <p>Try this:</p>
<pre><code>for usernameTest in lis:
if username == usernameTest.strip():
print "yes"
print lis[x]
</code></pre>
| 0 | 2016-10-16T12:47:41Z | [
"python",
"list"
] |
Searching Elements of a List | 40,070,357 | <p>I am trying to search a array of previous usernames used in a game, for the username currently used by the gamer (allowing all the previous game scores under the username to be displayed). This list has been imported from an external text file.</p>
<pre><code>for x in range(0, len(lis)):
if username == lis[x]:
... | 0 | 2016-10-16T12:41:36Z | 40,070,443 | <p>I'm not sure if it is what you meant but at least this prints yes:</p>
<pre><code>lis = ["Jack","Rose", "Joe", "Franz"]
username = "Joe"
for x in range(0, len(lis)):
if username == lis[x]:
print ("yes")
</code></pre>
| 0 | 2016-10-16T12:51:06Z | [
"python",
"list"
] |
Get distance to non-empty item in two-dimensional list column | 40,070,364 | <p>I am trying to make a game of scrabble. I have a board, defined below.</p>
<pre><code>self.board = [[" ", "A ", "B ", "C ", "D ", "E ", "F ", "G ", "H ", "I ", "J ", "K ", "L ", "M ", "N ", "O "],
['01', 'TWS', ' ', ' ', 'DLS', ' ', ' ', ' ', 'TWS', ' ', ' ', ' ', 'DLS', ' ', ' ', 'TWS'],
['02', ' ', 'DWS',... | 0 | 2016-10-16T12:42:55Z | 40,071,651 | <p>You could use <code>next</code>, and extract the column with <code>[row[col_num] for row in board]</code> like this:</p>
<pre><code>def distances(row_num, col_num):
letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
if not col_num.isdigit():
col_num = ord(col_num.upper()) - ord('A') + 1
col = [row[col_num] ... | 1 | 2016-10-16T14:52:49Z | [
"python",
"python-3.x",
"multidimensional-array",
"distance"
] |
Use parameterized query with mysql.connector in Python 2.7 | 40,070,368 | <p>Im using Python 2.7 with <a href="https://dev.mysql.com/doc/connector-python/en/connector-python-example-cursor-select.html" rel="nofollow"><code>mysql.connector</code></a> running in pyCharm</p>
<p>I need to use a parameterized query like shown <a href="https://dev.mysql.com/doc/connector-python/en/connector-pytho... | 0 | 2016-10-16T12:43:36Z | 40,070,500 | <p>The error you get is from mysql when it tries to execute the query. The query parameters passed to <code>cursor.execute()</code> need to be a tuple, you're passing a single value. To create a tuple with a single element you need to add a comma after the element:</p>
<pre><code>cursor.execute("SELECT * FROM automate... | 1 | 2016-10-16T12:57:55Z | [
"python",
"mysql",
"mysql-connector",
"mysql-connector-python"
] |
Building a function of a random variable dynamically in python | 40,070,390 | <p>I have some random variables using <code>scipy.stats</code> as follows:</p>
<pre><code>import scipy.stats as st
x1 = st.uniform()
x2 = st.uniform()
</code></pre>
<p>Now I would like make another random variable based on previous random variables and make some calculations like <code>var</code> for the new random v... | 1 | 2016-10-16T12:45:38Z | 40,074,929 | <p>Not directly, I think. However, this approach might be of use to you.</p>
<p>Assume to begin with that you know either the pdf or the cdf of the function of the random variables of interest. Then you can use rv_continuous in scipy.stats to calculate the variance and other moments of that function using the recipe o... | 0 | 2016-10-16T20:08:54Z | [
"python",
"random",
"scipy"
] |
cx_Freeze: no base named Console | 40,070,426 | <p>I am trying to compile a simple "Hello, world!" python script using cx_freeze (linux). I installed cx-freeze via the SourceForge tar file, because I had to apply <a href="https://bitbucket.org/anthony_tuininga/cx_freeze/issues/32/cant-compile-cx_freeze-in-ubuntu-1304" rel="nofollow">this</a> patch.</p>
<p>However, ... | 0 | 2016-10-16T12:48:49Z | 40,070,675 | <p>I just solved the problem by changing</p>
<pre><code>ext = ".exe" if sys.platform == "win32" else ""
</code></pre>
<p>to</p>
<pre><code>ext = ".exe" if sys.platform == "win32" else ".py"
</code></pre>
<p>in file freezer.py</p>
| 0 | 2016-10-16T13:16:33Z | [
"python",
"linux",
"build",
"cx-freeze"
] |
Algorithm for finding the possible palindromic strings in a list containing a list of possible subsequences | 40,070,474 | <p>I have "n" number of strings as input, which i separate into possible subsequences into a list like below</p>
<p>If the Input is : aa, b, aa</p>
<p>I create a list like the below(<strong>each list having the subsequences of the string</strong>):</p>
<pre><code>aList = [['a', 'a', 'aa'], ['b'], ['a', 'a', 'aa']]
<... | 1 | 2016-10-16T12:55:03Z | 40,071,717 | <h1>Second version</h1>
<p>This version uses a set called <code>seen</code>, to avoid testing combinations more than once.</p>
<p>Note that your function <code>isPalindrome()</code> can simplified to single expression, so I removed it and just did the test in-line to avoid the overhead of an unnecessary function call... | 0 | 2016-10-16T14:59:54Z | [
"python",
"algorithm"
] |
Algorithm for finding the possible palindromic strings in a list containing a list of possible subsequences | 40,070,474 | <p>I have "n" number of strings as input, which i separate into possible subsequences into a list like below</p>
<p>If the Input is : aa, b, aa</p>
<p>I create a list like the below(<strong>each list having the subsequences of the string</strong>):</p>
<pre><code>aList = [['a', 'a', 'aa'], ['b'], ['a', 'a', 'aa']]
<... | 1 | 2016-10-16T12:55:03Z | 40,071,991 | <p>Current approach has disadvantage and that most of generated solutions are finally thrown away when checked that solution is/isn't palindrome.</p>
<p>One Idea is that once you pick solution from one side, you can immediate check if there is corresponding solution in last group.</p>
<p>For example lets say that you... | 0 | 2016-10-16T15:28:14Z | [
"python",
"algorithm"
] |
Algorithm for finding the possible palindromic strings in a list containing a list of possible subsequences | 40,070,474 | <p>I have "n" number of strings as input, which i separate into possible subsequences into a list like below</p>
<p>If the Input is : aa, b, aa</p>
<p>I create a list like the below(<strong>each list having the subsequences of the string</strong>):</p>
<pre><code>aList = [['a', 'a', 'aa'], ['b'], ['a', 'a', 'aa']]
<... | 1 | 2016-10-16T12:55:03Z | 40,074,371 | <p>For larger input you could probably get some time gain by grabbing words from the first array, and compare them with the words of the last array to check that these pairs still allow for a palindrome to be formed, or that such a combination can never lead to one by inserting arrays from the remaining words in betwee... | 0 | 2016-10-16T19:13:08Z | [
"python",
"algorithm"
] |
Can't change tkinter label text constantly in loop | 40,070,475 | <p>I'm trying to make simple Quiz program. I want labels to change their text for every question in range of 10 questions. So, when you are on 1st question, one label should show 'Question 1'. But it immediately shows 'Question 10', and I'm unable to play quiz.</p>
<p>In dictionary, there's only one question, but it s... | 1 | 2016-10-16T12:55:10Z | 40,071,202 | <p>You need to wait for the user to enter their answer into the Entry widget. The code you posted doesn't do that. You have to organize your logic a little differently in GUI programss compared to command-line programs because you need to wait for events generated by user actions and then respond to them.</p>
<p>The ... | 1 | 2016-10-16T14:07:18Z | [
"python",
"loops",
"for-loop",
"tkinter",
"range"
] |
Python using while loop with a list name | 40,070,584 | <p>I am a beginner to python so this might be easy but I am not sure of what the following code means.</p>
<pre><code>q=[start]
while q:
</code></pre>
<p>Does this mean when there is at least one element in the list q execute it and q becomes false when it is empty?
Edit:I cannot execute it at the moment and I ne... | 1 | 2016-10-16T13:07:19Z | 40,070,694 | <p>The line <code>q = [start]</code> means <em>create a variable called <code>q</code>, and assign the value <code>[start]</code> to it</em>. In this case, it will create a list with one element: the value of the variable <code>start</code>. It's the exact same syntax as <code>q = [1, 2]</code>, but it uses a variable ... | 2 | 2016-10-16T13:18:20Z | [
"python",
"list",
"while-loop"
] |
How to unpack a tuple for looping without being dimension specific | 40,070,615 | <p>I'd like to do something like this:</p>
<pre><code> if dim==2:
a,b=grid_shape
for i in range(a):
for j in range(b):
A[i,j] = ...things...
</code></pre>
<p>where <code>dim</code> is simply the number of elements in my tuple <code>grid_shape</code>. <code>A</code> is a ... | 0 | 2016-10-16T13:11:17Z | 40,070,778 | <p>Using itertools, you can do it like this:</p>
<pre><code>for index in itertools.product(*(range(x) for x in grid_shape)):
A[index] = ...things...
</code></pre>
<p>This relies on a couple of tricks. First, <code>itertools.product()</code> is a function which generates tuples from iterables.</p>
<pre><code>for... | 0 | 2016-10-16T13:25:53Z | [
"python",
"loops",
"numpy",
"multidimensional-array",
"tuples"
] |
How to unpack a tuple for looping without being dimension specific | 40,070,615 | <p>I'd like to do something like this:</p>
<pre><code> if dim==2:
a,b=grid_shape
for i in range(a):
for j in range(b):
A[i,j] = ...things...
</code></pre>
<p>where <code>dim</code> is simply the number of elements in my tuple <code>grid_shape</code>. <code>A</code> is a ... | 0 | 2016-10-16T13:11:17Z | 40,070,813 | <p>You can catch the rest of the tuple by putting a star in front of the last variable and make a an array by putting parentheses around it.</p>
<pre><code>>>> tupl = ((1, 2), 3, 4, 5, 6)
>>> a, *b = tupl
>>> a
(1, 2)
>>> b
[3, 4, 5, 6]
>>>
</code></pre>
<p>And then you c... | 0 | 2016-10-16T13:29:17Z | [
"python",
"loops",
"numpy",
"multidimensional-array",
"tuples"
] |
Iterative RFE scores sklearn | 40,070,681 | <p>I'm using RFE with ExtraTreeRegressor as estimator in order to make SupervisedFeatureSelection in a regression problem. </p>
<p>I get the ranking and the support from the model with the common code below:</p>
<pre><code>rfe_vola = RFE(estimator=ExtraTreesRegressor(), n_features_to_select=1, step=1)
rfe_vola.fit(X_... | 0 | 2016-10-16T13:16:54Z | 40,093,005 | <p>That is was I was looking for:</p>
<pre><code>from sklearn.metrics import r2_score
rfe_vola = RFE(estimator=ExtraTreesRegressor(),n_features_to_select=None, step=1, verbose=2)
r2_scorer = lambda est, features: r2_score(y_true=y_vol,y_pred=est.predict(X_allfeatures[:, features]))
rfe_vola._fit(X_allfeatures, y_... | 0 | 2016-10-17T18:12:10Z | [
"python",
"scikit-learn",
"iteration",
"rfe"
] |
BeautifulSoup html table scrape - will only return last row | 40,070,746 | <p>I am attempting a simple scrape of an HTML table using BeautifulSoup with the following:</p>
<pre><code>import urllib
import urllib.request
from bs4 import BeautifulSoup
def make_soup(url):
page = urllib.request.urlopen(url)
sdata = BeautifulSoup(page, 'html.parser')
return sdata
url = 'http://www.sat... | 0 | 2016-10-16T13:23:19Z | 40,070,982 | <p>Your problem is here:</p>
<pre><code>bbdata = [ele.text.strip() for ele in bbdata_]
</code></pre>
<p>You want to append to the list or extend it:</p>
<pre><code>bbdata.append([ele.text.strip() for ele in bbdata_])
</code></pre>
<p>You are overwriting bbdata each time through the loop which is why it ends up only... | 2 | 2016-10-16T13:46:28Z | [
"python",
"beautifulsoup",
"html-table"
] |
Why is this code dependant on my local machine timezone? | 40,070,757 | <p>Why does this code:</p>
<pre><code>def parse_date(datetime_string, tz_code):
tz = timezone(tz_code)
datetime_obj = parser.parse(datetime_string)
datetime_obj_localized = datetime_obj.replace(tzinfo=tz)
return time.mktime(datetime_obj_localized.timetuple())
def test_parse_date(self):
self.assert... | 1 | 2016-10-16T13:24:15Z | 40,071,275 | <p><code>dateutil.parser</code> will attach a time zone if and only if it finds one, which <em>could</em> depend on your local machine time zone settings, because if it detects an abbreviated time zone like "EST" that is in the list of abbreviations for your local time zone, it will assume that that's the one you mean.... | 2 | 2016-10-16T14:13:33Z | [
"python",
"timezone",
"python-dateutil"
] |
Best Way to launch an asynchronous function in django? | 40,070,758 | <p>I am using <code>tweepy</code> library to collect tweets from <code>twitter streaming API</code> and store them in an <code>Elasticsearch</code> server. Overall I am writing a simple <code>Django application</code> to display the tweets in real time, over a map. However for that I need the ElasticSearch database to ... | -1 | 2016-10-16T13:24:24Z | 40,070,897 | <p>Use <a href="http://www.celeryproject.org/" rel="nofollow">celery</a> along with <a href="https://pypi.python.org/pypi/celery-haystack" rel="nofollow">celery-haystack</a> (hopefully you are already using <a href="http://haystacksearch.org/" rel="nofollow">django-haystack</a> to interact with Elasticsearch). Its not ... | 0 | 2016-10-16T13:37:13Z | [
"python",
"django",
"twitter",
"django-views",
"tweepy"
] |
Best Way to launch an asynchronous function in django? | 40,070,758 | <p>I am using <code>tweepy</code> library to collect tweets from <code>twitter streaming API</code> and store them in an <code>Elasticsearch</code> server. Overall I am writing a simple <code>Django application</code> to display the tweets in real time, over a map. However for that I need the ElasticSearch database to ... | -1 | 2016-10-16T13:24:24Z | 40,084,068 | <p>I use supervisor + <a href="https://docs.djangoproject.com/es/1.10/howto/custom-management-commands/" rel="nofollow">custom django command</a>. Inside the command you decide when to run that asynchronous function.</p>
| 0 | 2016-10-17T10:31:59Z | [
"python",
"django",
"twitter",
"django-views",
"tweepy"
] |
How to round to the nearest lower float in Python? | 40,070,868 | <p>I have a list of floats which I want to round up to 2 numbers; I used below line for this purpose:</p>
<pre><code>item = ['41618.45110', '1.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '41619.001202', '3468.678822']
print ["{0:.2f}".format(round(float(x), 2)) if re.match("^\d... | 1 | 2016-10-16T13:34:52Z | 40,070,934 | <p>You can use a cast to do that :</p>
<pre><code>a = '3468.678822'
def round_2(n):
return ((int)(n*100)/100)
print(round_2(float(a)))
>>> 3468.67
</code></pre>
| 1 | 2016-10-16T13:41:53Z | [
"python",
"formatting",
"precision"
] |
How to round to the nearest lower float in Python? | 40,070,868 | <p>I have a list of floats which I want to round up to 2 numbers; I used below line for this purpose:</p>
<pre><code>item = ['41618.45110', '1.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '41619.001202', '3468.678822']
print ["{0:.2f}".format(round(float(x), 2)) if re.match("^\d... | 1 | 2016-10-16T13:34:52Z | 40,071,509 | <p>I just made a couple functions for this kind of precision rounding. Added some documentation for how it works, in case you'd be curious as to how they work.</p>
<pre><code>import math
def precCeil(num, place = 0):
"""
Rounds a number up to a given place.
num - number to round up
place - place to r... | 0 | 2016-10-16T14:39:03Z | [
"python",
"formatting",
"precision"
] |
Python pandas group by two columns | 40,070,909 | <p>I have a pandas dataframe:</p>
<pre><code> code type
index
312 11 21
312 11 41
312 11 21
313 23 22
313 11 21
... ...
</code></pre>
<p>So I need to group it by count of pairs 'code' and 'type' columns for each index item:</p>
<pre><code> 11_21 11_... | 0 | 2016-10-16T13:38:16Z | 40,071,119 | <p>Here's one way using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.crosstab.html" rel="nofollow"><code>pd.crosstab</code></a> and then rename column names, using levels information.</p>
<pre><code>In [136]: dff = pd.crosstab(df['index'], [df['code'], df['type']])
In [137]: dff
Out[137]:
cod... | 1 | 2016-10-16T13:58:07Z | [
"python",
"pandas",
"dataframe",
"group-by"
] |
I need to find The smallest positive factor (apart from 1) of the integer ânâ, where n ⥠2 | 40,070,961 | <p>i can only use for loops and range.. no while loop.</p>
<pre><code>def SmalletFactor(n):
# find the smallest positive factor (apart from 1) of the
# integer ânâ, where n ⥠2
result = 0
m = n
for i in range(2, n -1):
if n >=2 and (n % i == 0):
result = n // i
... | -2 | 2016-10-16T13:44:32Z | 40,071,038 | <p>Your code is more complicated than it needs to be. Consider the following:</p>
<pre><code>def SmallestFactor(n):
for i in range(2, n + 1): # n + 1 ensures that n itself
# is returned if n is prime
if n % i == 0:
return i
return None # this should never happ... | 1 | 2016-10-16T13:52:38Z | [
"python",
"factors"
] |
Python 2.7: Print a dictionary without brackets and quotation marks | 40,071,006 | <pre><code>myDict = {"Harambe" : "Gorilla", "Restaurant" : "Place", "Codeacademy" : "Place to learn"}
</code></pre>
<p>So, I want to print out a dictionary. But I want to do it like it looks like an actual list of things. I can't just do <code>print myDict</code>, as it will leave all the ugly stuff in. I want the out... | 1 | 2016-10-16T13:49:44Z | 40,071,052 | <p>You could try something like this.</p>
<pre><code>for (i, j) in myDict.items():
print "{0} : {1}".format(i, j), end = " "
</code></pre>
<p>Note that since dictionaries don't care about order, the output will most likely be more like <code>Restaurant : Place Harambe : Gorilla Codeacademy : Place to learn</code... | 0 | 2016-10-16T13:53:30Z | [
"python",
"python-2.7",
"dictionary",
"printing"
] |
Python 2.7: Print a dictionary without brackets and quotation marks | 40,071,006 | <pre><code>myDict = {"Harambe" : "Gorilla", "Restaurant" : "Place", "Codeacademy" : "Place to learn"}
</code></pre>
<p>So, I want to print out a dictionary. But I want to do it like it looks like an actual list of things. I can't just do <code>print myDict</code>, as it will leave all the ugly stuff in. I want the out... | 1 | 2016-10-16T13:49:44Z | 40,071,073 | <p>My solution:</p>
<pre><code>print ', '.join('%s : %s' % (k,myDict[k]) for k in myDict.keys())
</code></pre>
| 1 | 2016-10-16T13:54:48Z | [
"python",
"python-2.7",
"dictionary",
"printing"
] |
Python 2.7: Print a dictionary without brackets and quotation marks | 40,071,006 | <pre><code>myDict = {"Harambe" : "Gorilla", "Restaurant" : "Place", "Codeacademy" : "Place to learn"}
</code></pre>
<p>So, I want to print out a dictionary. But I want to do it like it looks like an actual list of things. I can't just do <code>print myDict</code>, as it will leave all the ugly stuff in. I want the out... | 1 | 2016-10-16T13:49:44Z | 40,071,100 | <p>Using the <code>items</code> dictionary method:</p>
<pre><code>print('\n'.join("{}: {}".format(k, v) for k, v in myDict.items()))
</code></pre>
<p>Output: </p>
<pre><code>Restaurant: Place
Codeacademy: Place to learn
Harambe: Gorilla
</code></pre>
<p>Expanded: </p>
<pre><code>for key, value in myDict.items():
... | 1 | 2016-10-16T13:56:42Z | [
"python",
"python-2.7",
"dictionary",
"printing"
] |
how to split a string with whitespace but ignore specific whitespace (that includes comma) in python | 40,071,026 | <p>I want split a string with whitespace but ignore specific whitespace (that includes comma).</p>
<p>Example: </p>
<pre><code>str = "abc de45+ Pas hfa, underak (333)"
</code></pre>
<p><strong>Required split</strong>:</p>
<pre><code>Item 1: abc
Item 2: de45+
Item 3: Pas hfa, underak
Item 4: (333)
</code></pre>
| -2 | 2016-10-16T13:51:33Z | 40,071,048 | <p>If you want to split only at a space, then simply use <code>split()</code></p>
<pre><code>a = "abc de45+ Pas hfa, underak (333)"
split_str = a.split(' ') #Splits only at space
</code></pre>
<p>If you want to split at spaces but not period, as suggested by @Beloo, use regex</p>
<pre><code>import re
a = "abc de... | 0 | 2016-10-16T13:53:16Z | [
"python",
"regex"
] |
how to split a string with whitespace but ignore specific whitespace (that includes comma) in python | 40,071,026 | <p>I want split a string with whitespace but ignore specific whitespace (that includes comma).</p>
<p>Example: </p>
<pre><code>str = "abc de45+ Pas hfa, underak (333)"
</code></pre>
<p><strong>Required split</strong>:</p>
<pre><code>Item 1: abc
Item 2: de45+
Item 3: Pas hfa, underak
Item 4: (333)
</code></pre>
| -2 | 2016-10-16T13:51:33Z | 40,071,265 | <p>You should split by <code>(?<!,)\s</code>
Check here : <a href="https://regex101.com/r/9VXO49/1" rel="nofollow">https://regex101.com/r/9VXO49/1</a></p>
| 1 | 2016-10-16T14:12:49Z | [
"python",
"regex"
] |
how to send html object from python to web page Tornado | 40,071,071 | <p>Inside my python code I have a html code for table </p>
<pre><code>import os.path
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
from tornado.options import define, options
define("port", default=8000, help="run on the given port", type=int)
class IndexHandler(tornado.web.... | 0 | 2016-10-16T13:54:32Z | 40,071,612 | <p>Tornado template output is escaped by default. To include raw html, use the <code>raw</code> template directive (and be careful of XSS!): <code>{% raw tableinfo %}</code></p>
| 0 | 2016-10-16T14:49:13Z | [
"python",
"html",
"tornado"
] |
How to split a column data into other columns which is stored in a dataframe? | 40,071,074 | <p>The df is the dataframe which contain the following information.</p>
<pre><code> In [61]: df.head()
Out[61]:
id movie_id info
0 1 1 Italy:1 January 1994
1 2 2 USA:22 January 2006
2 3 3 USA:12 February 2006
3 4 4 USA:Februa... | 0 | 2016-10-16T13:54:50Z | 40,071,213 | <p>You can use regex <code>:|\s+</code> to split the column on either semicolon or white spaces and specify the <code>expand</code> parameter to be true so that the result will expand to columns:</p>
<pre><code>df[["country","Date","Month","Year"]] = df['info'].str.split(':|\s+', expand = True)
</code></pre>
<p><a hr... | 0 | 2016-10-16T14:08:03Z | [
"python",
"pandas"
] |
How to split a column data into other columns which is stored in a dataframe? | 40,071,074 | <p>The df is the dataframe which contain the following information.</p>
<pre><code> In [61]: df.head()
Out[61]:
id movie_id info
0 1 1 Italy:1 January 1994
1 2 2 USA:22 January 2006
2 3 3 USA:12 February 2006
3 4 4 USA:Februa... | 0 | 2016-10-16T13:54:50Z | 40,071,226 | <p>Using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.split.html" rel="nofollow"><code>split</code></a> string method.</p>
<pre><code>In [163]: df[['country', 'date', 'month', 'year']] = df['info'].str.split('\W+', expand=True)
In [164]: df
Out[164]:
id movie_id ... | 0 | 2016-10-16T14:09:22Z | [
"python",
"pandas"
] |
Filter a large number of IDs from a dataframe Spark | 40,071,095 | <p>I have a large dataframe with a format similar to</p>
<pre><code>+-----+------+------+
|ID |Cat |date |
+-----+------+------+
|12 | A |201602|
|14 | B |201601|
|19 | A |201608|
|12 | F |201605|
|11 | G |201603|
+-----+------+------+
</code></pre>
<p>and I need to filter rows based on ... | 1 | 2016-10-16T13:56:35Z | 40,071,408 | <p>If you're committed to using Spark SQL and <code>isin</code> doesn't scale anymore then inner equi-join should be a decent fit. </p>
<p>First convert id list to as single column <code>DataFrame</code>. If this is a local collection</p>
<pre><code>ids_df = sc.parallelize(id_list).map(lambda x: (x, )).toDF(["id"])
<... | 3 | 2016-10-16T14:28:19Z | [
"python",
"apache-spark",
"pyspark"
] |
How to plot multiple lines in one figure in Pandas Python based on data from multiple columns? | 40,071,096 | <p>I have a dataframe with 3 columns, like this:</p>
<pre><code>df['year'] = ['2005, 2005, 2005, 2015, 2015, 2015, 2030, 2030, 2030']
df['name'] = ['A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'C']
df['weight'] = [80, 65, 88, 65, 60, 70, 60, 55, 65]
</code></pre>
<p>how can I plot a line for A, B and C, where it shows ho... | 2 | 2016-10-16T13:56:36Z | 40,071,258 | <p>Does this produce what you're looking for?</p>
<pre><code>import matplotlib.pyplot as plt
fig,ax = plt.subplots()
for name in ['A','B','C']:
ax.plot(df[df.name==name].year,df[df.name==name].weight,label=name)
ax.set_xlabel("year")
ax.set_ylabel("weight")
ax.legend(loc='best')
</code></pre>
<p><a href="https:... | 0 | 2016-10-16T14:12:16Z | [
"python",
"pandas",
"matplotlib",
"plot"
] |
How to call a variable inside main function from another program in python? | 40,071,150 | <p>I have two python files first.py and second.py</p>
<p>first.py looks like</p>
<pre><code>def main():
#some computation
first_variable=computation_result
</code></pre>
<p>second.py looks like</p>
<pre><code>import first
def main():
b=getattr(first, first_variable)
#computation
</code></pre>
<p>but I am g... | 0 | 2016-10-16T14:01:08Z | 40,071,244 | <p>You should use function calls and return values instead of this. </p>
<p>Return the computation_result from the function in the first file, and then store the result in the b variable in the second file.</p>
<p>first.py</p>
<pre><code>def main():
# computation
return computation_result
</code></pre>
<p>s... | 3 | 2016-10-16T14:11:16Z | [
"python"
] |
How to call a variable inside main function from another program in python? | 40,071,150 | <p>I have two python files first.py and second.py</p>
<p>first.py looks like</p>
<pre><code>def main():
#some computation
first_variable=computation_result
</code></pre>
<p>second.py looks like</p>
<pre><code>import first
def main():
b=getattr(first, first_variable)
#computation
</code></pre>
<p>but I am g... | 0 | 2016-10-16T14:01:08Z | 40,071,316 | <p>You will want to read <a href="https://docs.python.org/3/tutorial/classes.html#a-word-about-names-and-objects" rel="nofollow">9.1 and 9.2</a> in the Tutorial and <a href="https://docs.python.org/3/reference/executionmodel.html#naming-and-binding" rel="nofollow">Naming and Binding</a> in the Language Reference.</p>
... | 1 | 2016-10-16T14:18:23Z | [
"python"
] |
Django - trouble with separating objects by user and date | 40,071,153 | <p>So I have these models: </p>
<pre><code>excercises_choices = (('Bench Press', 'Bench press'),('Overhead Press', 'Overhead Press'), ('Squat', 'Squat'),
('Deadlift', 'Deadlift'))
unit_choices = (('kg','kg'), ('lbs', 'lbs'))
class Lifts(models.Model):
user = models.ForeignKey('auth.User', null=Tru... | 1 | 2016-10-16T14:01:26Z | 40,073,718 | <p>Have a look at the <a href="https://docs.djangoproject.com/en/dev/ref/templates/builtins/#regroup" rel="nofollow">regroup</a> template tag, it does exactly what you need.</p>
<p>You can do something like this in your view:</p>
<pre><code>@login_required
def entries(request):
lifts_by_user = (Lifts.objects.filt... | 0 | 2016-10-16T18:14:58Z | [
"python",
"django",
"web-applications",
"django-models",
"django-templates"
] |
Self Restarting a Python Script | 40,071,165 | <p>I have created a watchdog timer for my script (Python 3), which allows me to halt execution if anything goes wrong (not shown in code below). However, I would like to have the ability to restart the script automatically using only Python (no external scripts). The code needs to be cross platform compatible.</p>
<p>... | 0 | 2016-10-16T14:03:09Z | 40,072,303 | <p>Sounds like you are using threading in your original script, which explains why your can't break your original script when simply pressing <kbd>Ctrl</kbd>+<kbd>C</kbd>. In that case, you might want to add a KeyboardInterrupt exception to your script, like this:</p>
<pre><code>from time import sleep
def interrupt_th... | 0 | 2016-10-16T16:02:05Z | [
"python",
"restart",
"unattended-processing"
] |
Python Sockets SSL: certificate verify failed | 40,071,168 | <p>I am attempting to use python sockets to make an Extensible Provisioning Protocol (EPP) request to a domain registrar, which only accepts requests over ssl.</p>
<p>Certificate file: www.myDomain.se.crt
Key File: mydomain.pem</p>
<pre><code>openssl s_client -connect epptestv3.iis.se:700 -cert www.myDomain.se.crt -k... | 0 | 2016-10-16T14:03:25Z | 40,071,235 | <p>From your code:</p>
<pre><code> cert_reqs=ssl.CERT_REQUIRED,
ca_certs=None
</code></pre>
<p>From the <a href="https://docs.python.org/2/library/ssl.html#ssl.wrap_socket" rel="nofollow">documentation of wrap_socket</a>:</p>
<blockquote>
<p>If the value of this parameter is ... | 2 | 2016-10-16T14:10:23Z | [
"python",
"sockets",
"ssl",
"registrar",
"epp"
] |
Making continuous clicks on a pagination 'view-more' button in selenium (python) to load JS populated data | 40,071,189 | <p>I am trying to crawl the contents of a website by dynamically clicking a 'load-more' button. I saw some other <a href="http://stackoverflow.com/questions/30490549/how-to-click-on-load-button-dynamically-using-selenium-python/40071131#40071131">similar questions</a> but they seem to be getting other types of errors o... | 0 | 2016-10-16T14:06:13Z | 40,074,236 | <p>When websites like that dynamically load in content that way, it tends to wreak havoc on the page DOM, constantly invalidating element as new ones are being loaded in. I have found the best approach is to organize your code in way that puts the selenium calls into their own functions, which you then decorate with a ... | 1 | 2016-10-16T18:59:25Z | [
"python",
"selenium",
"pagination",
"web-crawler",
"selenium-chromedriver"
] |
What are routine and subroutine in program? | 40,071,214 | <p>I am learning stack and hearing this word called "Subroutine" too much. I am confused: what are exactly "routine" and "subroutine" ? </p>
<p>Let's suppose I have a program :</p>
<pre><code>def tav(x):
if x==0:
return 19
else:
u=1
tav(x-1)
u+=1
tav(4)
</code></pre>
<p>So what ar... | 2 | 2016-10-16T14:08:16Z | 40,071,241 | <p>Routines and subroutines are the same.
In older languages such as Fortran you had to differenciate between subroutines and functions. The latter returned something the former changed some state.</p>
| 3 | 2016-10-16T14:10:47Z | [
"python",
"stack",
"subroutine",
"routines"
] |
python: dictionaries overwriting when using pythonic way | 40,071,262 | <p>If I create a dictionary in a pythonic way, it gets overwritten</p>
<pre><code>ans = ['car','bus']
exp = ['a','b']
for ex in exp:
b ={x: {ex: {'1:N': [],'2:N': []}} for x in ans}
</code></pre>
<p>How do I avoid overwriting of an 'a' key?</p>
| -3 | 2016-10-16T14:12:33Z | 40,071,769 | <p>It looks like you are beginner in Python so I would suggest break your program into smaller pieces to debug it.
In your case dictionaries is getting overwritten because <code>=</code> operator always do reassignment that is create new copy and does not modify the existing variable even for mutable data types</p>
<... | 1 | 2016-10-16T15:05:21Z | [
"python"
] |
Filtering a column in a Spark Dataframe to find percentage of each element | 40,071,263 | <p>I am trying to filter a column in a Spark Dataframe with pyspark, I want to know which records represents 10% or less than the total column, </p>
<p>For example I have the following column entitled "Animal" in my DataFrame :</p>
<p><strong>Animal</strong></p>
<ul>
<li>Cat</li>
<li>Cat</li>
<li>Dog</li>
<li>Dog</l... | 0 | 2016-10-16T14:12:39Z | 40,075,506 | <p>You first have to count the total and in a second step use it to filter.</p>
<p>In condensed code (pyspark, spark 2.0):</p>
<pre><code>import pyspark.sql.functions as F
df=sqlContext.createDataFrame([['Cat'],['Cat'],['Dog'],['Dog'],
['Cat'],['Cat'],['Dog'],['Dog'],['Cat'],['Rat']],['Animal'])
total=df.count()
... | 0 | 2016-10-16T21:08:33Z | [
"python",
"filtering",
"pyspark",
"spark-dataframe",
"pyspark-sql"
] |
Adding a new Unique Field in an existing database table with existing values- Django1.7/MySql | 40,071,295 | <p>I have an existing database table.
I want to add a new (Char)field to it. This field will have unique values.</p>
<p>When I try to do so:</p>
<pre><code>id = models.CharField(max_length=100, Unique=True)
</code></pre>
<p>I get integrity error.</p>
<p>Some of the other things I have tried :</p>
<pre><code>id = m... | 1 | 2016-10-16T14:16:09Z | 40,071,496 | <p>I will show the following with the new column being an INT not a CHAR. Same difference. </p>
<pre><code>create table t1
( id int auto_increment primary key,
col1 varchar(100) not null
);
insert t1(col1) values ('fish'),('apple'),('frog');
alter table t1 add column col2 int; -- OK (all of col2 is now NULL)
AL... | 1 | 2016-10-16T14:38:01Z | [
"python",
"mysql",
"django"
] |
How to change 1 bit from a string python? | 40,071,311 | <p>I generate a 64 bits random string using <code>os.urandom(8)</code>. Next, I want to randomly change the value of one bit of the string getting the bit to change first <code>x = random.getrandbits(6)</code> and doing the XOR operation for that bit like this <code>rand_string ^= 1 << x</code> but this last oper... | 1 | 2016-10-16T14:18:18Z | 40,071,356 | <p>I do not see the point in getting random bits and than lshifting. A randInt should do just right. Also if you want to change a single bit, try to xor a character instead of the string. If that does not work <code>...=chr(ord(char)^x)</code></p>
| 0 | 2016-10-16T14:22:38Z | [
"python",
"python-2.7",
"random",
"bit-manipulation"
] |
How to change 1 bit from a string python? | 40,071,311 | <p>I generate a 64 bits random string using <code>os.urandom(8)</code>. Next, I want to randomly change the value of one bit of the string getting the bit to change first <code>x = random.getrandbits(6)</code> and doing the XOR operation for that bit like this <code>rand_string ^= 1 << x</code> but this last oper... | 1 | 2016-10-16T14:18:18Z | 40,071,709 | <p>I assume there's a typo in your question. As Jonas Wielicki says, <code>os.random</code> doesn't exist; presumably you meant <code>os.urandom</code>. Yes, it's a Good Idea to use the system's random source for crypto work, but using <code>os.urandom</code> directly isn't so convenient. Fortunately, the <code>random<... | 3 | 2016-10-16T14:59:04Z | [
"python",
"python-2.7",
"random",
"bit-manipulation"
] |
how to use linecache.clearcache to clear the cache of a certain file? | 40,071,332 | <p>If I use linecache to read several files, and now the memory is to busy such that I want to clear a certain file cache rather than use 'linecache.clearcache()' to clear all the cache, what should I do?</p>
| 0 | 2016-10-16T14:20:19Z | 40,100,422 | <p>I had the same consideration as you.</p>
<p>So I wrote the test codes by myself. You can check it out.</p>
<p><a href="https://ideone.com/xHxTEl" rel="nofollow">https://ideone.com/xHxTEl</a></p>
<p>Basically using <code>linecache.clearcache()</code> which is out of for-loop could be much faster but it would consu... | 0 | 2016-10-18T05:45:01Z | [
"python",
"caching"
] |
scatter plot and line in python | 40,071,398 | <p>I have a question about how to place scatter plot and line into one graph correctly.</p>
<p>Here is the code:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
t= np.linspace(60, 180,100)
ax= plt.subplot()
ax.plot(data.Weight, data.Height , color = 'red')
ax.plot(t, 60+ 0.05*t, label=r"$Height = 6... | 0 | 2016-10-16T14:26:58Z | 40,071,443 | <p>Assuming you want the variable <code>data</code> to be displayed in the scatter plot,</p>
<pre><code>ax.scatter(data.Weight, data.Height , color = 'red')
</code></pre>
| 0 | 2016-10-16T14:32:31Z | [
"python",
"numpy",
"matplotlib",
"plot"
] |
scatter plot and line in python | 40,071,398 | <p>I have a question about how to place scatter plot and line into one graph correctly.</p>
<p>Here is the code:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
t= np.linspace(60, 180,100)
ax= plt.subplot()
ax.plot(data.Weight, data.Height , color = 'red')
ax.plot(t, 60+ 0.05*t, label=r"$Height = 6... | 0 | 2016-10-16T14:26:58Z | 40,071,694 | <p>To scatter <code>data.Weight</code> against <code>data.Height</code>:</p>
<pre><code>ax.plot(data.Weight, data.Height , 'o', markerfacecolor = 'red')
</code></pre>
| 0 | 2016-10-16T14:57:59Z | [
"python",
"numpy",
"matplotlib",
"plot"
] |
Writing large amounts of numbers to a HDF5 file in Python | 40,071,425 | <p>I currently have a data-set with a million rows and each around 10000 columns (variable length).</p>
<p>Now I want to write this data to a HDF5 file so I can use it later on.
I got this to work, but it's <strong>incredibly slow</strong>. Even a 1000 values take up to a few minutes just to get stored in the HDF5 fil... | 0 | 2016-10-16T14:30:15Z | 40,074,505 | <p>Following <a href="http://docs.h5py.org/en/latest/special.html" rel="nofollow">http://docs.h5py.org/en/latest/special.html</a></p>
<p>and using an open h5 file <code>f</code>, I tried:</p>
<pre><code>dt = h5py.special_dtype(vlen=np.dtype('int32'))
vset=f.create_dataset('vset', (100,), dtype=dt)
</code></pre>
<p>S... | 1 | 2016-10-16T19:27:07Z | [
"python",
"numpy",
"hdf5",
"numpy-broadcasting"
] |
Prevent Tweepy from falling behind | 40,071,459 | <p><code>streamer.filter(locations=[-180, -90, 180, 90], languages=['en'], async=True)</code></p>
<p>I am trying to extract the tweets which have been geotagged from the twitter streaming API using the above call. However, I guess tweepy is not able to handle the requests and quickly falls behind the twitter rate. Is ... | 0 | 2016-10-16T14:34:08Z | 40,072,173 | <p>There is no workaround to rate limits other than polling for the rate limit status and waiting for the rate limit to be over. you can also use the flag 'wait_on_rate_limit=True'. This way tweepy will poll for rate limit by itself and sleep until the rate limit period is over.</p>
<p>You can also use the flag 'monit... | 0 | 2016-10-16T15:48:15Z | [
"python",
"twitter",
"tweepy"
] |
Swapping characters in string inputted from user in python | 40,071,461 | <p>I'm a beginner in Python. I have already taken an input from the user for string and turned it into a list so I can manipulate the individual characters. I know how to switch say, the first and last letter, etc. but I am confused on what code to use because I don't know how many characters the user will input. Someo... | -2 | 2016-10-16T14:34:23Z | 40,071,495 | <p>In python, reversing the order of a list is as simple as <code>list[::-1]</code></p>
<p>So say</p>
<pre><code>a='my_string'
a=a[::-1]
print(a)
</code></pre>
<p>Your output will be </p>
<pre><code>gnirts_ym
</code></pre>
<p>For more information on how this works, have a look at <a href="http://pythoncentral.io/h... | -3 | 2016-10-16T14:37:58Z | [
"python",
"string",
"python-3.x"
] |
python import error: cannot open shared object file | 40,071,541 | <p>My python code gives this error:</p>
<p><code>from cv_bridge import CvBridge, CvBridgeError</code> </p>
<p>ImportError: libcv_bridge.so: cannot open shared object file: No such file or directory.</p>
<p>However if I do a ldd, every thing seems fine. What is wrong?
(ROS indigo, ubuntu 14.04 LTS, PyCharm)</p>
<pre... | 0 | 2016-10-16T14:42:11Z | 40,071,962 | <p>You need to export the relevant LD LIBRARY path and add it in your bash profile file as in this example:</p>
<p><a href="http://stackoverflow.com/questions/7880454/python-executable-not-finding-libpython-shared-library">Python executable not finding libpython shared library</a></p>
| 0 | 2016-10-16T15:25:01Z | [
"python",
"ldd"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.