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
sequence |
---|---|---|---|---|---|---|---|---|---|
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</em> of <code>dict1</code> and, using the corresponding <em>value</em> from <code>dict1</code> as a key, looks up the value in <code>dict2</code>. The key from <code>dict1</code> and the value from <code>dict2</code> are then combined to produce a new dictionary.</p>
<p>Note that, in Python 2, this should be slightly faster then using <code>dict1.items()</code> because that will build a temporary list. Similarly, iterating over <code>dict1.iteritems()</code> returns an iterator which has to be created, but that is neglible. Iterating directly over a dictionary's keys also incurs minimal overhead.</p>
| 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 1ca11bb1b1a1b1
4 bb1111b1111
5 b1111c1aa111
6 1b1a111b11b1ab
7 1bc111ab1ba
8 a11b1b1b11111
9 1cc1ab1acc1
dtype: object
</code></pre>
<hr>
<p>I'm looking to count the number of groups of consecutive digits in each element of <code>s</code>. Or, how many integers are in each string.</p>
<p>I'd expec the result to look like</p>
<pre><code>0 2
1 3
2 5
3 6
4 2
5 3
6 5
7 3
8 4
9 4
dtype: int64
</code></pre>
<p>I'm looking for efficiency, though elegance is important too.</p>
| 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 2
1 3
2 5
3 6
4 2
5 3
6 5
7 3
8 4
9 4
dtype: int64
</code></pre>
<p>Timing against 100K Series:</p>
<pre><code>In [160]: %timeit big.replace(['\d+', '[^1]+'], ['1', ''], regex=True).str.len()
1 loop, best of 3: 1 s per loop
In [161]: %timeit big.apply(lambda x: len(re.sub('\D+', ' ', x).strip().split()))
1 loop, best of 3: 1.18 s per loop
In [162]: %timeit big.str.replace(r'\D+', ' ').str.strip().str.split().str.len()
1 loop, best of 3: 1.25 s per loop
In [163]: big.shape
Out[163]: (100000,)
</code></pre>
<p>Timing against 1M Series:</p>
<pre><code>In [164]: big = pd.concat([s] * 10**5, ignore_index=True)
In [165]: %timeit big.replace(['\d+', '[^1]+'], ['1', ''], regex=True).str.len()
1 loop, best of 3: 9.98 s per loop
In [166]: %timeit big.apply(lambda x: len(re.sub('\D+', ' ', x).strip().split()))
1 loop, best of 3: 11.7 s per loop
In [167]: %timeit big.str.replace(r'\D+', ' ').str.strip().str.split().str.len()
1 loop, best of 3: 12.6 s per loop
In [168]: big.shape
Out[168]: (1000000,)
</code></pre>
<p>Explanation:</p>
<pre><code>In [169]: s.replace(['\d+', '[^1]+'], ['1', ''], regex=True)
Out[169]:
0 11
1 111
2 11111
3 111111
4 11
5 111
6 11111
7 111
8 1111
9 1111
dtype: object
</code></pre>
<p><strong>OLD (slow) answer:</strong></p>
<p>What about using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.extractall.html" rel="nofollow">.str.extractall()</a> in conjunction with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.groupby.html" rel="nofollow">.groupby(level=0)</a>?</p>
<pre><code>In [130]: s.str.extractall('(\d+)').groupby(level=0).count()
Out[130]:
0
0 2
1 3
2 5
3 6
4 2
5 3
6 5
7 3
8 4
9 4
</code></pre>
<p>Explanation:</p>
<pre><code>In [131]: s.str.extractall('(\d+)')
Out[131]:
0
match
0 0 11111
1 1
1 0 1
1 111
2 1
2 0 11
1 1
2 11
3 11
4 11
3 0 1
1 11
2 1
3 1
4 1
5 1
4 0 1111
1 1111
5 0 1111
1 1
2 111
6 0 1
1 1
2 111
3 11
4 1
7 0 1
1 111
2 1
8 0 11
1 1
2 1
3 11111
9 0 1
1 1
2 1
3 1
</code></pre>
| 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 1ca11bb1b1a1b1
4 bb1111b1111
5 b1111c1aa111
6 1b1a111b11b1ab
7 1bc111ab1ba
8 a11b1b1b11111
9 1cc1ab1acc1
dtype: object
</code></pre>
<hr>
<p>I'm looking to count the number of groups of consecutive digits in each element of <code>s</code>. Or, how many integers are in each string.</p>
<p>I'd expec the result to look like</p>
<pre><code>0 2
1 3
2 5
3 6
4 2
5 3
6 5
7 3
8 4
9 4
dtype: int64
</code></pre>
<p>I'm looking for efficiency, though elegance is important too.</p>
| 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></pre>
<p><a href="https://i.stack.imgur.com/7yQDE.png" rel="nofollow"><img src="https://i.stack.imgur.com/7yQDE.png" alt="enter image description here"></a></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 1ca11bb1b1a1b1
4 bb1111b1111
5 b1111c1aa111
6 1b1a111b11b1ab
7 1bc111ab1ba
8 a11b1b1b11111
9 1cc1ab1acc1
dtype: object
</code></pre>
<hr>
<p>I'm looking to count the number of groups of consecutive digits in each element of <code>s</code>. Or, how many integers are in each string.</p>
<p>I'd expec the result to look like</p>
<pre><code>0 2
1 3
2 5
3 6
4 2
5 3
6 5
7 3
8 4
9 4
dtype: int64
</code></pre>
<p>I'm looking for efficiency, though elegance is important too.</p>
| 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+', ' ').str.strip().str.split().str.len()
1 loop, best of 3: 403 ms per loop
In [145]: s.shape
Out[145]: (100000L,)
</code></pre>
| 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 rectangle picture.</p>
<p>As per the pics below, this is the Output of what is required.</p>
<p><a href="https://i.stack.imgur.com/p31tA.png" rel="nofollow">Output</a></p>
<p>I know how to mirror a pic (as shown below) with a square image, but i cannot work out if this can also be done with a rectangle image?</p>
<p><a href="https://i.stack.imgur.com/rBFKH.png" rel="nofollow">Cross</a></p>
<p>I had a look at a method of using y=mx+b but it seems overcomplicated?
Maybe there is some coordinate geometry i need? Or algebra?
Any help would be greatly appreciated!</p>
| 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 rectangle picture.</p>
<p>As per the pics below, this is the Output of what is required.</p>
<p><a href="https://i.stack.imgur.com/p31tA.png" rel="nofollow">Output</a></p>
<p>I know how to mirror a pic (as shown below) with a square image, but i cannot work out if this can also be done with a rectangle image?</p>
<p><a href="https://i.stack.imgur.com/rBFKH.png" rel="nofollow">Cross</a></p>
<p>I had a look at a method of using y=mx+b but it seems overcomplicated?
Maybe there is some coordinate geometry i need? Or algebra?
Any help would be greatly appreciated!</p>
| 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 pixel
for y in range(h):
for x in range(w):
# Map to tangent/normal space
n = (x+0.5 - x0)*nx + (y+0.5 - y0)*ny
t = (x+0.5 - x0)*tx + (y+0.5 - y0)*ty
# If we're in the positive half-space
if n >= 0:
# Compute mirrored point in XY space
# (negate the normal component)
xx = int(x0 + t*tx - n*nx + 0.5)
yy = int(y0 + t*ty - n*ny + 0.5)
# If valid copy to destination
if 0 <= xx < w and 0 <= yy < h:
img[y][x] = img[yy][xx]
</code></pre>
<p>Here you can see an example of the results
<a href="https://i.stack.imgur.com/4lzrZ.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/4lzrZ.jpg" alt="example of mirroring"></a></p>
<p>The top-left red corner are pixels that would be mirroring pixels outside of the original image and they're left untouched by the above code.</p>
| 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 first axis, we are using a shape of <code>-1</code> to <em>push all elements</em> into it.</p>
<p>Sample run -</p>
<pre><code>In [119]: x = np.array([2,5,6,4])
In [120]: x.reshape((-1,) + (1,)*9).shape
Out[120]: (4, 1, 1, 1, 1, 1, 1, 1, 1, 1)
</code></pre>
| 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.init()
rot = (255,0,0)
grün = (0,255,0)
blau = (0,0,255)
gelb = (255,255,0)
schwarz = (0,0,0)
weià = (255,255,255)
uhr = pygame.time.Clock()
display = pygame.display.set_mode((800, 600))
pygame.display.set_mode((800, 600))
pygame.display.set_caption('Snake')
display.fill(weiÃ)
def arialmsg(msg, color, x, y, s):
header = pygame.font.SysFont("Arial", s)
text = header.render(msg, True, color)
display.blit(text, [x, y])
def mainloop():
gameExit = False
start = False
movex = 400
movey = 300
changex = 0
changey = -2
rx = random.randrange(10, 790)
ry = random.randrange(10, 590)
snakelist = []
snakelenght = 20
#coinlist defined here:
coinlist = []
while start == False:
display.fill(schwarz)
arialmsg('Snake', grün, 350, 200, 25)
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RETURN:
start = True
pygame.display.flip()
#gameloop:
while gameExit == False:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_DOWN:
changey = 2
changex = 0
elif event.key == pygame.K_UP:
changey = -2
changex = 0
elif event.key == pygame.K_RIGHT:
changex = 2
changey = 0
elif event.key == pygame.K_LEFT:
changex = -2
changey = 0
movex += changex
movey += changey
snakehead = []
snakehead.append(movex)
snakehead.append(movey)
snakelist.append(snakehead)
display.fill(schwarz)
if len(coinlist) < 1:
rx = random.randrange(10, 790)
ry = random.randrange(10, 590)
coinlist.append(rx)
coinlist.append(ry)
for XY in snakelist:
pygame.draw.circle(display, grün, (XY[0], XY[1]), 10, 10)
for-loop for the coinlist:
for coin in coinlist:
pygame.draw.rect(display, grün, (coin[0], coin[1], 10, 10))
pygame.display.flip()
if snakelenght < len(snakelist):
del snakelist[:1]
if movex >= rx - 19 and movex <= rx + 19 and movey >= ry - 19 and movey <= ry + 19:
del coinlist[:1]
snakelenght += 10
uhr.tick(15)
mainloop()
pygame.quit()
quit()
</code></pre>
| 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.append([rx,ry])
</code></pre>
| 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/24744347,2016-03-27 01:08:59,44,,Р СâºÐ  Рâ¦Ð  Ð»Р Ð°Р вââÐ Â Ð â¦-Р СР Ð°Р СâÐ Â Ð°Р Ð·Р СâÐ Â Ð â¦
e29bea24f74b7fb26cb9c14ef8c3b10b,ozon.ru/context/detail/id/135168438,2016-03-27 01:11:39,6,,Р СâºÐ  Рâ¦Ð  Ð»Р Ð°Р вââÐ Â Ð â¦-Р СР Ð°Р СâÐ Â Ð°Р Ð·Р СâÐ Â Ð â¦
e29bea24f74b7fb26cb9c14ef8c3b10b,ozon.ru/context/detail/id/33290689,2016-03-27 01:12:37,8,,Р СâºÐ  Рâ¦Ð  Ð»Р Ð°Р вââÐ Â Ð â¦-Р СР Ð°Р СâÐ Â Ð°Р Ð·Р СâÐ Â Ð â¦
e29bea24f74b7fb26cb9c14ef8c3b10b,ozon.ru/context/detail/id/31642544,2016-03-27 01:13:07,14,,Р СâºÐ  Рâ¦Ð  Ð»Р Ð°Р вââÐ Â Ð â¦-Р СР Ð°Р СâÐ Â Ð°Р Ð·Р СâÐ Â Ð â¦
1cf378e0ba824651d9d80b076514bfe7,citilink.ru,2016-03-27 01:54:22,12,,Р СâºÐ  Рâ¦Ð  Ð»Р Ð°Р вââÐ Â Ð â¦-Р СР Ð°Р СâÐ Â Ð°Р Ð·Р СâÐ Â Ð â¦
1cf378e0ba824651d9d80b076514bfe7,citilink.ru/catalog/computers_and_notebooks/net_equipment/netcards/90520,2016-03-27 01:55:26,20,,Р СâºÐ  Рâ¦Ð  Ð»Р Ð°Р вââÐ Â Ð â¦-Р СР Ð°Р СâÐ Â Ð°Р Ð·Р СâÐ Â Ð â¦
1cf378e0ba824651d9d80b076514bfe7,citilink.ru/catalog/computers_and_notebooks/net_equipment/netcards/896835,2016-03-27 01:55:58,10,,Р СâºÐ  Рâ¦Ð  Ð»Р Ð°Р вââÐ Â Ð â¦-Р СР Ð°Р СâÐ Â Ð°Р Ð·Р СâÐ Â Ð â¦
1cf378e0ba824651d9d80b076514bfe7,citilink.ru/catalog/computers_and_notebooks/net_equipment/netcards/896840,2016-03-27 01:57:48,52,,Р СâºÐ  Рâ¦Ð  Ð»Р Ð°Р вââÐ Â Ð â¦-Р СР Ð°Р СâÐ Â Ð°Р Ð·Р СâÐ Â Ð â¦
</code></pre>
<p>I use</p>
<pre><code>names = ['ID', 'url', 'date', 'duration', 'request', 'category']
df = pd.read_csv('pv-lena11.csv', sep=",", header=None, names=names)
</code></pre>
<p>but it doesn't separate that.</p>
| -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 solution to get the same arrays on Mac and Linux?</p>
| 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/libjpeg-turbo/lib/libjpeg.a /path/to/OpenCV
</code></pre>
<p>One of the libjpg source: <a href="https://github.com/libjpeg-turbo/libjpeg-turbo" rel="nofollow">link</a></p>
<p>Currently it is giving different result due to different version of libjpg in these OS.</p>
| 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)
syn = html.xpath("//DIV[@id='filters-0']")
print(syn)
</code></pre>
<p>If you are good at python, then tell me how to do such a task more concise and simple.
Big thanks!</p>
| -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)
syn = html.xpath("//DIV[@id='filters-0']")
print(syn)
</code></pre>
<p>If you are good at python, then tell me how to do such a task more concise and simple.
Big thanks!</p>
| -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>
<pre><code>import win32com.client as win32
xl = win32.gencache.EnsureDispatch('Excel.Application')
xl.Visible = True
wb = xl.Workbooks.Open(r'Test.xlsx')
sh = wb.ActiveSheet
xl.ScreenUpdating = True
last_col = sh.UsedRange.Columns.Count
last_row = sh.UsedRange.Rows.Count
my_range = sh.Range(sh.Cells(1, 1), sh.Cells(last_row, 4))
my_range.Select()
xl.Selection.ClearContents()
</code></pre>
<p>So, what I would like to do, is like in VBA:</p>
<pre><code>Columns("A:D").Clear
</code></pre>
<p>Is there any way to work with rows and columns with Python, and not only with ranges? </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 for these softwares and the language is natively built-in but VBA is actually a component. Under Tools/References in IDE, you will see VBA is first checked item. </p>
<p>So, with the Windows <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/ms680573(v=vs.85).aspx" rel="nofollow">Component Object Model (COM)</a>, any general purpose language including Python, PHP, R, Java, C#, etc. can connect to the Excel Object Library and make calls to workbook objects and methods. You just have to adhere to the languages' syntax. As example:</p>
<p><strong>Python</strong> <em>(win32com module)</em></p>
<pre class="lang-py prettyprint-override"><code>sh.Columns("A:D").Clear()
</code></pre>
<p><strong>PHP</strong> <em>(<a href="http://php.net/manual/en/class.com.php" rel="nofollow">COM</a> class)</em></p>
<pre class="lang-php prettyprint-override"><code>sh->Columns("A:D")->Clear()
</code></pre>
<p><strong>R</strong> <em>(<a href="http://www.omegahat.net/RDCOMClient/Docs/introduction.html" rel="nofollow">RDCOMClient</a> module)</em></p>
<pre class="lang-r prettyprint-override"><code>sh$Columns("A:D")$Clear()
</code></pre>
<hr>
<p>Also, consider running your code in <code>try...except...finally</code> blocks to catch exceptions and properly uninitialize COM objects regardless if your code errors out or not. Otherwise, the Excel.exe process will continue running in background.</p>
<pre><code>import win32com.client as win32
try:
xl = win32.gencache.EnsureDispatch('Excel.Application')
xl.Visible = True
wb = xl.Workbooks.Open(r'C:\Path\To\Test.xlsx')
sh = wb.ActiveSheet
xl.ScreenUpdating = True
sh.Columns("A:D").Clear()
except Exception as e:
print(e)
finally:
sh = None
wb = None
xl = None
</code></pre>
| 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:
MenuChoice = str(input("Please enter your choice here ----------------->>>>>"))
except ValueError:
print("Please enter one of the menu choices above, TRY AGAIN ")
</code></pre>
<p>I just want to know a way in which I can insure that only the numbers 1 to 5 are accepted and that if anything else is entered then the program asks the question again.</p>
<p>Please dont roast me.</p>
<p>Thanks</p>
| -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("Type 4 to enter the fourth option")
print("Press x to quit")
while not (1 <= MenuChoice <= 4):
MenuChoice = input("Please enter your choice here ----------------->>>>>")
if MenuChoice == 'x' : break
try:
MenuChoice = int(MenuChoice)
except ValueError:
print("Please enter one of the menu choices above, TRY AGAIN ")
MenuChoice = 0 # We need this in case MenuChoice is a string, so we need to default it back to 0 for the conditional to work
</code></pre>
<p>We make our input an integer so that we can see if it's between 1-5. Also, you should put your beginning print statements outside of the loop so it doesn't continually spam the reader (unless this is what you want).</p>
| 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:
MenuChoice = str(input("Please enter your choice here ----------------->>>>>"))
except ValueError:
print("Please enter one of the menu choices above, TRY AGAIN ")
</code></pre>
<p>I just want to know a way in which I can insure that only the numbers 1 to 5 are accepted and that if anything else is entered then the program asks the question again.</p>
<p>Please dont roast me.</p>
<p>Thanks</p>
| -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 ("Only Use number 1 to 4 or x to Quit... Thanks please try again")
MenuChoice = raw_input("Please enter your choice here ----------------->>>>> ")
try:
MenuChoice = int(MenuChoice)
except:
MenuChoice1 = str(MenuChoice)
if MenuChoice1 == 'x' or 1 <= MenuChoice <= 4:
print "You selected %r Option.. Thank you & good bye"%(MenuChoice)
time.sleep(2)
break
except:
pass
</code></pre>
| 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 __init__
self.service.start()
File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/common/service.py", line 71, in start
os.path.basename(self.path), self.start_error_message)
selenium.common.exceptions.WebDriverException: Message: 'geckodriver' executable needs to be in PATH.
Exception AttributeError: "'Service' object has no attribute 'process'" in <bound method Service.__del__ of <selenium.webdriver.firefox.service.Service object at 0x7f1aaba35110>> ignored
</code></pre>
<p>I am using Last Version of Kali Linux , and when I want to use program which using selenium , I take this error . So I try "pip uninstall selenium " - "pip install selenium " again , and nothing changes . Thanks for helps </p>
| -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", using this command: </p>
<pre><code>dataframe[['day','month','year']] = dataframe['release'].str.rsplit(expand=True)
</code></pre>
<p>The resulting dataframe is :
<a href="https://i.stack.imgur.com/695Hd.png" rel="nofollow">dataframe</a></p>
<p>As you can see, that it works perfectly when it gets 3 strings, but whenever it is getting less then 3 strings, it saves the data at the wrong place. </p>
<p>I have tried split and rsplit, both are giving the same result.
Any solution to get the data at the right place?</p>
<p>The last one is year and it is present in every condition , it should be the first one to be saved and then month if it is present otherwise nothing and same way the day should be stored.</p>
| 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", using this command: </p>
<pre><code>dataframe[['day','month','year']] = dataframe['release'].str.rsplit(expand=True)
</code></pre>
<p>The resulting dataframe is :
<a href="https://i.stack.imgur.com/695Hd.png" rel="nofollow">dataframe</a></p>
<p>As you can see, that it works perfectly when it gets 3 strings, but whenever it is getting less then 3 strings, it saves the data at the wrong place. </p>
<p>I have tried split and rsplit, both are giving the same result.
Any solution to get the data at the right place?</p>
<p>The last one is year and it is present in every condition , it should be the first one to be saved and then month if it is present otherwise nothing and same way the day should be stored.</p>
| 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 2012 2012 NaN NaN
2 31 January 2013 2013 January 31
3 February 2008 2008 February NaN
4 17 June 2014 2014 June 17
5 2013 2013 NaN NaN
</code></pre>
| 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.DiGraph(),nodetype=int)
in_degrees = webg.in_degree()
in_values = sorted(set(in_degrees.values()))
in_hist = [in_degrees.values().count(x)for x in in_values]
</code></pre>
<p>I want to plot degree distribution web graph
how can i change dict to solve?</p>
| -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.DiGraph(),nodetype=int)
in_degrees = webg.in_degree()
in_values = sorted(set(in_degrees.values()))
in_hist = [in_degrees.values().count(x)for x in in_values]
</code></pre>
<p>I want to plot degree distribution web graph
how can i change dict to solve?</p>
| -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>
<TD style="text-align:center;width:100px"></TD>
<TD style="text-align:center;width:50px">{% for z in recentResultHistory %} {{ z.0 }} {% endfor %}</TD>
</TR>
</code></pre>
<p>when the first instance of the <code>{% for z in recentResultHistory %} {{ z.0 }} {% endfor %}</code> runs I get the expected result. When it runs for the second time it produces no results like it is not looping at all. Do I need to reset the loop in some way?</p>
<p>The variable is created in my django view.py as follows:</p>
<pre><code> cursor = connection.cursor()
cursor.execute("""
select
team,
group_concat( concat(result, '-', convert(opponent USING utf8), '-', team_score, '-', opponent_score, '-', mstatus)
order by fixturedate desc
separator '|') as output from plain_result
where (select count(*)
from plain_result as p
where plain_result.team = p.team
and p.fixturedate>=plain_result.fixturedate) <= 5
group by team
""")
recentResultHistory = cursor.fetchall
</code></pre>
| 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. The first time you press it, it does nothing. The second time, it will move. If you then press "g", you don't move back to the left, instead the 2nd "k" gets processed and the "g" ends up "on deck". Here's the loop that's supposed to be processing the moves.</p>
<pre><code> def main_loop(self):
#This will catch and handle all keystrokes. Not too happy with if,elif,elif or case. Use a dict lookup eventually
while 1:
self.render_all()
c = self.main.getch()
try:
self.keybindings[c]["function"](**self.keybindings[c]["args"])
except KeyError:
continue
</code></pre>
<p>And here is the dictionary lookup I promised myself I'd use in that comment</p>
<pre><code> self.keybindings = {ord("h"): {"function":self.move_object,
"args":{"thing":self.things[0], "direction":"North"}},
ord('j'): {"function":self.move_object,
"args":{"thing":self.things[0], "direction":"South"}},
ord('g'): {"function":self.move_object,
"args":{"thing":self.things[0], "direction":"West"}},
ord('k'): {"function":self.move_object,
"args":{"thing":self.things[0], "direction":"East"}},
ord('y'): {"function":self.move_object,
"args":{"thing":self.things[0], "direction":"NorthWest"}},
ord('u'): {"function":self.move_object,
"args":{"thing":self.things[0], "direction":"NorthEast"}},
ord('b'): {"function":self.move_object,
"args":{"thing":self.things[0], "direction":"SouthWest"}},
ord('n'): {"function":self.move_object,
"args":{"thing":self.things[0], "direction":"SouthEast"}},
ord('l'): {"function":self.look, "args":{"origin_thing":self.things[0],}},
ord('q'): {"function":self.save_game,
"args":{"placeholder":0}}}
</code></pre>
<p>Finally, here is the move_object function that's supposed to be called:</p>
<pre><code> def move_object(self, thing, direction):
"""I chose to let the Game class handle redraws instead of objects.
I did this because it will make it easier should I ever attempt to rewrite
this with libtcod, pygcurses, or even some sort of browser-based thing.
Display is cleanly separated from obects and map data.
Objects use the variable name "thing" to avoid namespace collision."""
curx = thing.x
cury = thing.y
newy = thing.y + directions[direction][0]
newx = thing.x + directions[direction][1]
if not self.is_blocked(newx, newy):
logging.info("Not blocked")
thing.x = newx
thing.y = newy
</code></pre>
<h1>Edited to cleanup code formatting.</h1>
| -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%3A%2F%2Fscipy-cookbook.readthedocs.org%2F_images%2Fgriddataexample1.png&imgrefurl=https%3A%2F%2Fwizardforcel.gitbooks.io%2Fscipy-cookbook-en%2Fcontent%2F37.html&h=288&w=432&tbnid=j0EtJS7s1utbYM%3A&docid=KQV-DInQ9QIq2M&ei=L2ADWJqUJ8L9aemiiYAJ&tbm=isch&client=safari&iact=rc&uact=3&dur=1229&page=13&start=324&ndsp=31&ved=0ahUKEwja57uTmN_PAhXCfhoKHWlRApA4rAIQMwg0KDEwMQ&bih=739&biw=1438" rel="nofollow">http://images.google.fr/imgres?imgurl=http%3A%2F%2Fscipy-cookbook.readthedocs.org%2F_images%2Fgriddataexample1.png&imgrefurl=https%3A%2F%2Fwizardforcel.gitbooks.io%2Fscipy-cookbook-en%2Fcontent%2F37.html&h=288&w=432&tbnid=j0EtJS7s1utbYM%3A&docid=KQV-DInQ9QIq2M&ei=L2ADWJqUJ8L9aemiiYAJ&tbm=isch&client=safari&iact=rc&uact=3&dur=1229&page=13&start=324&ndsp=31&ved=0ahUKEwja57uTmN_PAhXCfhoKHWlRApA4rAIQMwg0KDEwMQ&bih=739&biw=1438</a>) However i can't figure out a way to do it using marplotlib. For now i have this code but it is irrelevant to what i am trying to show: </p>
<pre><code>for k in range(number gf bike stations):
</code></pre>
<p>T(k)/Tt is (occupation rate/average occupation rate) and R_0 is a list with all the data </p>
<pre><code>if T(k)/Tt>1.5: (if the occupation ratio is >1.5, i scatter a green dot and so on)
ax.scatter(R_0[k]['position']['lng'],R_0[k]['position']['lat'], color='g', s=10)
elif T(k)/Tt>1: (yellow dot)
ax.scatter(R_0[k]['position']['lng'],R_0[k]['position']['lat'], color='y', s=10)
elif T(k)/Tt>0.5: (red dot)
ax.scatter(R_0[k]['position']['lng'],R_0[k]['position']['lat'], color='r', s=10)
</code></pre>
| 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 example code or simple code Python.</p>
<p>Thank you very much</p>
<p>K.ademarus</p>
| -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>diffs</code> followed by the triplet into a list named <code>all_splits</code>. Finally, it sorts <code>all_splits</code>, and because each item in <code>all_splits</code> begins with <code>diffs</code> the saved tuples are sorted in order of their <code>diffs</code> from lowest to highest.</p>
<pre><code>def split_list_test(lst):
all_splits = []
for i in range(1, len(lst) - 1):
for j in range(i + 1, len(lst)):
splits = [lst[:i], lst[i:j], lst[j:]]
a, b, c = map(sum, splits)
diffs = sorted((abs(c-a), abs(c-b), abs(b-a)), reverse=True)
all_splits.append((diffs, splits))
all_splits.sort()
return all_splits
test = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
for row in split_list_test(test):
print(row)
</code></pre>
<p><strong>output</strong></p>
<pre><code>([60, 40, 20], [[10, 20, 30, 40, 50], [60, 70, 80], [90, 100]])
([60, 40, 20], [[10, 20, 30, 40, 50, 60], [70, 80], [90, 100]])
([140, 110, 30], [[10, 20, 30, 40, 50, 60], [70, 80, 90], [100]])
([140, 120, 20], [[10, 20, 30, 40, 50], [60, 70], [80, 90, 100]])
([160, 90, 70], [[10, 20, 30, 40], [50, 60, 70, 80], [90, 100]])
([170, 90, 80], [[10, 20, 30, 40], [50, 60, 70], [80, 90, 100]])
([180, 110, 70], [[10, 20, 30, 40, 50, 60, 70], [80, 90], [100]])
([200, 110, 90], [[10, 20, 30, 40, 50, 60, 70], [80], [90, 100]])
([200, 140, 60], [[10, 20, 30, 40, 50, 60], [70], [80, 90, 100]])
([200, 150, 50], [[10, 20, 30, 40, 50], [60, 70, 80, 90], [100]])
([210, 160, 50], [[10, 20, 30], [40, 50, 60, 70], [80, 90, 100]])
([240, 130, 110], [[10, 20, 30], [40, 50, 60, 70, 80], [90, 100]])
([240, 220, 20], [[10, 20], [30, 40, 50, 60, 70], [80, 90, 100]])
([240, 230, 10], [[10, 20, 30, 40], [50, 60], [70, 80, 90, 100]])
([250, 250, 0], [[10, 20, 30, 40], [50, 60, 70, 80, 90], [100]])
([260, 260, 0], [[10], [20, 30, 40, 50, 60, 70], [80, 90, 100]])
([270, 260, 10], [[10, 20, 30, 40, 50, 60, 70, 80], [90], [100]])
([280, 190, 90], [[10, 20, 30], [40, 50, 60], [70, 80, 90, 100]])
([280, 190, 90], [[10, 20, 30, 40, 50], [60], [70, 80, 90, 100]])
([300, 160, 140], [[10, 20], [30, 40, 50, 60, 70, 80], [90, 100]])
([310, 160, 150], [[10, 20], [30, 40, 50, 60], [70, 80, 90, 100]])
([330, 190, 140], [[10], [20, 30, 40, 50, 60], [70, 80, 90, 100]])
([330, 290, 40], [[10, 20, 30], [40, 50, 60, 70, 80, 90], [100]])
([340, 180, 160], [[10], [20, 30, 40, 50, 60, 70, 80], [90, 100]])
([340, 310, 30], [[10, 20, 30], [40, 50], [60, 70, 80, 90, 100]])
([350, 300, 50], [[10, 20, 30, 40], [50], [60, 70, 80, 90, 100]])
([370, 280, 90], [[10, 20], [30, 40, 50], [60, 70, 80, 90, 100]])
([390, 260, 130], [[10], [20, 30, 40, 50], [60, 70, 80, 90, 100]])
([390, 320, 70], [[10, 20], [30, 40, 50, 60, 70, 80, 90], [100]])
([410, 390, 20], [[10, 20, 30], [40], [50, 60, 70, 80, 90, 100]])
([420, 380, 40], [[10, 20], [30, 40], [50, 60, 70, 80, 90, 100]])
([430, 340, 90], [[10], [20, 30, 40, 50, 60, 70, 80, 90], [100]])
([440, 360, 80], [[10], [20, 30, 40], [50, 60, 70, 80, 90, 100]])
([460, 460, 0], [[10, 20], [30], [40, 50, 60, 70, 80, 90, 100]])
([480, 440, 40], [[10], [20, 30], [40, 50, 60, 70, 80, 90, 100]])
([510, 500, 10], [[10], [20], [30, 40, 50, 60, 70, 80, 90, 100]])
</code></pre>
<hr>
<p>The next script is a little more compact, and it only returns a single solution. It uses a different rule to decide on the minimal split. If <code>(a, b, c)</code> are the sums of the lists in a triplet, sorted from lowest to highest, then the absolute differences of those sums are <code>c-a</code>, <code>c-b</code>, and <code>b-a</code>. The sum of the differences is <code>c-a + c-b + b-a</code> which is equal to <code>2*(c-a)</code>, so we can find the minimal split (using this rule) by looking for the split with the minimal value of <code>c-a</code>.</p>
<pre><code>def keyfunc(seq):
sums = sorted(sum(u) for u in seq)
return sums[2] - sums[0]
def split_list(lst):
gen = ([lst[:i], lst[i:j], lst[j:]]
for i in range(1, len(lst) - 1)
for j in range(i + 1, len(lst)))
return min(gen, key=keyfunc)
test = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
print(split_list(test))
</code></pre>
<p><strong>output</strong></p>
<pre><code>[[10, 20, 30, 40, 50], [60, 70, 80], [90, 100]]
</code></pre>
<p>As you can see, for this <code>test</code> list this version gives the same solution as one of the minimal solutions found above.</p>
| 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 than a specific threshold and then put them into one class i.e. label them as for example 'zero'. </p>
<p>This is my attemp:</p>
<pre><code>value_count=df.label.value_counts()
threshold = 3
for index in value_count[value_count.values<=threshold].index:
df.label[df.label==index]='zero'
</code></pre>
<p>Is there a better way to do this?</p>
| 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 3 zero 0.516933
3 4 a 0.234042
4 3 zero -0.206185
5 7 zero 0.840724
6 12 a -0.728868
7 18 zero 0.111260
8 11 zero -0.471337
9 2 zero 0.030803
10 5 zero 1.012638
11 3 zero -1.233750
</code></pre>
<p>Here are my timings:</p>
<pre><code>df = pd.concat([df]*10**4)
%timeit df.groupby('label')['label'].transform('count') <= threshold
100 loops, best of 3: 7.86 ms per loop
%%timeit
value_count=df.label.value_counts()
df['label'].isin(value_count[value_count.values<=threshold].index)
100 loops, best of 3: 9.24 ms per loop
</code></pre>
| 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 than a specific threshold and then put them into one class i.e. label them as for example 'zero'. </p>
<p>This is my attemp:</p>
<pre><code>value_count=df.label.value_counts()
threshold = 3
for index in value_count[value_count.values<=threshold].index:
df.label[df.label==index]='zero'
</code></pre>
<p>Is there a better way to do this?</p>
| 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 zero 0.128430
6 12 a 0.200825
7 18 zero -0.560548
8 11 zero -2.925706
9 2 zero -0.061373
10 5 zero -0.632036
11 3 zero -1.061894
</code></pre>
<p>Timings</p>
<pre><code>In [87]: df = pd.concat([df]*10**4, ignore_index=True)
In [88]: %timeit df['label'].isin(value_count[value_count.values<=threshold].index)
100 loops, best of 3: 7.1 ms per loop
In [89]: %timeit df.groupby('label')['label'].transform('count') <= threshold
100 loops, best of 3: 11.7 ms per loop
In [90]: df.shape
Out[90]: (120000, 3)
</code></pre>
<p>You may want to benchmark with larger dataset. And, this may not be aaccurate to compare, since you're precomuting <code>value_count</code></p>
| 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">https://www.tripadvisor.com/Airline_Review-d8729164-Reviews-Cheap-Flights-or560-TAP-Portugal#REVIEWS</a></p>
<p>If there is a non english comment, then I want to print its translated english version. Otherwise if the comment is already in English, I want to print english itself. But its the code is skipping over these comments (not printing them). Also you can see in the output that comments are getting printed twice.</p>
<p>There are 10 reviews/comments (translated+ non translated) on this page & it should print them all.</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.common.by import By
import time
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Chrome()
driver.maximize_window()
url="https://www.tripadvisor.com/Airline_Review-d8729164-Reviews-Cheap-Flights-or560-TAP-Portugal#REVIEWS"
driver.get(url)
ctr=0
def expand_reviews(driver):
# TRYING TO EXPAND REVIEWS (& CLOSE A POPUP)
try:
driver.find_element_by_class_name("moreLink").click()
except:
print "err"
try:
driver.find_element_by_class_name("ui_close_x").click()
except:
print "err2"
try:
driver.find_element_by_class_name("moreLink").click()
except:
print "err3"
# FIRST EXPAND THE REVIEWS BY CLICKING "MORE" BUTTON
expand_reviews(driver)
for j in driver.find_elements_by_xpath("//div[@class='wrap']"): # FIND ALL REVIEW ELEMENTS
for ent in j.find_elements_by_xpath('.//p[@class="partial_entry"]'): # FIND REVIEW TEXT
# FIRST CHECK IF TRANSLATION IS AVAILABLE (I.E. NON ENGLISH COMMENTS)
if j.find_elements_by_css_selector('#REVIEWS .googleTranslation>.link'):
#print 'NOW PRINTING TRANSLATED COMMENTS'
gt= driver.find_elements(By.CSS_SELECTOR,"#REVIEWS .googleTranslation>.link")
size=len(gt)
while (ctr<size):
for i in gt:
try:
if not i.is_displayed():
continue
driver.execute_script("arguments[0].click()",i)
wait = WebDriverWait(driver, 10)
wait.until(EC.element_to_be_clickable((By.XPATH, ".//span[@class = 'ui_overlay ui_modal ']//div[@class='entry']")))
com= driver.find_element_by_xpath(".//span[@class = 'ui_overlay ui_modal ']//div[@class='entry']")
print com.text
print "++" * 60
time.sleep(5)
driver.find_element_by_class_name("ui_close_x").click()
time.sleep(5)
#loop+=1
except Exception as e:
print "skipped"
pass
ctr+=1
# COMMENT ALREADY IN ENGLISH, PRINT AS IT IS
else:
print ent
print "="*60
driver.quit()
</code></pre>
<p>================================THE OUTPUT=========================</p>
<pre><code><selenium.webdriver.remote.webelement.WebElement (session="15b6c83088a289e59c544a2c7787d27d", element="0.40753995907133644-28")>
============================================================
<selenium.webdriver.remote.webelement.WebElement (session="15b6c83088a289e59c544a2c7787d27d", element="0.40753995907133644-29")>
============================================================
<selenium.webdriver.remote.webelement.WebElement (session="15b6c83088a289e59c544a2c7787d27d", element="0.40753995907133644-30")>
============================================================
<selenium.webdriver.remote.webelement.WebElement (session="15b6c83088a289e59c544a2c7787d27d", element="0.40753995907133644-31")>
============================================================
<selenium.webdriver.remote.webelement.WebElement (session="15b6c83088a289e59c544a2c7787d27d", element="0.40753995907133644-32")>
============================================================
On my change my flight without asking my opinion or offer another solution without paying extra I stay more than 10 hours in boarding of room I have the urge to have something to eat I haven not even able to rest after my flight c is inadmissible night I no longer would resume this company and would not advise a person to take
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
A little apprehensive before but quickly lifted. Very welcome and good service from the PNC, hot meal and good even for this short flight (1h50). Good punctuality and boarding more efficient
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Everything normal. Aircraft clean and almost full. Embarking on time, regular. Arrive slightly earlier. friendly and courteous staff. On board it was given a snack.
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
In the recent past I have traveled a few times from Venice to Lisbon and from Venice to Oporto via Lisbon. Good facilities on land and aboard; friendly service, clean air, punctuality and competitive rates. recommended
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Sympathy and competence. The company strives to make passengers as comfortable as possible.
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
On my change my flight without asking my opinion or offer another solution without paying extra I stay more than 10 hours in boarding of room I have the urge to have something to eat I haven not even able to rest after my flight c is inadmissible night I no longer would resume this company and would not advise a person to take
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
A little apprehensive before but quickly lifted. Very welcome and good service from the PNC, hot meal and good even for this short flight (1h50). Good punctuality and boarding more efficient
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Everything normal. Aircraft clean and almost full. Embarking on time, regular. Arrive slightly earlier. friendly and courteous staff. On board it was given a snack.
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
</code></pre>
| 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.webdriver.common.by import By
import time
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Chrome()
driver.maximize_window()
url="https://www.tripadvisor.com/Airline_Review-d8729164-Reviews-Cheap-Flights-or560-TAP-Portugal#REVIEWS"
driver.get(url)
ctr=0
for j in driver.find_elements_by_xpath("//div[@class='wrap']"): # FIND ALL REVIEW ELEMENTS
for ent in j.find_elements_by_xpath('.//p[@class="partial_entry"]'): # FIND REVIEW TEXT
# FIRST CHECK IF TRANSLATION IS AVAILABLE (I.E. NON ENGLISH COMMENTS)
if j.find_elements_by_css_selector('#REVIEWS .googleTranslation>.link'):
#print 'NOW PRINTING TRANSLATED COMMENTS'
gt= driver.find_elements(By.CSS_SELECTOR,"#REVIEWS .googleTranslation>.link")
size=len(gt)
while (ctr<size):
for i in gt:
try:
if not i.is_displayed():
continue
driver.execute_script("arguments[0].click()",i)
wait = WebDriverWait(driver, 10)
wait.until(EC.element_to_be_clickable((By.XPATH, ".//span[@class = 'ui_overlay ui_modal ']//div[@class='entry']")))
com= driver.find_element_by_xpath(".//span[@class = 'ui_overlay ui_modal ']//div[@class='entry']")
print com.text
print "++" * 60
time.sleep(5)
driver.find_element_by_class_name("ui_close_x").click()
time.sleep(5)
#loop+=1
except Exception as e:
print "skipped"
pass
ctr+=1
# COMMENT ALREADY IN ENGLISH, PRINT AS IT IS
else:
print ent.text
print "="*60
driver.quit()
</code></pre>
<p>the output I am getting is:</p>
<pre><code>Quite comfortable for the economy class, with a friendly staff and good service. The food is good but could still be better.
============================================================
The pilot was amazing, soft take off, soft landing (even with ruf weather), very nice staff with amazing portuguese food and wine. The only downsize was the interior condition, although clean and without scratches or so you could see that is already aged. Appart from that all was good.
============================================================
Speedy check in process was very accurate and precise. They allowed cabin to be booked into the hold with no additional charges. Boarding was efficient and timely. the seats were very comfortable. Wide enough to fit me fairly comfortably with armrests that were able to lift during the flight. The really stand out thing for me was the leg space....
============================================================
My country's flag airline, It has struggle to survive in a hard economic cycle. Clever choice of unique African and south american cities, guarantied its continuity.~ Do not expect a exquisite food, alcoholic drinks, down to beer and wine, forget white spirits. Good safety record. Pilots well trained, good maintenance. I have flight TAP for the last 40 odd years...
============================================================
Our first trip to Europe on a long flight both ways. The flight TO Rome was good. I am tall and have back issues, and thank God we were able to get exit row seats. This made all the difference in the world. The food served was fair to good. There were movies offered which helped pass the time and...
============================================================
On my change my flight without asking my opinion or offer another solution without paying extra I stay more than 10 hours in boarding of room I have the urge to have something to eat I haven not even able to rest after my flight c is inadmissible night I no longer would resume this company and would not advise a person to take
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
A little apprehensive before but quickly lifted. Very welcome and good service from the PNC, hot meal and good even for this short flight (1h50). Good punctuality and boarding more efficient
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Everything normal. Aircraft clean and almost full. Embarking on time, regular. Arrive slightly earlier. friendly and courteous staff. On board it was given a snack.
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
In the recent past I have traveled a few times from Venice to Lisbon and from Venice to Oporto via Lisbon. Good facilities on land and aboard; friendly service, clean air, punctuality and competitive rates. recommended
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Sympathy and competence. The company strives to make passengers as comfortable as possible.
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
</code></pre>
<p><strong>Update for handling the things in comment:</strong></p>
<ol>
<li>First install ntkl using command "pip install nltk"</li>
<li>Once installation complete</li>
<li>Open python shell ..i.e, Idle</li>
<li>Type command: import nltk</li>
<li>now type: nltk.download()</li>
<li>The UI will open: click on Models...search for punkt & click on download</li>
<li>After this ...click on Corpora....search for stopwords & click on download</li>
</ol>
<p>One these installation are done: run following program:</p>
<pre><code>from selenium.webdriver.common.by import By
import time
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from nltk import word_tokenize
from nltk.corpus import stopwords
def detect_lang(text):
lang_ratios = {}
tokens = word_tokenize(text)
words = [word.lower() for word in tokens]
for language in stopwords.fileids():
stopwords_set = set(stopwords.words(language))
words_set = set(words)
common_elements = words_set.intersection(stopwords_set)
lang_ratios[language] = len(common_elements)
return max(lang_ratios, key=lang_ratios.get)
driver = webdriver.Chrome()
driver.maximize_window()
url="https://www.tripadvisor.com/Airline_Review-d8729164-Reviews-Cheap-Flights-or570-TAP-Portugal#REVIEWS"
driver.get(url)
ctr=0
time.sleep(5)
def expand_reviews(driver):
# TRYING TO EXPAND REVIEWS (& CLOSE A POPUP)
try:
driver.find_element_by_class_name("moreLink").click()
except:
print "err"
try:
driver.find_element_by_class_name("ui_close_x").click()
except:
print "err2"
try:
driver.find_element_by_class_name("moreLink").click()
except:
print "err3"
# # FIRST EXPAND THE REVIEWS BY CLICKING "MORE" BUTTON
expand_reviews(driver)
time.sleep(10)
for ent in driver.find_elements_by_xpath('.//div[@class="entry"]/p[1]'): # FIND REVIEW TEXT
lang = detect_lang(ent.text)
if (lang == 'english'):
print ent.text
print "=="*30
else:
if driver.find_elements_by_css_selector('#REVIEWS .googleTranslation>.link'):
gt= driver.find_elements(By.CSS_SELECTOR,"#REVIEWS .googleTranslation>.link")
size=len(gt)
while (ctr<(size/2)):
for i in gt:
try:
if not i.is_displayed():
continue
driver.execute_script("arguments[0].click()",i)
wait = WebDriverWait(driver, 10)
wait.until(EC.element_to_be_clickable((By.XPATH, ".//span[@class = 'ui_overlay ui_modal ']//div[@class='entry']")))
com= driver.find_element_by_xpath(".//span[@class = 'ui_overlay ui_modal ']//div[@class='entry']")
print com.text
print "++" * 60
time.sleep(5)
driver.find_element_by_class_name("ui_close_x").click()
time.sleep(5)
#loop+=1
except Exception as e:
print "skipped"
pass
ctr+=1
</code></pre>
<p>This will print following output:</p>
<pre><code> Speedy check in process was very accurate and precise. They allowed cabin to be booked into the... read more
============================================================
Very pleasant flight, excellent service on board and on the ground, the best seats in the Buisness Class and Top Food and drinks during the flight.
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Perfect atendimento.Bom care of Commissioners and Commissioners, punctuality. Good movies offered.
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Overall, a good flight! Time (departure and arrival). Enough time for the change to Lisbon. Very nice crew!
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
It was a flight noturno.Teve strong turbulence and I could not dormir.Rezei all night. After all it was a decent trip. only regret the discomfort of the aircraft but praise the good atendimento.Toda the crew was very kind and helpful.The journey back was quieter.
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
The food really is not the best to tell the truth, I could not even eat. But the service is very good.
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Kindness, professionalism, and willingness on the part of the crew: good landing and includes drinks and light dinner
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
On 9 October flown with this company. By delayed entering the unit departed late. Atmosphere Loos routine operation. The evening meal consisted of a tuna sandwich and a liquid plum in plastic vial. A choice of meat or cheese was not there. For me and many others so no meal on this flight. Downright depressing.
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Speedy check in process was very accurate and precise. They allowed cabin to be booked into the hold with no additional charges. Boarding was efficient and timely. the seats were very comfortable. Wide enough to fit me fairly comfortably with armrests that were able to lift during the flight. The really stand out thing for me was the leg space. I'm 6ft 4in and I was able to fully extend my legs under the chair in front of me. if for this reason alone I have started looking for other destinations they fly to. In flight entertainment was none existent but then it was only a short haul flight so I won't fault them. Food snack and beverages were included in the price. The in flight attendants were professional, courteous and well presented. I will definitely use them again in the future!
============================================================
My country's flag airline, It has struggle to survive in a hard economic cycle. Clever choice of unique African and south american cities, guarantied its continuity.~
Do not expect a exquisite food, alcoholic drinks, down to beer and wine, forget white spirits. Good safety record. Pilots well trained, good maintenance. I have flight TAP for the last 40 odd years I have seen many faces and crisis, however customer service really Bad.
============================================================
Our first trip to Europe on a long flight both ways. The flight TO Rome was good. I am tall and have back issues, and thank God we were able to get exit row seats. This made all the difference in the world. The food served was fair to good. There were movies offered which helped pass the time and blankets because the cabin got very cold. We had to sit in Lisbon Airport for six hours to complete our journey. It was tiring but still the trip was good (fun even)
The flight back home was not as pleasant. The first leg from Rome to Lisbon was horrible. The woman in front of me kept slamming her seat up against my legs and telling me she had to lay back and to put my tray table up. The flight attendant SAW this happen and did nothing. I found the crew to be very unfriendly on all legs of the flight. They were not warm and friendly and even bordered on rude at some point.
I would probably fly this airline again because the price was right and it was acceptable....
============================================================
</code></pre>
| 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 and every function. e.g. let's say a function trial(). If a function calls this function, then that function is in example category else non-example.</p>
| 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 called from method B or C; then your design is most likely ... <strong>broken</strong>. Having such dependencies within your code will <em>quickly</em> turn the whole thing un-maintainable. Simply because you will very soon be constantly asking yourself "that path seems fine, but will happen over here?"</p>
<p>One way out of that: create <strong>different</strong> methods; so that B can call something else as C does; but of course, you should still extract the common parts into <em>one</em> method.</p>
<p>Long story short: my non-answer is: take your current design; and have some other people review it. As you should step back from whatever you are doing right now; and find a way to it differently! You know, most of the times, when you start thinking about strange/awkward ways to solve a problem within your current code, the <em>real</em> problem <em>is</em> your current code.</p>
<p>EDIT: given your comments ... The follow up questions would be: what is the purpose of this classification? How often will it need to take place? You know, will it happen only once (then manual counting might be an option), or after each and any change? For the "manual" thing - ideas such as pycharm are pretty good in analyzing python source code, you can do simple things like "search usages in workspaces" - so the IDE lists you all those methods that invoke some method A. But of course, that works only for one <strong>level</strong>. </p>
<p>The other option I see: write some test code that imports all your methods; and then see how far the <a href="http://The%20follow%20up%20question%20would%20be:%20what%20is%20the%20purpose%20of%20this%20classification?%20How%20often%20will%20it%20need%20to%20take%20place?%20You%20know,%20will%20it%20happen%20only%20once%20(then%20manual%20counting%20might%20be%20an%20option),%20or%20after%20each%20and%20any%20change?%20For%20the%20%22manual%22%20thing%20-%20ideas%20such%20as%20pycharm%20are%20pretty%20good%20in%20analyzing%20python%20source%20code,%20you%20can%20do%20simple%20things%20like%20%22search%20usages%20in%20workspaces%22%20-%20so%20the%20IDE%20lists%20you%20all%20those%20methods%20that%20invoke%20some%20method%20A.%20But%20of%20course,%20that%20works%20only%20for%20one%20**level**.%20The%20other%20option%20I%20see:%20write%20some%20test%20code%20that%20imports%20all%20your%20methods;%20http://stackoverflow.com/questions/427453/how-can-i-get-the-source-code-of-a-python-function">inspect</a> module helps you. Probably you could really iterate through a complete method body and simply search for matching method names. </p>
| 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 definitions if it would help</p>
<p>(Ball class)</p>
<pre><code>def setPos(self, windowWidth, playerPosSizes, playerSpeed):
playerPosSizes[0].append(playerSpeed[0])
playerPosSizes[1].append(playerSpeed[1])
playerPosSizeSp = playerPosSizes
</code></pre>
<p>(Player Class)</p>
<pre><code>def getPosSize(self):
return self.posSize
def getSpeed(self):
return self.ysp
</code></pre>
<p>this is the output:</p>
<pre><code>[80, 285.0, 40, 150]
[80, 285.0, 40, 150, 0.0]
</code></pre>
<p>So the list that <code>getPosSize()</code> returns is changed. This is weird because <code>getPosSize</code> returns a list <code>posSize</code> that exists ONLY in the class player. And I'm using the VALUE of <code>posSize</code> in the method of AN OTHER class. I don't see how <code>posSize</code> list can be changed! I mean when I call <code>getPosSize</code> I will get a copy of the <code>posSize</code>, right? So when I use that copy in the method <code>setPos</code> of the ball class the original <code>posSize</code> shouldn't change. </p>
<p>I'm really sorry if the code looks confusing I've tried to only include the relevant parts. </p>
| 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 __init__(self):
self.lst = [4, 5, 6]
def get_cls_pos(self):
return One.CLS_LST
def get_pos(self):
return self.lst
class Two:
def do_smthng(self, data):
data.append(-1)
a = One()
print('This is One.CLS_LST: {}'.format(a.CLS_LST))
print('This is a.lst: {}'.format(a.lst))
b = Two()
print('Calling b do something with One.CLS_LST')
b.do_smthng(a.get_cls_pos())
print('This is One.CLS_LST: {}'.format(a.CLS_LST))
print('Calling b to do something with a.lst')
b.do_smthng(a.get_pos())
print('This is a.lst: {}'.format(a.lst))
</code></pre>
<p>The result of this code will print:</p>
<pre><code>This is One.CLS_LST: [1, 2, 3]
This is a.lst: [4, 5, 6]
Calling b to do something with One.CLS_LST
This is One.CLS_LST: [1, 2, 3, -1]
Calling b to do something with a.lst
This is a.lst: [4, 5, 6, -1]
</code></pre>
<p>If you really want to pass the copy of list, try to use <code>return list[:]</code>.</p>
| 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 definitions if it would help</p>
<p>(Ball class)</p>
<pre><code>def setPos(self, windowWidth, playerPosSizes, playerSpeed):
playerPosSizes[0].append(playerSpeed[0])
playerPosSizes[1].append(playerSpeed[1])
playerPosSizeSp = playerPosSizes
</code></pre>
<p>(Player Class)</p>
<pre><code>def getPosSize(self):
return self.posSize
def getSpeed(self):
return self.ysp
</code></pre>
<p>this is the output:</p>
<pre><code>[80, 285.0, 40, 150]
[80, 285.0, 40, 150, 0.0]
</code></pre>
<p>So the list that <code>getPosSize()</code> returns is changed. This is weird because <code>getPosSize</code> returns a list <code>posSize</code> that exists ONLY in the class player. And I'm using the VALUE of <code>posSize</code> in the method of AN OTHER class. I don't see how <code>posSize</code> list can be changed! I mean when I call <code>getPosSize</code> I will get a copy of the <code>posSize</code>, right? So when I use that copy in the method <code>setPos</code> of the ball class the original <code>posSize</code> shouldn't change. </p>
<p>I'm really sorry if the code looks confusing I've tried to only include the relevant parts. </p>
| 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.posSize</code> to <code>ball.posSize = player1.posSize[:]</code></p>
| 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 datetime import *
def main():
s = socket()
client_socket = None
s.bind(("127.0.0.1",8200))
print "1:time"
print "2:get list of files"
print "3:download file"
print "4:quit"
input()
s.listen(1)
client_socket, client_address = s.accept()
strn=client_socket.recv(4096)
if int(strn[0])>4 or int(strn[0])<1:
print "please send a num between 1-4"
elif int(strn[0])==1:
print datetime.time(datetime.now())
elif int(strn[0])==2:
folder=raw_input("enter the name of the folder")
dir(folder)
client_socket.close()
s.close()
input()
if name == '__main__':
main()
</code></pre>
<p>the client </p>
<pre><code>from socket import *
def main():
s = socket()
s.connect(("127.0.0.1",8200))
buf = raw_input()
s.send(buf)
s.close()
input()
if name == '__main__':
main()
</code></pre>
<p>the error </p>
<pre><code>Traceback (most recent call last):
File "D:\client.py", line 10, in <module>
main()
File "D:\client.py", line 4, in main
s.connect(("127.0.0.1",8200))
File "C:\Python27\lib\socket.py", line 228, in meth
return getattr(self._sock,name)(*args)
error: [Errno 10061] No connection could be made because the target machine actively refused it
</code></pre>
| -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 datetime import *
def main():
s = socket()
client_socket = None
s.bind(("127.0.0.1",8200))
print "1:time"
print "2:get list of files"
print "3:download file"
print "4:quit"
input()
s.listen(1)
client_socket, client_address = s.accept()
strn=client_socket.recv(4096)
if int(strn[0])>4 or int(strn[0])<1:
print "please send a num between 1-4"
elif int(strn[0])==1:
print datetime.time(datetime.now())
elif int(strn[0])==2:
folder=raw_input("enter the name of the folder")
dir(folder)
client_socket.close()
s.close()
input()
if name == '__main__':
main()
</code></pre>
<p>the client </p>
<pre><code>from socket import *
def main():
s = socket()
s.connect(("127.0.0.1",8200))
buf = raw_input()
s.send(buf)
s.close()
input()
if name == '__main__':
main()
</code></pre>
<p>the error </p>
<pre><code>Traceback (most recent call last):
File "D:\client.py", line 10, in <module>
main()
File "D:\client.py", line 4, in main
s.connect(("127.0.0.1",8200))
File "C:\Python27\lib\socket.py", line 228, in meth
return getattr(self._sock,name)(*args)
error: [Errno 10061] No connection could be made because the target machine actively refused it
</code></pre>
| -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' : pd.date_range('1/3/2011', periods=10, freq='D'),
'Plant' : pd.Series(["Plant2"]*10),
'Output' : pd.Series(abs(np.random.randn(10)))}
plant3 = {'Date' : pd.date_range('1/5/2011', periods=10, freq='D'),
'Plant' : pd.Series(["Plant3"]*10),
'Output' : pd.Series(abs(np.random.randn(10)))}
df_plant_1 = pd.DataFrame(plant1)
df_plant_2 = pd.DataFrame(plant2)
df_plant_3 = pd.DataFrame(plant3)
sample = pd.concat([df_plant_1,df_plant_2,df_plant_3])
</code></pre>
<p>My output is meant to be an area plot with each individual plant and the respective y-Value (Output) and x-value (Date). Notice that "Dates" are only partially overlapping.</p>
<p>I am stuck at finding a way to meaningful organize my data. The first challenge is to merge the data for duplicate "Date"-Values. The next step would be to fill the resulting holes in the series with .fillna(). The final step would be to plot for each unique "Plant"-value.</p>
<p>However, I am already stuck at the first step. I am aware of the .merge function, but don't know how to apply it to this case.</p>
<p>Thank you for your time and consideration.</p>
| 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="https://i.stack.imgur.com/QmtA4.png" rel="nofollow"><img src="https://i.stack.imgur.com/QmtA4.png" alt="enter image description here"></a></p>
| 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>
<p>Any suggestions what is causing this error are appreciated:</p>
<pre><code>'DataFlowAnalysis' object has no attribute 'op_STORE_DEREF'
</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()
---------------------------------------------------------------------------
NotImplementedError : Failed at nopython (nopython mode backend)
cannot convert native str to Python object
</code></pre>
<p>That specific error is because list comprehensions are also not currently supported in nopython mode.</p>
<p><a href="https://github.com/numba/numba/issues/504" rel="nofollow">https://github.com/numba/numba/issues/504</a></p>
| 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),("один","два","ÑÑи","ÑеÑÑÑе","пÑÑÑ","ÑеÑÑÑ","ÑемÑ","воÑемÑ","девÑÑÑ"))}
</code></pre>
<p>Imagine that I should find the digit if roomnum ="одна"
Here is how I trying to match this:</p>
<pre><code> if roomnum.isalpha():
for key,value in azeri_nums.items():
if value.startswith(roomnum.lower()):
roomnum = str(key)
break
if roomnum.isalpha():
for key,value in russian_nums.items():
if value.startswith(roomnum.lower()):
roomnum = str(key)
break
</code></pre>
<p>is there any other method to do that that will work faster, or some best practices for this situation?</p>
<p>Thank you in advance!</p>
<p>P.S.
the reason that this code works that module "re" capture from "одна" only "од" and that is why "один".startswith("од") returns true.</p>
| 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),("один","два","ÑÑи","ÑеÑÑÑе","пÑÑÑ","ÑеÑÑÑ","ÑемÑ","воÑемÑ","девÑÑÑ"))}
</code></pre>
<p>And once you've names mapped to digits, just use:</p>
<pre><code>key = None # By default
roomnum_lower = roomnum.lower()
if roomnum_lower in azeri_nums:
key = azeri_nums[roomnum_lower]
elif roomnum_lower in russian_nums:
key = russian_nums[roomnum_lower]
</code></pre>
<p>Dictionary is based on keysearch, not valuesearch. The first one is O(1) and allows u to use <code>key in dict</code> when the 2nd one is O(n) and requires looping.</p>
<h1>EDIT TO COMMENT:</h1>
<p>if you want to map one word to others, create another dict that will handle it.</p>
<pre><code> string_map = {'одна': ['один',]} # map single string to many others if u want
</code></pre>
<p>And then all u need to do is:</p>
<pre><code>key = None # By default
roomnum_lower = roomnum.lower()
if roomnum_lower in azeri_nums:
key = azeri_nums[roomnum_lower]
elif roomnum_lower in russian_nums:
key = russian_nums[roomnum_lower]
if key is None:
# At this point you know that the single string is not in any dict,
# so u start to check if any other string that u assigned to it is in dict
for optional_string in string_map.get(roomnum_lower, []):
opt_str_low = optional_string.lower()
key = azeri_nums.get(opt_str_low, None)
key = russian_nums.get(opt_str_low, None) if key is None else key
</code></pre>
| 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 code is this : </p>
<p>View : </p>
<pre><code>class RepresentativeView(ListView):
model = Representative
template_name= 'lea/elus.html'
context_object_name = 'represents'
def get_queryset(self, council):
return Representative.objects.filter(active=True).filter(council=council).order_by(order)
</code></pre>
<p>url : </p>
<pre><code>url(r'^elus/(?P<council>[A-B]+)$', views.RepresentativeView.as_view(), name='elus'),
</code></pre>
<p>Template :</p>
<pre><code>{% url 'elus' council='CFVU' %}
</code></pre>
<p>I've tried with <code>**kwargs</code> and other things. It work with <code>**kwargs</code> in another function with <code><pk></code> in url, and my query is based on the <code>id</code>. But here, with a string I can't find the solution.</p>
| 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, underscores, and hyphens:</p>
<pre><code>url(r'^elus/(?P<council>[\w-]+)$
</code></pre>
| 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 = np.empty(shape=(x,x, 4), dtype=np.uint8)
# B-G-R-A
blue = [255, 0, 0, 255]
green = [0, 255, 0, 255]
red = [0, 0, 255, 255]
orange = [0, 128, 255, 255]
black = [0, 0, 0, 255]
...
</code></pre>
<p>The colors above are added.
Then the image is returned. And when it is returned by the method, i would like to add a graphic to it.</p>
<p><strong>Example Below. Instead of the graphic, i would have an image</strong></p>
<p><a href="https://i.stack.imgur.com/6c6KQ.png" rel="nofollow"><img src="https://i.stack.imgur.com/6c6KQ.png" alt="Example"></a></p>
<p><strong>Extra Information</strong></p>
<p>The output is a numpy array with values ranging from 0 to 255.
Each pixel, value in the array, is formed by a 4-D array ( Blue-Green-Red-Alpha)</p>
<p>The legend should be added in the bottom right of the image.</p>
<p>The reason is because i have to do it, i guess.</p>
<p>Basically the current output is the numpy array, which i later use for other purposes.</p>
| 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/questions/26506204/replace-sub-part-of-matrix-by-another-small-matrix-in-numpy">this answer</a></p>
| 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 features.</p>
<p>NaNs were removed, new features created:</p>
<pre><code>square_feet = tf.contrib.layers.real_valued_column("square_feet")
guests_included = tf.contrib.layers.real_valued_column("guests_included")
security_deposit = tf.contrib.layers.real_valued_column("security_deposit")
cleaning_fee = tf.contrib.layers.real_valued_column("cleaning_fee")
extra_people = tf.contrib.layers.real_valued_column("extra_people")
</code></pre>
<p>and</p>
<pre><code>neighbourhood_group_cleansed = tf.contrib.layers.sparse_column_with_keys(column_name="neighbourhood_group_cleansed", keys=['Bronx', 'Queens', 'Staten Island', 'Brooklyn', 'Manhattan'])
host_response_time = tf.contrib.layers.sparse_column_with_keys(column_name="host_response_time", keys=['within an hour', 'within a few hours', 'within a day', 'a few days or more'])
</code></pre>
<p>-- I got more a lot more features, but I think this conveys the gist.</p>
<p>I copied those functions:</p>
<pre><code>def input_fn(df):
# Creates a dictionary mapping from each continuous feature column name (k) to
# the values of that column stored in a constant Tensor.
continuous_cols = {k: tf.constant(df[k].values) for k in CONTINUOUS_COLUMNS}
# Creates a dictionary mapping from each categorical feature column name (k)
# to the values of that column stored in a tf.SparseTensor.
categorical_cols = {k: tf.SparseTensor(indices=[[i, 0] for i in range(df[k].size)], values=df[k].values, shape=[df[k].size, 1]) for k in CATEGORICAL_COLUMNS}
# Merges the two dictionaries into one.
feature_cols = dict(continuous_cols.items() + categorical_cols.items())
# Converts the label column into a constant Tensor.
label = tf.constant(df[LABEL_COLUMN].values)
# Returns the feature columns and the label.
return feature_cols, label
def train_input_fn():
return input_fn(df_train)
def eval_input_fn():
return input_fn(df_test)
</code></pre>
<p>Which will be later used by </p>
<pre><code>model_dir = tempfile.mkdtemp()
m = tf.contrib.learn.LinearClassifier(feature_columns=FEATURE_COLUMNS, model_dir=model_dir)
m.fit(input_fn=train_input_fn, steps=200)
</code></pre>
<p>If I do a bit of debugging does the function <strong>input_fn()</strong> return a valid <strong>dict</strong> and the <strong>classification</strong>.
However, I get this error:</p>
<pre><code>/lib/python2.7/site-packages/tensorflow/contrib/layers/python/layers/feature_column_ops.pyc in check_feature_columns(feature_columns)
510 seen_keys = set()
511 for f in feature_columns:
--> 512 key = f.key
513 if key in seen_keys:
514 raise ValueError('Duplicate feature column key found for column: {}. '
AttributeError: 'str' object has no attribute 'key'
</code></pre>
<p>Debugging output of <strong>feature_cols</strong> (only an excerpt):</p>
<pre><code>'square_feet': <tf.Tensor 'Const_15:0' shape=(10000,) dtype=float64>,
'guests_included': <tf.Tensor 'Const_16:0' shape=(10000,) dtype=float64>,
'security_deposit': <tf.Tensor 'Const_17:0' shape=(10000,) dtype=float64>,
'cleaning_fee': <tf.Tensor 'Const_18:0' shape=(10000,) dtype=float64>,
..
</code></pre>
<p>and for <strong>label</strong></p>
<pre><code><tf.Tensor 'Const_27:0' shape=(10000,) dtype=int64>
</code></pre>
<p>and for <strong>df[LABEL_COLUMN].values</strong>:</p>
<pre><code>array([1, 1, 1, ..., 1, 1, 1])
</code></pre>
<p>Help, hints, tips much appreciated. Those are my first steps with Tensorflow and I don't how to proceed or to further troubleshoot the error.</p>
<p>Thank you!</p>
<p>--- Update ---</p>
<p>I tried to use</p>
<pre><code>import tensorflow.contrib.learn.python.learn as learn
</code></pre>
<p>and now on a DNN classifier, just on the continuous columns </p>
<pre><code>classifier = learn.DNNClassifier(hidden_units=[10, 20, 10], n_classes=2, feature_columns=CONTINUOUS_COLUMNS)
classifier.fit(df_train[CONTINUOUS_COLUMNS], df_train['classification'], steps=200, batch_size=32)
</code></pre>
<p>and get the same error</p>
<pre><code>/lib/python2.7/site-packages/tensorflow/contrib/layers/python/layers/feature_column_ops.pyc in check_feature_columns(feature_columns)
510 seen_keys = set()
511 for f in feature_columns:
--> 512 key = f.key
513 if key in seen_keys:
514 raise ValueError('Duplicate feature column key found for column: {}. '
AttributeError: 'str' object has no attribute 'key'
</code></pre>
| 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 list <code>wide_columns</code>:</p>
<pre><code>wide_columns=[square_feet, guests_included,...]
m = tf.contrib.learn.LinearClassifier(feature_columns=wide_columns, model_dir=model_dir)
m.fit(...)
</code></pre>
| 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.stripplot([cimin, cimax], color='r', marker='d') #overlay confidence intervals over boxplot
ax1.set_ylabel('Relative Frequency') #label only the top subplot
plt.xlabel('Difference')
plt.show()
</code></pre>
<p>Here is the output:</p>
<p><a href="https://i.stack.imgur.com/qWzAd.png" rel="nofollow"><img src="https://i.stack.imgur.com/qWzAd.png" alt="Distribution Plot"></a></p>
<p>I am rather stumped on how to make ax2 (the bottom figure) to become shorter relative to ax1 (the top figure). I was looking over the GridSpec (<a href="http://matplotlib.org/users/gridspec.html" rel="nofollow">http://matplotlib.org/users/gridspec.html</a>) documentation but I can't figure out how to apply it to seaborn objects.</p>
<p><strong>Question:</strong></p>
<ol>
<li>How do I make the bottom subplot shorter compared to the top
subplot? </li>
<li>Incidentally, how do I move the plot's title "Distrubition of Difference" to go above the top
subplot?</li>
</ol>
<p>Thank you for your time.</p>
| 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")
gridkw = dict(height_ratios=[5, 1])
fig, (ax1, ax2) = plt.subplots(2, 1, gridspec_kw=gridkw)
sns.distplot(tips.loc[:,'total_bill'], ax=ax1) #array, top subplot
sns.boxplot(tips.loc[:,'total_bill'], ax=ax2, width=.4) #bottom subplot
plt.show()
</code></pre>
<p><a href="https://i.stack.imgur.com/AQ1vz.png" rel="nofollow"><img src="https://i.stack.imgur.com/AQ1vz.png" alt="enter image description here"></a></p>
| 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 Center and the Landscape Ecology Branch of the U.S. Environmental Protection Agency are collaborating on a four-year research project to document the types, distributions, rates, drivers, and consequences of land cover change for the conterminous United States over the past 30 years. The project is using an ecoregion framework as a geographic stratifier."</p>
<p><em>Wants to separate every sentence on new line. I am parsing for "." replacing every "." as "\n" (new line character). It works fine for normal sentence, but when "The U.S. Geological..." such things came my script make 2 separate sentences which i don't want. Please suggest anything possible</em></p>
<p><strong>Expected Output:-- (3 sentences numbered serially )</strong></p>
<p>1) 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. </p>
<p>2) The U.S. Geological Survey's EROS Data Center and the Landscape Ecology Branch of the U.S. Environmental Protection Agency are collaborating on a four-year research project to document the types, distributions, rates, drivers, and consequences of land cover change for the conterminous United States over the past 30 years. </p>
<p>3) The project is using an ecoregion framework as a geographic stratifier.</p>
<p><strong>Currently Getting: (7 sentences)</strong></p>
<p>1) 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.</p>
<p>2) The U.</p>
<p>3) S. </p>
<p>4) Geological Survey's EROS Data Center and the Landscape Ecology Branch of the U.</p>
<p>5) S. </p>
<p>6) Environmental Protection Agency are collaborating on a four-year research project to document the types, distributions, rates, drivers, and consequences of land cover change for the conterminous United States over the past 30 years.</p>
<p>7) The project is using an ecoregion framework as a geographic stratifier.</p>
| -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 accurate estimates of landscape change. The U.S. Geological Survey's EROS Data Center and the Landscape Ecology Branch of the U.S. Environmental Protection Agency are collaborating on a four-year research project to document the types, distributions, rates, drivers, and consequences of land cover change for the conterminous United States over the past 30 years. The project is using an ecoregion framework as a geographic stratifier."
tokenizer = nltk.data.load('tokenizers/punkt/english.pickle')
for index, sentence in enumerate(tokenizer.tokenize(text), start=1):
print "{}) {}\n".format(index, sentence)
</code></pre>
<p>This would display the following output:</p>
<pre class="lang-none prettyprint-override"><code>1) 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.
2) The U.S. Geological Survey's EROS Data Center and the Landscape Ecology Branch of the U.S. Environmental Protection Agency are collaborating on a four-year research project to document the types, distributions, rates, drivers, and consequences of land cover change for the conterminous United States over the past 30 years.
3) The project is using an ecoregion framework as a geographic stratifier.
</code></pre>
| 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 environment variable for db_arn in my serverless handler function.</p>
<p>db_arn = "ec2-xx-xx-xx-xxx.eu-west-1.compute.amazonaws.com"</p>
<p>def getCustomer():
#connect using db_arn</p>
<p>Id like db_arn to be an environment variable (dev, test, prod for example), rather then the hard coded string.</p>
<p>How can this be done with dotenv and how would you organise the serverless service to enable this?</p>
<p>Help much welcome thanks!</p>
| 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.eu-west-1.compute.amazonaws.com"
plugins:
- serverless-plugin-write-env-vars
</code></pre>
<p>Notice the variables must be defined under <code>custom:</code> and <code>writeEnvVars:</code>.</p>
<p>The plugin will create a <code>.env</code> file during the code deployment to AWS Lambda. </p>
<p>In the code, using <a href="https://github.com/theskumar/python-dotenv" rel="nofollow">python-dotenv</a> you can read the environment variables by loading the <code>.env</code> file:</p>
<pre><code>import os.path
from dotenv import load_dotenv
dotenv_path = os.path.join(os.path.dirname(__file__), '.env')
load_dotenv(dotenv_path)
db_arn = os.environ.get('DB_ARN')
</code></pre>
<p>Just in case, if you need help with deploying and loading external dependencies, look at <a href="http://stackoverflow.com/a/39791686/1111215">http://stackoverflow.com/a/39791686/1111215</a></p>
| 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 Python, which is not efficient. </li>
</ol>
<p>Is there any way to "map" memory corresponding to C++ variables so that I may access the data from Python? I don't want to copy 6GB of data onto a hard drive. </p>
| 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>
<p>In Windows, you can create a DLL, and in Linux you can create a shared .so library.</p>
<p>Now this has the advantage that this will be independent of your Python version.</p>
<p><strong>Second path</strong>: I think it's less appropriate but you can get it to work, which is the <a href="https://docs.python.org/3.4/extending/extending.html" rel="nofollow">Python C Extension</a>. With this, you can call Python data containers (<code>PyObject</code>s) and fill them inside C.</p>
<p>However, the code you compile here will always need to be linked to Python libraries.</p>
<p><strong>Which one to use?</strong>: </p>
<ul>
<li>Use ctypes if you have some functions you want to call in C/C++, and then do the rest of the work in Python.</li>
<li>Use Python C Extension if you have some functions you want to call in Python, and you want to do the rest in C/C++.</li>
</ul>
<p>With both options, you can transfer huge blocks of memory between C++ and Python without necessarily involving any disk read/write operations.</p>
<p>Hope this helps.</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.</p>
<pre><code>MAX_WORKERS = 4
class ASYNCHandler(tornado.web.RequestHandler):
executor = ThreadPoolExecutor(max_workers=MAX_WORKERS)
counter = 0
def pow_task(self, x, y):
time.sleep(10)
return pow(x,y)
async def background_task(self):
future = ASYNCHandler.executor.submit(self.pow_task, 2, 3)
return future
@gen.coroutine
def get(self, *args, **kwargs):
future = yield from self.background_task()
response= dumps({"result":future.result()}, default=json_util.default)
print(response)
application = tornado.web.Application([
('/async', ASYNCHandler),
('/sync', SYNCHandler),
], db=db, debug=True)
application.listen(8888)
tornado.ioloop.IOLoop.current().start()
</code></pre>
| 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/en/latest/faq.html#why-isn-t-this-example-with-time-sleep-running-in-parallel</a></p>
| 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.</p>
<pre><code>MAX_WORKERS = 4
class ASYNCHandler(tornado.web.RequestHandler):
executor = ThreadPoolExecutor(max_workers=MAX_WORKERS)
counter = 0
def pow_task(self, x, y):
time.sleep(10)
return pow(x,y)
async def background_task(self):
future = ASYNCHandler.executor.submit(self.pow_task, 2, 3)
return future
@gen.coroutine
def get(self, *args, **kwargs):
future = yield from self.background_task()
response= dumps({"result":future.result()}, default=json_util.default)
print(response)
application = tornado.web.Application([
('/async', ASYNCHandler),
('/sync', SYNCHandler),
], db=db, debug=True)
application.listen(8888)
tornado.ioloop.IOLoop.current().start()
</code></pre>
| 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 that it's not going to be as simple as I originally anticipated. In any case, here is the code which does what you expect (I've trimmed your original example down a bit so that anyone can run it quickly):</p>
<pre><code>from concurrent.futures import ThreadPoolExecutor
from json import dumps
import time
from tornado.platform.asyncio import to_tornado_future
from tornado.ioloop import IOLoop
from tornado import gen, web
MAX_WORKERS = 4
class ASYNCHandler(web.RequestHandler):
executor = ThreadPoolExecutor(max_workers=MAX_WORKERS)
counter = 0
def pow_task(self, x, y):
time.sleep(5)
return pow(x,y)
async def background_task(self):
future = self.executor.submit(self.pow_task, 2, 3)
result = await to_tornado_future(future) # convert to tornado future
return result
@gen.coroutine
def get(self, *args, **kwargs):
result = yield from self.background_task()
response = dumps({"result": result})
self.write(response)
application = web.Application([
('/async', ASYNCHandler),
], debug=True)
application.listen(8888)
IOLoop.current().start()
</code></pre>
<p>The main differences are in the <code>background_tasks()</code> method. I convert the <code>asyncio</code> future to a <code>tornado</code> future, wait for the result, then return the result. The code you provided in the question, blocked for some reason when yielding from <code>background_task()</code> and you were unable to <code>await</code> the result because the future wasn't a tornado future.</p>
<p>On a slightly different note, this simple example can easily be implemented using a single thread/async designs and chances are your code can also be done without threads. Threads are easy to implement but equally easy to get wrong and can lead to very sticky situations. When attempting to write threaded code please remember <a href="http://bholley.net/images/posts/thistall.jpg" rel="nofollow">this photo</a> :)</p>
| 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 anyway to make it faster and stable?</p>
<p>Thanks.</p>
<pre><code>import itertools
a = [x for x in range(400,411)]
b = [x for x in range(400,411)]
c = [x for x in range(400,411)]
d = [x for x in range(400,411)]
e = [x for x in range(400,411)]
f = [x for x in range(400,411)]
fl = lambda x: x
it = filter(fl, itertools.product(a,b,c,d,e,f))
posslist = [x for x in it]
print(len(posslist))
</code></pre>
| 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(np.ix_(*arrays)):
arr[...,i] = a
return arr.reshape(-1, la)
</code></pre>
| 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 anyway to make it faster and stable?</p>
<p>Thanks.</p>
<pre><code>import itertools
a = [x for x in range(400,411)]
b = [x for x in range(400,411)]
c = [x for x in range(400,411)]
d = [x for x in range(400,411)]
e = [x for x in range(400,411)]
f = [x for x in range(400,411)]
fl = lambda x: x
it = filter(fl, itertools.product(a,b,c,d,e,f))
posslist = [x for x in it]
print(len(posslist))
</code></pre>
| 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 in 64-bit Python<sup>*</sup>.</p>
<p>So the total size of <code>posslist</code> is 6 * 8 * 11<sup>6</sup> = 81 GB!</p>
<p>Do you have enough RAM for that? Probably not, so the OS is going to start swapping RAM, which is extremely slow. Therefore, in addition to calculating 81 GB of data, thecomputer will have to constantly swap data from RAM to HDD and back, so it will do the job even slower.</p>
<hr>
<p><sup>* Note that while it is half that size in a 32-bit Python, a 32-bit Python cannot address enough memory at all </sup></p>
| 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 anyway to make it faster and stable?</p>
<p>Thanks.</p>
<pre><code>import itertools
a = [x for x in range(400,411)]
b = [x for x in range(400,411)]
c = [x for x in range(400,411)]
d = [x for x in range(400,411)]
e = [x for x in range(400,411)]
f = [x for x in range(400,411)]
fl = lambda x: x
it = filter(fl, itertools.product(a,b,c,d,e,f))
posslist = [x for x in it]
print(len(posslist))
</code></pre>
| 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 then the result would look like the following. You just have to unpack the tuple of tuple to a single tuple.</p>
<pre><code>[((1, 4), 7),
((1, 4), 8),
((1, 4), 9),
((1, 5), 7),
((1, 5), 8),
((1, 5), 9),
((1, 6), 7),
((1, 6), 8),
((1, 6), 9),
((2, 4), 7),
((2, 4), 8),
((2, 4), 9),
((2, 5), 7),
((2, 5), 8),
((2, 5), 9),
((2, 6), 7),
((2, 6), 8),
((2, 6), 9),
((3, 4), 7),
((3, 4), 8),
((3, 4), 9),
((3, 5), 7),
((3, 5), 8),
((3, 5), 9),
((3, 6), 7),
((3, 6), 8),
((3, 6), 9)]
</code></pre>
<p>I also think that this can be made parallelizable where you can do the product of the lists in parallel.</p>
<p>For lists L1, L2, L3, L4, do something like:</p>
<pre><code>th1_res = itertools.product(L1, L2)
th2_res = itertools.product(L3, L4)
thread_final = itertools.product(th1_res, th2_res)
</code></pre>
| 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 anyway to make it faster and stable?</p>
<p>Thanks.</p>
<pre><code>import itertools
a = [x for x in range(400,411)]
b = [x for x in range(400,411)]
c = [x for x in range(400,411)]
d = [x for x in range(400,411)]
e = [x for x in range(400,411)]
f = [x for x in range(400,411)]
fl = lambda x: x
it = filter(fl, itertools.product(a,b,c,d,e,f))
posslist = [x for x in it]
print(len(posslist))
</code></pre>
| 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 product with high values.
<br>
<br><a href="https://docs.python.org/2.7/library/itertools.html#itertools.product" rel="nofollow">Product generator for Python 2</a>
<br><a href="https://docs.python.org/3.5/library/itertools.html#itertools.product" rel="nofollow" title="Python 3 product generator">Product generator for Python 3</a></p>
| 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]:
print "yes"
print lis[x]
</code></pre>
<p>Here for example, the username could be "Jack". Even though multiple elements in lis have the value "Jack" (verified by printing all the values of the list through 'print lis[x]'), "yes" is never printed to show this.</p>
<p>What's going wrong?</p>
| 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]:
print "yes"
print lis[x]
</code></pre>
<p>Here for example, the username could be "Jack". Even though multiple elements in lis have the value "Jack" (verified by printing all the values of the list through 'print lis[x]'), "yes" is never printed to show this.</p>
<p>What's going wrong?</p>
| 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]:
print "yes"
print lis[x]
</code></pre>
<p>Here for example, the username could be "Jack". Even though multiple elements in lis have the value "Jack" (verified by printing all the values of the list through 'print lis[x]'), "yes" is never printed to show this.</p>
<p>What's going wrong?</p>
| 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', ' ', ' ', ' ', 'TLS', ' ', ' ', ' ', 'TLS', ' ', ' ', ' ', 'DWS', ' '],
['03', ' ', ' ', 'DWS', ' ', ' ', ' ', 'DLS', ' ', 'DLS', ' ', ' ', ' ', 'DWS', ' ', ' '],
['04', 'DLS', ' ', ' ', 'DWS', ' ', ' ', ' ', 'DLS', ' ', ' ', ' ', 'DWS', ' ', ' ', 'DLS'],
['05', ' ', ' ', ' ', ' ', 'DWS', ' ', ' ', ' ', ' ', ' ', 'DWS', ' ', ' ', ' ', ' '],
['06', ' ', 'TLS', ' ', ' ', ' ', 'TLS', ' ', ' ', ' ', 'TLS', ' ', ' ', ' ', 'TLS', ' '],
['07', ' ', ' ', 'DLS', ' ', ' ', ' ', 'DLS', ' ', 'DLS', ' ', ' ', ' ', 'DLS', ' ', ' '],
['08', 'TWS', ' ', ' ', 'DLS', ' ', ' ', ' ', 'B', 'O', 'G', ' ', 'DLS', ' ', ' ', 'TWS'],
['09', ' ', ' ', 'DLS', ' ', ' ', ' ', 'DLS', ' ', 'DLS', ' ', ' ', ' ', 'DLS', ' ', ' '],
['10', ' ', 'TLS', ' ', ' ', ' ', 'TLS', ' ', ' ', ' ', 'TLS', ' ', ' ', ' ', 'TLS', ' '],
['11', ' ', ' ', ' ', ' ', 'DWS', ' ', ' ', ' ', ' ', ' ', 'DWS', ' ', ' ', ' ', ' '],
['12', 'DLS', ' ', ' ', 'DWS', ' ', ' ', ' ', 'DLS', ' ', ' ', ' ', 'DWS', ' ', ' ', 'DLS'],
['13', ' ', ' ', 'DWS', ' ', ' ', ' ', 'DLS', ' ', 'DLS', ' ', ' ', ' ', 'DWS', ' ', ' '],
['14', ' ', 'DWS', ' ', ' ', ' ', 'TLS', ' ', ' ', ' ', 'TLS', ' ', ' ', ' ', 'DWS', ' '],
['15', 'TWS', ' ', ' ', 'DLS', ' ', ' ', ' ', 'TWS', ' ', ' ', ' ', 'DLS', ' ', ' ', 'TWS']]
</code></pre>
<p>My goal is to find the distance to the nearest letter from any letter. For example, if I called the function on B, it would return</p>
<pre><code>{"up" : 7, "down" : 7, "left" : 7, "right" : 0}
</code></pre>
<p>I have experimented with the built-in <code>next</code> function, but I guess my question is, is there an easy way to get the column of a two-dimensional list?</p>
<p>I also have a list of things that should be considered as empty:</p>
<pre><code>emptyList = "TWS", "DWS", "TLS", "DLS"
</code></pre>
<p>Please help. Thank you so much!</p>
| 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] for row in board]
row = board[row_num]
return {
'right': next((i for i, c in enumerate(row[col_num+1:]) if c in letters), 15-col_num),
'left': next((i for i, c in enumerate(row[col_num-1:0:-1]) if c in letters), col_num-1),
'down': next((i for i, c in enumerate(col[row_num+1:]) if c in letters), 15-row_num),
'up': next((i for i, c in enumerate(col[row_num-1:0:-1]) if c in letters), row_num-1)
}
print (distances(8, 'H'))
</code></pre>
<p>The arguments to the function should be the row number (<code>8</code>) and column number (<code>8</code>) or the corresponding letter <code>H</code>.</p>
<p>To check that a square is empty the function checks whether the contents are not a single letter (A-Z).</p>
<p>See it run on <a href="https://repl.it/Dx2V" rel="nofollow">repl.it</a></p>
| 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-python-example-cursor-select.html" rel="nofollow">here</a> and <a href="http://stackoverflow.com/a/775399/1376624">also here</a> </p>
<p>Given those examples, it seems like <code>cursor.execute("SELECT * FROM automatedReports WHERE pythonFunctionName = %s", (function_name))</code> in the below should work. </p>
<p>However, when I write this line in pyCharm, I get this error:</p>
<p><a href="https://i.stack.imgur.com/RUAF7.png" rel="nofollow"><img src="https://i.stack.imgur.com/RUAF7.png" alt="enter code here"></a></p>
<p>The inspection says:</p>
<p><a href="https://i.stack.imgur.com/kLgwL.png" rel="nofollow"><img src="https://i.stack.imgur.com/kLgwL.png" alt="enter image description here"></a></p>
<p>If I run the code, I get this error:</p>
<blockquote>
<p>You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%s' at line 1</p>
</blockquote>
<p>Here is the full code:</p>
<pre><code>class DatabaseManager():
def get_report_settings_for_function_named(self, function_name):
"""
Get the settings for a given report from the database based on the name of the function that was called
to process the report
This is how we get the, email subject and email addresses to send the report to
:param function_name: The name of the function that was called to process the report
:type function_name: str.
:returns: array -- the settings row from the database.
"""
cnx = mysql.connector.connect(**config)
cursor = cnx.cursor(dictionary=True)
cursor.execute("SELECT * FROM automatedReports WHERE pythonFunctionName = %s", (function_name))
row = cursor.fetchone()
cursor.close()
cnx.close()
print cursor.statement
return row
print DatabaseManager().get_report_settings_for_function_named('process_elation_credit_report')
</code></pre>
<h3>What am I doing wrong here? Is this an old syntax? I wouldnt think so...</h3>
<p>Note, if I type the value into the query string it all works fine, it's just wont let me use the parameter.</p>
| 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 automatedReports WHERE pythonFunctionName = %s", (function_name,))
</code></pre>
<p>Otherwise <code>mysql.connector</code> doesn't escape anything and leaves the literal <code>%s</code> in the query.</p>
| 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 variable. Assume that I want the new random variable to be something like <code>max(2, x1) + x2</code>. How can I define this dynamically?</p>
| 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 offered at <a class='doc-link' href="http://stackoverflow.com/documentation/scipy/6873/rv-continuous-for-distribution-with-parameters#t=201610161945055670237">SO doc</a>. (Incidentally, someone doesn't like it for some reason. If you think of improvements, please comment.)</p>
<p>Obviously the 'fun' begins here. Usually you would attempt to define the cdf. For any given value of the random variable this is the probability that an expression such as the one you gave is not more than the given value. Thus determining the cdf reduces to solving a (an infinite) collection of inequalities in two variables. Of course there is often a strong pattern that greatly reduces the complexity and difficulty of performing this task.</p>
| 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, when I run:</p>
<pre><code>cx_Freeze-4.3.3$ ./cxfreeze hello.py
Traceback (most recent call last):
File "./cxfreeze", line 5, in <module>
main()
File "cx_Freeze-4.3.3/cx_Freeze/main.py", line 187, in main
silent = options.silent)
File "cx_Freeze-4.3.3/cx_Freeze/freezer.py", line 108, in __init__
self._VerifyConfiguration()
File "cx_Freeze-4.3.3/cx_Freeze/freezer.py", line 488, in _VerifyConfiguration
self._GetBaseFileName()
File "cx_Freeze-4.3.3/cx_Freeze/freezer.py", line 211, in _GetBaseFileName
raise ConfigError("no base named %s", name)
cx_Freeze.freezer.ConfigError: no base named Console
</code></pre>
| 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']]
</code></pre>
<p>I would like to find the <strong>combinations of palindromes</strong> across the lists in aList.
For eg, the possible palindromes for this would be 5 - aba, aba, aba, aba, aabaa</p>
<p>This could be achieved by <em>brute force algorithm</em> using the below code:</p>
<pre><code>d = []
def isPalindrome(x):
if x == x[::-1]: return True
else: return False
for I in itertools.product(*aList):
a = (''.join(I))
if isPalindrome(a):
if a not in d:
d.append(a)
count += 1
</code></pre>
<p>But this approach is resulting in a timeout when the number of strings and the length of the string are bigger.</p>
<p>Is there a better approach to the problem ?</p>
| 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.</p>
<pre><code>import itertools
aList = [['a', 'a', 'aa'], ['b'], ['a', 'a', 'aa']]
d = []
seen = set()
for I in itertools.product(*aList):
if I not in seen:
seen.add(I)
a = ''.join(I)
if a == a[::-1]:
d.append(a)
print('d: {}'.format(d))
</code></pre>
| 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']]
</code></pre>
<p>I would like to find the <strong>combinations of palindromes</strong> across the lists in aList.
For eg, the possible palindromes for this would be 5 - aba, aba, aba, aba, aabaa</p>
<p>This could be achieved by <em>brute force algorithm</em> using the below code:</p>
<pre><code>d = []
def isPalindrome(x):
if x == x[::-1]: return True
else: return False
for I in itertools.product(*aList):
a = (''.join(I))
if isPalindrome(a):
if a not in d:
d.append(a)
count += 1
</code></pre>
<p>But this approach is resulting in a timeout when the number of strings and the length of the string are bigger.</p>
<p>Is there a better approach to the problem ?</p>
| 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 your space is this</p>
<pre><code>[["a","b","c"], ... , ["b","c","d"]]
</code></pre>
<p>We can see that if you pick "a" as first pick, there is no "a" in last group and this exclude all possible solutions that would be tried other way.</p>
| 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']]
</code></pre>
<p>I would like to find the <strong>combinations of palindromes</strong> across the lists in aList.
For eg, the possible palindromes for this would be 5 - aba, aba, aba, aba, aabaa</p>
<p>This could be achieved by <em>brute force algorithm</em> using the below code:</p>
<pre><code>d = []
def isPalindrome(x):
if x == x[::-1]: return True
else: return False
for I in itertools.product(*aList):
a = (''.join(I))
if isPalindrome(a):
if a not in d:
d.append(a)
count += 1
</code></pre>
<p>But this approach is resulting in a timeout when the number of strings and the length of the string are bigger.</p>
<p>Is there a better approach to the problem ?</p>
| 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 between. </p>
<p>This way you probably cancel out a lot of possibilities, and this method can be repeated recursively, once you have decided that a pair is still in the running. You would then save the common part of the two words (when the second word is reversed of course), and keep the remaining letters separate for use in the recursive part. </p>
<p>Depending on which of the two words was longer, you would compare the remaining letters with words from the array that is next from the left or from the right.</p>
<p>This should bring a lot of early pruning in the search tree. You would thus not perform the full Cartesian product of combinations.</p>
<p>I have also written the function to get all substrings from a given word, which you probably already had:</p>
<pre><code>def allsubstr(str):
return [str[i:j+1] for i in range(len(str)) for j in range(i, len(str))]
def getpalindromes_trincot(aList):
def collectLeft(common, needle, i, j):
if i > j:
return [common + needle + common[::-1]] if needle == needle[::-1] else []
results = []
for seq in aRevList[j]:
if seq.startswith(needle):
results += collectRight(common+needle, seq[len(needle):], i, j-1)
elif needle.startswith(seq):
results += collectLeft(common+seq, needle[len(seq):], i, j-1)
return results
def collectRight(common, needle, i, j):
if i > j:
return [common + needle + common[::-1]] if needle == needle[::-1] else []
results = []
for seq in aList[i]:
if seq.startswith(needle):
results += collectLeft(common+needle, seq[len(needle):], i+1, j)
elif needle.startswith(seq):
results += collectRight(common+seq, needle[len(seq):], i+1, j)
return results
aRevList = [[seq[::-1] for seq in seqs] for seqs in aList]
return collectRight('', '', 0, len(aList)-1)
# sample input and call:
input = ['already', 'days', 'every', 'year', 'later'];
aList = [allsubstr(word) for word in input]
result = getpalindromes_trincot(aList)
</code></pre>
<p>I did a timing comparison with the solution that martineau posted. For the sample data I have used, this solution is about 100 times faster:</p>
<p>See it run on <a href="https://repl.it/Dx2V/1" rel="nofollow">repl.it</a></p>
<h3>Another Optimisation</h3>
<p>Some gain could also be found in not repeating the search when the first array has several entries with the same string, like the <code>'a'</code> in your example data. The results that include the second <code>'a'</code> will obviously be the same as for the first. I did not code this optimisation, but it might be an idea to improve the performance even more.</p>
| 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 should not be problem, it should repeat that question 10 times.</p>
<p>Here's piece of my code (It's in class):</p>
<pre><code> self.label = tk.Label(self, text="This is page 1")
self.label.pack(side="top", fill="x", pady=10)
self.label1 = tk.Label(self, text='')
self.label1.pack()
self.label2 = tk.Label(self, text='')
self.label2.pack()
self.entry1 = tk.Entry(self)
self.entry1.pack()
self.label3 = tk.Label(self, text='')
self.label3.pack()
self.entry2 = tk.Entry(self)
self.entry2.pack()
my_dict = {
"Base-2 number system": "binary",
}
score = 0
for i in range(10):
question = (random.choice(list(my_dict.keys())))
answer = my_dict[question]
self.label1.config(text=("Question " + str(i + 1)))
self.label2.config(text=(question + "?"))
guess = self.entry1.get()
if guess.lower() == answer.lower():
score += 1
else:
score += 0
self.label3.config(text=("Your final score was " + str(score)))
</code></pre>
| 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 code below doesn't do everything you want, but it does run. :) It displays a question, waits for the user to type their answer into the <code>self.entry1</code> widget, and when they hit the <code>Enter</code> key in that widget it calls the <code>.get_answer</code> method which processes their answer and then calls the <code>.ask</code> method to ask a new question. After 10 questions the program exits.</p>
<pre><code>import tkinter as tk
import random
class Quiz(tk.Frame):
def __init__(self, root):
super().__init__(root)
self.root = root
self.pack()
self.label = tk.Label(self, text="This is page 1")
self.label.pack(side="top", fill="x", pady=10)
self.label1 = tk.Label(self, text='')
self.label1.pack()
self.label2 = tk.Label(self, text='')
self.label2.pack()
self.entry1 = tk.Entry(self)
self.entry1.bind("<Return>", self.get_answer)
self.entry1.pack()
self.label3 = tk.Label(self, text='')
self.label3.pack()
self.entry2 = tk.Entry(self)
self.entry2.pack()
self.start_quiz()
root.mainloop()
def start_quiz(self):
self.qdict = {
"Base-2 number system": "binary",
"Base-8 number system": "octal",
"Base-16 number system": "hexadecimal",
}
self.qkeys = list(self.qdict.keys())
self.score = 0
self.count = 1
self.ask()
def ask(self):
self.question = random.choice(self.qkeys)
self.label1.config(text="Question {}".format(self.count))
self.label2.config(text=self.question + "?")
def get_answer(self, event):
widget = event.widget
guess = widget.get()
answer = self.qdict[self.question]
if guess.lower() == answer.lower():
self.score += 1
self.label3.config(text="Score: {}".format(self.score))
self.count += 1
if self.count <= 10:
self.ask()
else:
self.root.destroy()
Quiz(tk.Tk())
</code></pre>
| 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 need to find it quickly.</p>
| 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 instead of a constant value.</p>
<p>After this, the line <code>while q:</code> is a use (or abuse) of Python's type conversion system. While loops require a boolean condition to know whether they should repeat, so your code is equivalent to <code>while bool(q):</code>. To understand how this works, let's examine the possible cases:</p>
<pre><code>bool([1]) == True # This applies for any non-empty list
bool([]) == False # This applies to any empty list
</code></pre>
<p>Therefore, the meaning of <code>while q:</code> is actually 'while <code>q</code> is non-empty'.</p>
| 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 numpy array of dimension <code>dim</code>.
Is there a way to do it without being dimension specific?
Without having to write ugly code like </p>
<pre><code> if dim==2:
a,b=grid_shape
for i in range(a):
for j in range(b):
A[i,j] = ...things...
if dim==3:
a,b,c=grid_shape
for i in range(a):
for j in range(b):
for k in range(c):
A[i,j,k] = ...things...
</code></pre>
| 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 i in range(a):
for j in range(b):
index = i,j
do_something_with(index)
</code></pre>
<p>can be reduced to</p>
<pre><code>for index in itertools.product(range(a),range(b)):
do_something_with(index)
</code></pre>
<p>This works for any number of arguments to <code>itertools.product()</code>, so you can effectively create nested loops of arbitrary depth.</p>
<p>The other trick is to convert your grid shape into the arguments for itertools.product:</p>
<pre><code>(range(x) for x in grid_shape)
</code></pre>
<p>is equivalent to</p>
<pre><code>(range(grid_shape[0]),range(grid_shape[1]),...)
</code></pre>
<p>That is, it is a tuple of ranges for each grid_shape dimension. Using * then expands this into the arguments.</p>
<pre><code>itertools.product(*(range(x1),range(x2),...))
</code></pre>
<p>is equivalent to</p>
<pre><code>itertools.product(range(x1),range(x2),...)
</code></pre>
<p>Also, since <code>A[i,j,k]</code> is equivalent to <code>A[(i,j,k)]</code>, we can just use <code>A[index]</code> directly.</p>
<p>As <a href="http://stackoverflow.com/users/487339/dsm">DSM</a> points out, since you are using numpy, you can reduce</p>
<pre><code>itertools.product(*(for range(x) for x in grid_shape))
</code></pre>
<p>to</p>
<pre><code>numpy.ndindex(grid_shape)
</code></pre>
<p>So the final loop becomes</p>
<pre><code>for index in numpy.ndindex(grid_shape):
A[index] = ...things...
</code></pre>
| 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 numpy array of dimension <code>dim</code>.
Is there a way to do it without being dimension specific?
Without having to write ugly code like </p>
<pre><code> if dim==2:
a,b=grid_shape
for i in range(a):
for j in range(b):
A[i,j] = ...things...
if dim==3:
a,b,c=grid_shape
for i in range(a):
for j in range(b):
for k in range(c):
A[i,j,k] = ...things...
</code></pre>
| 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 can loop through b. So it would look something like</p>
<pre><code>a,*b=grid_shape
for i in a:
for j in range(i):
for k in b:
for l in range(k):
A[j, l] = ...things...
</code></pre>
| 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_allfeatures, y_vol)
ranking_vola = rfe_vola.ranking_
print("ranking: ",ranking_vola)
print("support: ",rfe_vola.support_)
</code></pre>
<p>what I would like to have, is a deeper information, thus the scores or the features evaluation at each iteration of RFE. I've noticed that there are some hidden function like _fit, and I'm thinking in trying to force the step_score parameter to be different from none...
The point is that I'm not able to reach what I want.. (I'm new to python...) I would like to get the print of the scores at each iteration. Is there anyone who have experience with such a task? What should be a proper value of the step_score parameter? ( I've tried with a boolean but it doesn't work )</p>
<p>Thanks for any advice!!!</p>
| 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_vol, r2_scorer)
ranking_vola = rfe_vola.ranking_
</code></pre>
| 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.satp.org/satporgtp/countries/pakistan/database/bombblast.htm'
soup = make_soup(url)
table = soup.findAll('table', attrs={'class':'pagraph1'})
table = table[0]
trows = table.findAll('tr')
bbdata_ = []
bbdata = []
for trow in trows:
bbdata_ = trow.findAll('td')
bbdata = [ele.text.strip() for ele in bbdata_]
print(bbdata)
</code></pre>
<p>However, I can only extract the last row in the table, i.e.</p>
<pre><code>['Total*', '369', '1032+']
</code></pre>
<p>All of the data is included in the <code>trows</code>, so I must be forming my loop incorrectly, but I am not sure how.</p>
| 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 with the final value.</p>
| 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.assertEquals(1482951600, parse_date('2016-12-28 14:00', 'US/Eastern')
</code></pre>
<p>returns a different value depending on the timezone of the machine it is running on?</p>
<p>In my understanding, the parser returns a datetime without a timezone, it then assign a tz, without changing anything else and finally it is converted into a timestamp. My local tz should not be used anywhere.</p>
| 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.</p>
<p>That said, this is not what is happening in this case. Even if <code>parser</code> were attaching a time zone, <code>datetime.replace</code> does a wholesale replacement of the time zone, not a conversion. I do not think there is enough information in your question to fully diagnose this issue, but if <code>timezone()</code> is <code>pytz.timezone()</code>, at least one of your issues is that <code>pytz</code> time zones can't be attached to <code>datetime</code> objects with <code>replace</code>. You would need to instead use <code>datetime_obj = pytz.timezone(tz_code).localize(datetime_obj)</code>.</p>
<p>Note that the <code>localize</code> method assumes that you have a timezone-naive object, so it will throw an error if <code>datetutil</code>'s parser returns a timezone-aware <code>datetime</code>, so you should pass <code>ignoretz=True</code> to the parser to prevent this.</p>
<p>That said, even once you do this, the real issue is in your use of <code>time.mktime</code>. See <a href="https://stackoverflow.com/questions/38963653/dateutil-parse-bug-in-python-returns-the-wrong-value/38964103#38964103">this answer</a>, which is exactly the same problem. To summarize that answer, the best thing to do is to use <code>calendar.timegm</code> instead of <code>mktime</code>, and convert to UTC before calling it. Incorporating my suggestions, here is an updated version of your code:</p>
<pre><code>import calendar
from dateutil.tz import tzutc
def parse_date(datetime_string, tz_code):
tz = timezone(tz_code)
datetime_obj = parser.parse(datetime_string, ignoretz=True)
datetime_obj_localized = tz.localize(datetime_obj)
datetime_obj_utc = datetime_obj_localized.astimezone(tzutc())
return calendar.timegm(datetime_obj_utc.timetuple())
</code></pre>
| 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 be populated in realtime, constantly by the Django Server i.e it should preferably start doing it as soon as the Django Server is launched. What will be a good way to go about it ?</p>
<p>The calls look as followin:</p>
<pre><code>streamer = tweepy.Stream(twitter_api.auth, listener=stream_listener)
streamer.filter(locations=[-180, -90, 180, 90], languages=['en'], async=True)
</code></pre>
| -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 a straight forward solution but with some effort it is the best solution.</p>
| 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 be populated in realtime, constantly by the Django Server i.e it should preferably start doing it as soon as the Django Server is launched. What will be a good way to go about it ?</p>
<p>The calls look as followin:</p>
<pre><code>streamer = tweepy.Stream(twitter_api.auth, listener=stream_listener)
streamer.filter(locations=[-180, -90, 180, 90], languages=['en'], async=True)
</code></pre>
| -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+(\.\d+)?$", x) else x for x in item]
</code></pre>
<p>It rounds all the list members to the nearest upper float which causes <code>3468.678822</code> to be rounded to <code>3468.68</code>, but I want to round them to the nearest lower float, so <code>3468.678822</code> should be rounded to <code>3468.67</code>. There is an exception for <code>0</code>; I want numbers equal to <code>0</code> to remain <code>0</code>.</p>
<p>I tried using above command without <code>round</code> and even <code>float</code> function and the result was the same. I also tried: </p>
<pre><code>[x[:x.index('.')] if re.match("^\d+(\.\d+)?$", x) else x for x in item]
</code></pre>
<p>Which gave me <code>Substring not found</code> error.</p>
| 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+(\.\d+)?$", x) else x for x in item]
</code></pre>
<p>It rounds all the list members to the nearest upper float which causes <code>3468.678822</code> to be rounded to <code>3468.68</code>, but I want to round them to the nearest lower float, so <code>3468.678822</code> should be rounded to <code>3468.67</code>. There is an exception for <code>0</code>; I want numbers equal to <code>0</code> to remain <code>0</code>.</p>
<p>I tried using above command without <code>round</code> and even <code>float</code> function and the result was the same. I also tried: </p>
<pre><code>[x[:x.index('.')] if re.match("^\d+(\.\d+)?$", x) else x for x in item]
</code></pre>
<p>Which gave me <code>Substring not found</code> error.</p>
| 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 round up to (see notes)
"""
# example: 5.146, place is 1
# move the decimal point to the right or left, depending on
# the sign of the place
num = num * math.pow(10, place) # 51.46
# round it up normally
num = math.ceil(num) #52
# put the decimal place back where it was
num = num * math.pow(10, -place) #5.2
# return the result rounded, to avoid a weird glitch where
# a bunch of trailing numbers are added to the result (see notes).
return round(num, place)
"""
Notes:
Here is how the places work:
0 - ones place
positive ints - to the right of the decimal point
negative ints - to the left of the ones place
This function works perfectly fine on Python 3.4 and 2.7, last I checked.
If you want a version of this that rounds down, just replace the calls
to math.ceil with calls to math.floor.
Now, the glitch with the trailing numbers. Just have flexCeil return
num instead of round(num, place). Then test it with flexCeil(12345.12345, 2).
You get 12345.130000000001.
Interestingly enough, this glitch doesnt happen when you change the
function to round down, instead.
"""
</code></pre>
| 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_41 23_22
index
312 2 1 0
313 1 0 1
... ...
</code></pre>
<p>How implement it with python and pandas?</p>
| 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]:
code 11 23
type 21 41 22
index
312 2 1 0
313 1 0 1
In [138]: dff.columns = ['%s_%s' % c for c in dff.columns]
In [139]: dff
Out[139]:
11_21 11_41 23_22
index
312 2 1 0
313 1 0 1
</code></pre>
<p><em>Alternatively, less elegantly,</em> create another column and use crosstab.</p>
<pre><code>In [140]: df['ct'] = df.code.astype(str) + '_' + df.type.astype(str)
In [141]: df
Out[141]:
index code type ct
0 312 11 21 11_21
1 312 11 41 11_41
2 312 11 21 11_21
3 313 23 22 23_22
4 313 11 21 11_21
In [142]: pd.crosstab(df['index'], df['ct'])
Out[142]:
ct 11_21 11_41 23_22
index
312 2 1 0
313 1 0 1
</code></pre>
| 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
if result == 0:
#im not getting to this step???
result = m
if result % i != 0:
result = n // i
else:
return(result)
</code></pre>
| -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 happen for valid input
</code></pre>
<p>You may also want to consider the behaviour of your function if invalid input is given (e.g. a string, a negative number etc.).</p>
| 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 output to look like <code>Harambe : Gorilla, Restaurant : Place, etc</code></p>
<p>So what do I do? I haven't found a post meeting what I want. Thanks in advance.</p>
| 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>. </p>
| 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 output to look like <code>Harambe : Gorilla, Restaurant : Place, etc</code></p>
<p>So what do I do? I haven't found a post meeting what I want. Thanks in advance.</p>
| 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 output to look like <code>Harambe : Gorilla, Restaurant : Place, etc</code></p>
<p>So what do I do? I haven't found a post meeting what I want. Thanks in advance.</p>
| 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():
print("{}: {}".format(key, value))
</code></pre>
| 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 de45+ Pas hfa, underak (333)"
split_str = re.split(' ' , a) #Splits just at spaces
split_str = re.split('[ .:]', a) #Splits at spaces, periods, and colons
split_str = re.split('(?<!,)[ ]' , a) #Splits at spaces, excluding commas
</code></pre>
<p>As you might have guessd, if you want to exclude a character, simply put it in between the <code>(?<!</code> and <code>)</code></p>
| 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.RequestHandler):
def get(self):
tables = "<table> <tr> <th>Company</th> <th>Contact</th> <th>Country</th> </tr> <tr> \
<td>Alfreds Futterkiste</td> <td>Maria Anders</td> <td>Germany</td> </tr> <tr> \
<td>Centro comercial Moctezuma</td> <td>Francisco Chang</td> <td>Mexico</td> </tr> <tr> \
<td>Ernst Handel</td> <td>Roland Mendel</td> <td>Austria</td> </tr> <tr> <td>Island Trading</td> \
<td>Helen Bennett</td> <td>UK</td> </tr> <tr> <td>Laughing Bacchus Winecellars</td> \
<td>Yoshi Tannamuri</td> <td>Canada</td> </tr> <tr> <td>Magazzini Alimentari Riuniti</td> \
<td>Giovanni Rovelli</td> <td>Italy</td> </tr> </table>"
self.render('index.html',tableinfo = tables)
if __name__ == '__main__':
tornado.options.parse_command_line()
app = tornado.web.Application(
handlers=[(r'/', IndexHandler)],
template_path=os.path.join(os.path.dirname(__file__), "templates"))
http_server = tornado.httpserver.HTTPServer(app)
http_server.listen(options.port)
tornado.ioloop.IOLoop.instance().start()
</code></pre>
<p>I plan to print this table in the index.html file </p>
<pre><code><!DOCTYPE html>
<html>
<head><title>Help For table print</title></head>
<body>
<p> {{tableinfo}} </p>
</body>
</html>
</code></pre>
<p>unfortunately it is only prints the string into the html code and does not use the code to create the table.
Could you please help me to show the table by exchanging variables.
Many thanks</p>
| 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:February 2006
4 5 5 USA:2006
</code></pre>
<p>I want output like below:</p>
<pre><code>In [61]: df.head()
Out[61]:
id movie_id country Date Month Year
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 None February 2006
4 5 5 USA None None 2006
</code></pre>
<p>The data is stored in dataframe and it must be overwrite into the dataframe.</p>
| 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 href="https://i.stack.imgur.com/34WnK.png" rel="nofollow"><img src="https://i.stack.imgur.com/34WnK.png" alt="enter image description here"></a></p>
<p><em>Update</em>:</p>
<p>To handle optional missing dates and months, you could try <code>extract</code> with regular expression:</p>
<pre><code>(df[["country","Date","Month","Year"]] =
df['info'].str.extract('^([A-Za-z]+):(\d{1,2})? ?([A-Za-z]+)? ?(\d{4})$'))
</code></pre>
<ul>
<li><code>^([A-Za-z]+):(\d{1,2})? ?([A-Za-z]+)? ?(\d{4})$'</code> contains four capture groups corresponding to <code>country, Date, Month, Year</code> respectively;</li>
<li><code>^</code> and <code>$</code> denote the start and end of the string;</li>
<li><code>([A-Za-z]+)</code> captures the country which is before <code>:</code> and consists of letters; </li>
<li><code>(\d{1,2})</code> captures Date which consists of one or two digits but optional(with <code>?</code> after the group), i.e, could be missing;</li>
<li><code>([A-Za-z]+)</code> captures Month which consists of letters and it's marked as optional with <code>?</code>;</li>
<li><code>(\d{4})</code> captures the year which consists of four digits;</li>
</ul>
<p><a href="https://i.stack.imgur.com/SQGUN.png" rel="nofollow"><img src="https://i.stack.imgur.com/SQGUN.png" alt="enter image description here"></a></p>
| 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:February 2006
4 5 5 USA:2006
</code></pre>
<p>I want output like below:</p>
<pre><code>In [61]: df.head()
Out[61]:
id movie_id country Date Month Year
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 None February 2006
4 5 5 USA None None 2006
</code></pre>
<p>The data is stored in dataframe and it must be overwrite into the dataframe.</p>
| 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 info country date month year
0 1 1 Italy:1 January 1994 Italy 1 January 1994
1 2 2 USA:22 January 2006 USA 22 January 2006
2 3 3 USA:12 February 2006 USA 12 February 2006
3 4 4 USA:19 February 2006 USA 19 February 2006
4 5 5 USA:22 January 2006 USA 22 January 2006
</code></pre>
| 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 a list with around 5000 thousand IDs. The straighforward way would be to filter with <code>isin</code> but that has really bad performance. How can this filter be done?</p>
| 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"])
</code></pre>
<p>and <code>join</code>:</p>
<pre><code>df.join(ids_df, ["ID"], "inner")
</code></pre>
| 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 how their weight develops through the years. So I tried this: </p>
<pre><code>df.groupby("euro").plot(x="year", y="MKM")
</code></pre>
<p>However, I get multiple plots and that is not what I want. I want all those plots in one figure. </p>
| 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://i.stack.imgur.com/vKx8d.png" rel="nofollow"><img src="https://i.stack.imgur.com/vKx8d.png" alt="enter image description here"></a></p>
| 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 getting No Attribute error. Is there any way to access a variable inside main() method in first.py through second.py?</p>
| 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>second.py</p>
<pre><code>import first
def main():
b = first.main()
</code></pre>
<p>Other option is to use a global variable in the first file where you will store the value and later reference it.</p>
| 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 getting No Attribute error. Is there any way to access a variable inside main() method in first.py through second.py?</p>
| 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>
<p>In your example <code>first_variable</code> only <em>exists</em> within <code>first.main()</code>'s local scope - while it is executing. It isn't accessible to anything outside of that scope.</p>
<hr>
<p>You need to get <code>first_variable</code> into <code>first</code>'s global scope - then in <code>second</code> you can use it with <code>first.first_variable</code>.</p>
<p>One way would be to return something from <code>first.main()</code> and assign it to <code>first_variable</code>.</p>
<pre><code>def main():
return 2
first_variable = main()
</code></pre>
<p>Then in <code>second</code> you can use it:</p>
<pre><code>import first
times_3 = first.first_variable * 3
</code></pre>
| 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=True)
excercises = models.CharField(max_length=200, choices=excercises_choices)
sets = models.IntegerField(null=True, blank=True)
reps = models.IntegerField(null=True, blank=True)
weight = models.FloatField()
unit = models.CharField(max_length=3, choices=unit_choices)
created_date = models.ForeignKey('Dates')
amrap_set = models.BooleanField(default=False)
amrap_rep = models.IntegerField(null=True, blank=True)
def __str__(self):
return self.excercises
class Dates(models.Model):
created_date = models.DateField(unique=True)
def __str__(self):
return str(self.created_date)
</code></pre>
<p>Let's say I have few lifts at different dates for admin and few lifts at different for xx user.
I want multiple lifts matching one date that's why I've made foreign key. (eg. 3 lifts to 2016-10-10 and 2 lifts to 2016-10-11).</p>
<p>Here is a view for showing it:</p>
<pre><code> @login_required
def entries(request):
date = Dates.objects.all().order_by('-created_date')
lifts_by_user = Lifts.objects.filter(user=request.user)
return render(request, 'lift/entries.html', {'date': date,
'lifts_by_user': lifts_by_user})
</code></pre>
<p>And template: </p>
<pre><code>{% extends 'lift/base.html' %}
{% block content %}
{{ user }}
{% if user.is_authenticated %}
{% for date in date %}
<p><strong><a href="{% url 'lift_date' pk=date.pk %}">{{ date }}</a></strong>
{% for i in date.lifts_set.all %}
{{ i }}
{% endfor %}
<a href="{% url 'new_lifts' %}">add new lift</a></p>
{% endfor %}
{% endif %}
<p>
<a href="{% url 'entries_delete' %}">Delete lifts or dates </a>
</p>
{% endblock %}
</code></pre>
<p>The problem is that I dont know how to separate it by dates AND by user.
<a href="https://i.stack.imgur.com/0gljf.png" rel="nofollow">This is how it looks like</a> How do i keep this pattern date - lifts_to_that_date but for separate users? I dont want to see admin's entries while I am on test user</p>
| 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.filter(user=request.user)
.order_by('-created_date__created_date'))
return render(
request,
'lift/entries.html',
{'lifts_by_user': lifts_by_user}
)
</code></pre>
<p>And replace the <code>for date in dates</code> loop in your template with something like:</p>
<pre><code>{% regroup lifts_by_user by created_date.created_date as lifts %}
<ul>
{% for day in lifts %}
<li>Date: {{ day.grouper }}
<ul>
{% for lift in day.list %}
<li>{{ lift }}</li>
{% endfor %}
</ul>
</li>
{% endfor %}
</ul>
</code></pre>
<p>I've used a <code>ul</code> here so that it's easier to compare to the example in the docs, but obviously you can change the markup to whatever you need. It's important to know that regroup doesn't order its input, so you need to order by created_date in your view.</p>
<p>If you're using Django's dev version you can use this instead:</p>
<pre><code>{% regroup lifts_by_user by created_date.created_date as lift_list %}
<ul>
{% for day, lifts in lift_list %}
<li>Date: {{ day }}
<ul>
{% for lift in lifts %}
<li>{{ lift }}</li>
{% endfor %}
</ul>
</li>
{% endfor %}
</ul>
</code></pre>
<p>Which I think is a little clearer.</p>
<p>As an aside, none of this relies on having dates stored as a foreign key, but that's up to you.</p>
<h2>Questions from comments:</h2>
<ol>
<li><p><code>order_by('-created_date__created_date')</code> is joining Lifts to Dates through the Lifts.created_date foreign key and ordering by the Dates.created_date field. Have a look at <a href="https://docs.djangoproject.com/en/dev/topics/db/queries/#lookups-that-span-relationships" rel="nofollow">https://docs.djangoproject.com/en/dev/topics/db/queries/#lookups-that-span-relationships</a> for details.</p></li>
<li><p><code>for day, lifts in lift_list</code> is using tuple unpacking.
As a quick example:</p>
<pre><code>t = (1, 2, 3)
# first, second, third will have values 1, 2, 3 respectively
first, second, third = t
</code></pre>
<p><code>{% regroup lifts_by_user by created_date.created_date as lifts_list %}</code> produces a list of <a href="https://docs.python.org/3/library/collections.html#collections.namedtuple" rel="nofollow">namedtuples</a> (again, only in the dev version, if you're using 1.10 or earlier it's a list of dicts so you can't use this trick) so as you're iterating through lift_list you can unpack the date and list of lifts into separate variables.</p></li>
<li><p>If you have a Lift instance called lift, you can get the pk for its date by using <code>lift.created_date_id</code>. Accessing it where you have the date URL in your example template is a little trickier because you have to get a lift out of the regrouped date's list. Something like this:</p>
<pre><code>{% regroup lifts_by_user by created_date.created_date as lifts %}
<ul>
{% for day in lifts %}
<li>Date: {{ day.grouper }}
{# day.list.0 gets the first lift for this day #}
Date PK: {{ day.list.0.created_date_id }}
<ul>
{% for lift in day.list %}
<li>{{ lift }}</li>
{% endfor %}
</ul>
</li>
{% endfor %}
</ul>
</code></pre></li>
</ol>
| 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>I have tried subprocess and execv (<code>os.execv(sys.executable, ['python'] + sys.argv)</code>), however I am seeing very weird functionality on Windows. I open the command line, and run the script ("python myscript.py"). The script stops but does not exit (verified through Task Manager), and it will not restart itself unless I press enter twice. I would like it to work automatically.</p>
<p>Any suggestions? Thanks for your help!</p>
<pre><code>import threading
import time
import subprocess
import os
import sys
if __name__ == '__main__':
print("Starting thread list: " + str(threading.enumerate()))
for _ in range(3):
time.sleep(1)
print("Sleeping")
''' Attempt 1 with subprocess.Popen '''
# child = subprocess.Popen(['python',__file__], shell=True)
''' Attempt 2 with os.execv '''
args = sys.argv[:]
args.insert(0, sys.executable)
if sys.platform == 'win32':
args = ['"%s"' % arg for arg in args]
os.execv(sys.executable, args)
sys.exit()
</code></pre>
| 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_this()
try:
while True:
sleep(0.02)
except KeyboardInterrupt as ex:
# handle all exit procedures and data cleaning
print("[*] Handling all exit procedures...")
</code></pre>
<p>After this, you should be able to automatically restart your relevant procedure (even from within the script itself, without any external scripts). Anyway, it's a bit hard to know without seeing the relevant script, so maybe I can be of more help if you share some of it.</p>
| 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 -key mydomain.pem
</code></pre>
<p>When I try making request using openssl client I successfully get greeting response from registrar, but when I use following code in python i get ssl certificate error.</p>
<pre><code>sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(15)
sock.connect(('epptestv3.iis.se', 700))
sock.settimeout(60) # regular timeout
ssl_keyfile='myDomain.pem'
ssl_certfile='www.myDomain.se.crt'
ssl_ciphers='AES256-GCM-SHA384'
ssl_version=ssl.PROTOCOL_TLSv1_2
sock = ssl.wrap_socket(sock,
ssl_keyfile,
ssl_certfile,
ssl_version=ssl_version,
ciphers=ssl_ciphers,
server_side=False,
cert_reqs=ssl.CERT_REQUIRED,
ca_certs=None
)
</code></pre>
<p>After executing script I get following error:</p>
<pre><code>Traceback (most recent call last):
File "server_connect.py", line 54, in <module>
ca_certs=ssl_keyfile
File "/usr/lib/python2.7/ssl.py", line 933, in wrap_socket
ciphers=ciphers)
File "/usr/lib/python2.7/ssl.py", line 601, in __init__
self.do_handshake()
File "/usr/lib/python2.7/ssl.py", line 830, in do_handshake
self._sslobj.do_handshake()
ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:590)
</code></pre>
<p>Any idea what's wrong here?</p>
| 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 not CERT_NONE, then <strong>the ca_certs parameter must point to a file of CA certificates</strong>.</p>
</blockquote>
<p>Essentially you are asking in your code to validate the certificate from the server (<code>CERT_REQUIRED</code>) but specify at the same time that you have no trusted root (<code>ca_certs=None</code>). But without trusted root certificates no validation can be done.</p>
<p>Note that changing your code to use <code>CERT_NONE</code> instead would be a bad idea. It would probably work since no certificate validation will be done but it would be open to man in the middle attacks.</p>
| 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 or are simply facing version issues. I am trying to parse the website <a href="https://angel.co/companies" rel="nofollow">https://angel.co/companies</a>. Below is my code. </p>
<pre><code>with closing(Chrome()) as browser:
browser.get(url)
# wait for the page to load
while True:
try:
WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, "div.more")))
WebDriverWait(browser, timeout=10).until(EC.text_to_be_present_in_element((By.CSS_SELECTOR, 'div.more'), 'More'))
except:
break
element = browser.find_element_by_css_selector('div.more').click()
</code></pre>
<p>This code does not even hit the click option once. However, if I bring the second-wait-condition after the click() call (like below), it clicks the 'More' button once, the data for that pagination-step loads and then there are no more clicks done.</p>
<pre><code>with closing(Chrome()) as browser:
browser.get(url)
# wait for the page to load
while True:
try:
WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, "div.more")))
except:
break
element = browser.find_element_by_css_selector('div.more').click()
WebDriverWait(browser, timeout=10).until(EC.text_to_be_present_in_element((By.CSS_SELECTOR, 'div.more'), 'More'))
</code></pre>
<p>Can someone help me find out what am I doing wrong?</p>
| 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 retry decorator. If/when exceptions get thrown (StaleElementReferenceException, UnknownElementException, etc), you can immediately retry the call.</p>
<pre><code>from retry import retry
from explicit import waiter
from selenium import webdriver
from selenium.common.exceptions import StaleElementReferenceException
@retry(StaleElementReferenceException, tries=3, delay=0.5)
def click_more(driver):
waiter.find_element(driver, 'div.more').click()
driver = webdriver.Chrome()
try:
driver.get("https://angel.co/companies")
while True:
click_more(driver)
finally:
driver.quit()
</code></pre>
<p>Full disclosure: Explicit is a python package I maintain and available from PyPI. It is basically the same thing as the WebDriverWait call you have.</p>
| 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 are routine and subroutine in this program? I have read somewhere subroutine doesn't return anything so if I am getting right the inner portion of main function called subroutine or we can say directly subroutine is subprogram so in the above program subroutine should be:</p>
<pre><code>if x==0:
return 19
else:
u=1
tav(x-1)
u+=1
</code></pre>
<p>Am I getting it right?</p>
| 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>
<p>If you break your code like this</p>
<pre><code>ans = ['car','bus']
exp = ['a','b']
b = {x:{'1:N': [],'2:N': []} for x in exp}
print(b)
</code></pre>
<p>It would give<br>
<code>{'b': {'2:N': [], '1:N': []}, 'a': {'2:N': [], '1:N': []}}</code></p>
<p>If you modify dictionary comprehension like this<br>
<code>b = {a:{x:{'1:N': [],'2:N': []} for x in exp} for a in ans}</code></p>
<p>then you would get the output<br>
<code>{'bus': {'b': {'2:N': [], '1:N': []}, 'a': {'2:N': [], '1:N': []}}, 'car': {'b': {'2:N': [], '1:N': []}, 'a': {'2:N': [], '1:N': []}}}</code></p>
<p>I believe this is what you want, let me know if it helps.</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</li>
<li>Cat</li>
<li>Cat</li>
<li>Dog</li>
<li>Dog</li>
<li>Cat</li>
<li>Rat</li>
</ul>
<p>To find the record " Rat ", I tried </p>
<pre><code>df.filter(df.groupBy("Animal").count() <= 0.1 * df.select("Animal").count()).collect()
</code></pre>
<p>and I got the following error " TypeError : condition should be string or column" </p>
<p>How can I find the records that represent less than 10% ?</p>
<p>PS : Would it be simpler in SQL ? </p>
<p>Something like :</p>
<pre><code>result = spark.sql("SELECT Animal, COUNT(ANIMAL) FROM Table HAVING COUNT(Animal) < 0.1 * COUNT(Animal))
</code></pre>
<p>I know it is a simple operation but I just can't figure out how to code the
10% of total part.</p>
<p>Thanks for any help !</p>
| 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()
result=(df.groupBy('Animal').count()
.withColumn('total',F.lit(total))
.withColumn('fraction',F.expr('count/total'))
.filter('fraction>0.1'))
result.show()
</code></pre>
<p>Gave result:</p>
<pre><code>+------+-----+-----+--------+
|Animal|count|total|fraction|
+------+-----+-----+--------+
| Dog| 4| 10| 0.4|
| Cat| 5| 10| 0.5|
+------+-----+-----+--------+
</code></pre>
<p>To filter your initial set:</p>
<pre><code>filtered=df.join(result,df.Animal==result.Animal,'leftsemi')
filtered.show()
</code></pre>
<p>The 'leftsemi' join keeps the records in df that have a matching key in result</p>
| 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 = models.CharField(max_length=100, Unique=True,
default="".join([random.random(), random.random()])))
</code></pre>
<p>and</p>
<pre><code>id = models.CharField(max_length=100,
default="".join([random.random(), random.random()])))
</code></pre>
<p>Same error.</p>
<p>Is there a way around this? </p>
| 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)
ALTER TABLE t1 ADD UNIQUE (col2); -- OK (now a UNIQUE constraint on col2)
show create table t1;
CREATE TABLE `t1` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`col1` varchar(100) NOT NULL,
`col2` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `col2` (`col2`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
</code></pre>
<p>Now let's start over and see it blow up.</p>
<pre><code>drop table t1;
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 not null; -- OK (at the moment)
-- note: (all of col2 is now 0)
ALTER TABLE t1 ADD UNIQUE (col2); -- error 1062 duplicate entry '0' for key 'col2'
</code></pre>
<p>The reason the above blew up was because the NOT NULL on the col2 add column made all that data a 0. Then the UNIQUE constraint attempt failed.</p>
<p>Now below let's continue the thought:</p>
<pre><code>drop table t1;
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)
ALTER TABLE t1 ADD UNIQUE (col2); -- OK
select * from t1; -- col2 is NULL for all 3 rows
update t1 set col2=7 where id=1; -- OK
update t1 set col2=7 where id=2; -- error 1062 duplicate entry '7' for key 'col2'
</code></pre>
<p>The moral of the story is that if you add a column to a table with data pre-existing, and want that new column to be unique, you need to have it nullable to start. Then create the unique constraint. Now all data is NULL so the unique constraint is forgiving. But once you tweak the data to be non-NULL, it better be unique. Tweak meaning UPDATE or INSERT. So col2 needs to remain NULL or UNIQUE thereafter.</p>
| 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 operation gives me the following error: <code>TypeError: unsupported operand type(s) for ^=: 'str' and 'long'</code></p>
<p>It's important to me to generate a random binary string because I want to cipher it <code>cipher.encrypt(rand_string)</code> and only takes plain-text for parameters. I don't use <code>random.getrandbits(64)</code> because it returns a long but it doesn't match the 64 bits size block that I want.</p>
<p>Besides, I want to measure the hamming distance between the strings (should give me 1 because I only changed one bit) but I'm afraid that the algorithm I found is not valid to me because it compares the characters representations instead of comparing bit-level:</p>
<pre><code>def hamming_distance(s1, s2):
# Return the Hamming distance between equal-length sequences
if len(s1) != len(s2):
raise ValueError("Undefined for sequences of unequal length")
return sum(ch1 != ch2 for ch1, ch2 in zip(s1, s2))
</code></pre>
<p>So there are two questions:</p>
<p>How could I change randomly a bit of my binary string?</p>
<p>Is the above algorithm valid for my purposes? If it is not, how could I measure the Hamming Distance at bit-level?</p>
| 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 operation gives me the following error: <code>TypeError: unsupported operand type(s) for ^=: 'str' and 'long'</code></p>
<p>It's important to me to generate a random binary string because I want to cipher it <code>cipher.encrypt(rand_string)</code> and only takes plain-text for parameters. I don't use <code>random.getrandbits(64)</code> because it returns a long but it doesn't match the 64 bits size block that I want.</p>
<p>Besides, I want to measure the hamming distance between the strings (should give me 1 because I only changed one bit) but I'm afraid that the algorithm I found is not valid to me because it compares the characters representations instead of comparing bit-level:</p>
<pre><code>def hamming_distance(s1, s2):
# Return the Hamming distance between equal-length sequences
if len(s1) != len(s2):
raise ValueError("Undefined for sequences of unequal length")
return sum(ch1 != ch2 for ch1, ch2 in zip(s1, s2))
</code></pre>
<p>So there are two questions:</p>
<p>How could I change randomly a bit of my binary string?</p>
<p>Is the above algorithm valid for my purposes? If it is not, how could I measure the Hamming Distance at bit-level?</p>
| 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</code> module provides an interface to<code>os.urandom</code>: the <code>SystemRandom</code> class.</p>
<p>Doing bit-twiddling of multi-byte byte objects is possible in Python, although it is somewhat fiddly (especially in Python 2). It's much easier to do this sort of thing with Python integers. You can certainly get 64 random bits using the <code>getrandbits</code> method, although of course it's possible that some of those leading bits are zero bits.</p>
<p>Here's some code that runs on Python 2 or Python 3 that generates a random 64 bit number, flips one of its bits, and then computes the Hamming distance between the original number & the number with the flipped bit (which is of course 1). </p>
<pre><code>import random
# SystemRandom uses os.urandom()
sysrandom = random.SystemRandom()
def bincount(n):
return bin(n).count("1")
for _ in range(5):
bits0 = sysrandom.getrandbits(64)
print('bits0: {:016x}'.format(bits0))
bitnum = sysrandom.randint(0, 64)
print('bitnum: {}'.format(bitnum))
bits1 = bits0 ^ (1 << bitnum)
print('bits1: {:016x}'.format(bits1))
hamming = bincount(bits0 ^ bits1)
print('Hamming distance: {}\n'.format(hamming))
</code></pre>
<p><strong>typical output</strong></p>
<pre><code>bits0: a508c77693a0e7d7
bitnum: 32
bits1: a508c77793a0e7d7
Hamming distance: 1
bits0: 9608e25db458a350
bitnum: 3
bits1: 9608e25db458a358
Hamming distance: 1
bits0: f485bd53af91e2dc
bitnum: 62
bits1: b485bd53af91e2dc
Hamming distance: 1
bits0: 18f6749bc260fcd1
bitnum: 17
bits1: 18f6749bc262fcd1
Hamming distance: 1
bits0: 51b35142c99b6814
bitnum: 54
bits1: 51f35142c99b6814
Hamming distance: 1
</code></pre>
<p>There are faster ways to compute the number of 1 bits in a Python integer, but <code>bincount</code> is reasonably fast (and faster than a Python implementation of the well-known algorithm by Kernighan); see <a href="http://stackoverflow.com/q/9829578/4014959">fast way of counting non-zero bits in python</a> for other methods.</p>
<p>If you need to convert <code>bits0</code> to a bytes object that's easy in Python 3: just use the <code>.to_bytes</code> method, eg</p>
<pre><code>bytes0 = bits0.to_bytes(8, 'big')
</code></pre>
<p>If you need to use Python 2, converting an integer to a string and converting a string to an integer takes a little more work. Here's a demo, using a modified version of the above code.</p>
<pre><code>from __future__ import print_function
import random
from binascii import hexlify
# SystemRandom uses os.urandom()
sysrandom = random.SystemRandom()
def bincount(n):
return bin(n).count("1")
def int_to_bytes(n, size):
result = []
for _ in range(size):
result.append(chr(n & 0xff))
n >>= 8
return ''.join(result[::-1])
def bytes_to_int(bs):
n = 0
for b in bs:
n = (n << 8) | ord(b)
return n
for _ in range(4):
bits0 = sysrandom.getrandbits(64)
print('bits0: {0:016x}'.format(bits0))
bs = int_to_bytes(bits0, 8)
print('bytes:', repr(bs))
print('hex: ', hexlify(bs))
n = bytes_to_int(bs)
print('int: {0:016x}, {1}\n'.format(n, n == bits0))
</code></pre>
<p><strong>typical output</strong></p>
<pre><code>bits0: 69831968a1b0aff8
bytes: 'i\x83\x19h\xa1\xb0\xaf\xf8'
hex: 69831968a1b0aff8
int: 69831968a1b0aff8, True
bits0: c2c77e02969d3ebc
bytes: '\xc2\xc7~\x02\x96\x9d>\xbc'
hex: c2c77e02969d3ebc
int: c2c77e02969d3ebc, True
bits0: e87c78eb3929a76f
bytes: '\xe8|x\xeb9)\xa7o'
hex: e87c78eb3929a76f
int: e87c78eb3929a76f, True
bits0: 0d5d796c986ba329
bytes: '\r]yl\x98k\xa3)'
hex: 0d5d796c986ba329
int: 0d5d796c986ba329, True
</code></pre>
| 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 consume much more RAM the same time. The RAM sacrifices for the speed. The speed could be <strong>6 times faster</strong> comparing to clearing cache every time in the for-loop!!!</p>
<p>In contrast, you can use <code>linecache.clearcache()</code> in your for-loop. It took less memory but slow...</p>
<p>For me, I would clear the cache out of the for-loop and use multi-threads to chunk files into blocks. Extend the RAM and SWAP to be ready for the fast speed.</p>
| 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 = 60+ 0.05*Weight$")
ax.plot(t, 50+ 0.16*t, label=r"$Height = 50+ 0.16*Weight$")
ax.set_xlabel(r'$Weight$', fontsize=12)
ax.set_ylabel(r'$Height$', fontsize=12)
ax.set_title('Dependence')
plt.show()
</code></pre>
<p><a href="https://i.stack.imgur.com/cuk9R.png" rel="nofollow">enter image description here</a></p>
<p>As it can be seen scatter plot reflecting is not correct(it displays as lines)</p>
<p>Thank you!</p>
| 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 = 60+ 0.05*Weight$")
ax.plot(t, 50+ 0.16*t, label=r"$Height = 50+ 0.16*Weight$")
ax.set_xlabel(r'$Weight$', fontsize=12)
ax.set_ylabel(r'$Height$', fontsize=12)
ax.set_title('Dependence')
plt.show()
</code></pre>
<p><a href="https://i.stack.imgur.com/cuk9R.png" rel="nofollow">enter image description here</a></p>
<p>As it can be seen scatter plot reflecting is not correct(it displays as lines)</p>
<p>Thank you!</p>
| 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 file.</p>
<p>I've been looking everywhere, including SO and the H5Py docs, but I really can't find anything that describes my use-case, yet I know it can be done.</p>
<p>Below I have made a demo-source code describing what I'm doing right now:</p>
<pre><code>import h5py
import numpy as np
# I am using just random values here
# I know I can use h5py broadcasts and I have seen it being used before.
# But the issue I have is that I need to save around a million rows with each 10000 values
# so I can't keep the entire array in memory.
random_ints = np.random.random(size = (5000,10000))
# See http://stackoverflow.com/a/36902906/3991199 for "libver='latest'"
with h5py.File('my.data.hdf5', "w", libver='latest') as f:
X = f.create_dataset("X", (5000,10000))
for i1 in range(0, 5000):
for i2 in range(0, 10000):
X[i1,i2] = random_ints[i1,i2]
if i1 != 0 and i1 % 1000 == 0:
print "Done %d values..." % i1
</code></pre>
<p>This data comes from a database, it's not a pre-generated np array, as being seen in the source code.</p>
<p>If you run this code you can see it takes a long time before it prints out "Done 1000 values".</p>
<p>I'm on a laptop with 8GB ram, Ubuntu 16.04 LTS, and Intel Core M (which performs similar to Core i5) and SSD, that must be enough to perform a bit faster than this.</p>
<p>I've read about broadcasting here: <a href="http://docs.h5py.org/en/latest/high/dataset.html" rel="nofollow">http://docs.h5py.org/en/latest/high/dataset.html</a></p>
<p>When I use it like this:</p>
<pre><code>for i1 in range(0, 5000):
X[i1,:] = random_ints[i1]
</code></pre>
<p>It already goes a magnitude faster (done is a few secs). But I don't know how to get that to work with a variable-length dataset (the collumns are variable-length). It would be nice to get a bit of insights in how this should be done, as I think I'm not having a good idea of the concept of HDF5 right now :) Thanks a lot!</p>
| 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>Setting the elements one by one:</p>
<pre><code>vset[0]=np.random.randint(0,100,1000) # set just one element
for i in range(100): # set all arrays of varying length
vset[i]=np.random.randint(0,100,i)
vset[:] # view the dataset
</code></pre>
<p>Or making an object array:</p>
<pre><code>D=np.empty((100,),dtype=object)
for i in range(100): # setting that in same way
D[i]=np.random.randint(0,100,i)
vset[:]=D # write it to the file
vset[:]=D[::-1] # or write it in reverse order
</code></pre>
<p>A portion of the last write:</p>
<pre><code>In [587]: vset[-10:]
Out[587]:
array([array([52, 52, 46, 80, 5, 89, 6, 63, 21]),
array([38, 95, 51, 35, 66, 44, 29, 26]),
array([51, 96, 3, 64, 55, 31, 18]),
array([85, 96, 30, 82, 33, 45]), array([28, 37, 61, 57, 88]),
array([76, 65, 5, 29]), array([78, 29, 72]), array([77, 32]),
array([5]), array([], dtype=int32)], dtype=object)
</code></pre>
<p>I can view portions of an element with:</p>
<pre><code>In [593]: vset[3][:10]
Out[593]: array([86, 26, 2, 79, 90, 67, 66, 5, 63, 68])
</code></pre>
<p>but I can't treat it as a 2d array: <code>vset[3,:10]</code>. It's an array of arrays.</p>
| 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 there a suggested workaround the problem ?</p>
| 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 'monitor_rate_limit=True' if you want to handle the rate limit "Exception" by yourself.</p>
<p>That being said, you should really devise some smaller geo range, since your rate limit will be reached every 0.000000001 seconds (or less... it's still twitter).</p>
| 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. Someone told me to think about it in terms of l[0] with the end of len(l), l[1] with len(l)-1,... but there are n number of characters I am dealing with. Do I need to use a loop? Thank you.</p>
| -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/how-to-slice-listsarrays-and-tuples-in-python/" rel="nofollow">slicing in python</a>. Note, however, that strings in python are immutable, meaning you cannot change a portion of them using slicing (for instance, <code>a[2:4]='yo'</code> ).</p>
| -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><code>user@user-VirtualBox:/opt/ros/indigo/lib$ ldd libcv_bridge.so
linux-vdso.so.1 => (0x00007ffc9439d000)
libopencv_imgproc.so.2.4 => /usr/lib/x86_64-linux-gnu/libopencv_imgproc.so.2.4 (0x00007fcac6b34000)
libopencv_highgui.so.2.4 => /usr/lib/x86_64-linux-gnu/libopencv_highgui.so.2.4 (0x00007fcac68e9000)
libopencv_core.so.2.4 => /usr/lib/x86_64-linux-gnu/libopencv_core.so.2.4 (0x00007fcac64b1000)
libopencv_contrib.so.2.4 => /usr/lib/x86_64-linux-gnu/libopencv_contrib.so.2.4 (0x00007fcac61ce000)
libstdc++.so.6 => /usr/lib/x86_64-linux-gnu/libstdc++.so.6 (0x00007fcac5eca000)
libgcc_s.so.1 => /lib/x86_64-linux-gnu/libgcc_s.so.1 (0x00007fcac5cb3000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fcac58ee000)
libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007fcac56d0000)
libtbb.so.2 => /usr/lib/libtbb.so.2 (0x00007fcac549b000)
libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007fcac5195000)
libGL.so.1 => /var/lib/VBoxGuestAdditions/lib/libGL.so.1 (0x00007fcac4f5d000)
libjpeg.so.8 => /usr/lib/x86_64-linux-gnu/libjpeg.so.8 (0x00007fcac4d07000)
libpng12.so.0 => /lib/x86_64-linux-gnu/libpng12.so.0 (0x00007fcac4ae1000)
libtiff.so.5 => /usr/lib/x86_64-linux-gnu/libtiff.so.5 (0x00007fcac486f000)
libjasper.so.1 => /usr/lib/x86_64-linux-gnu/libjasper.so.1 (0x00007fcac4617000)
libIlmImf.so.6 => /usr/lib/x86_64-linux-gnu/libIlmImf.so.6 (0x00007fcac4368000)
libHalf.so.6 => /usr/lib/x86_64-linux-gnu/libHalf.so.6 (0x00007fcac4125000)
libgtk-x11-2.0.so.0 => /usr/lib/x86_64-linux-gnu/libgtk-x11-2.0.so.0 (0x00007fcac3ae7000)
libgdk-x11-2.0.so.0 => /usr/lib/x86_64-linux-gnu/libgdk-x11-2.0.so.0 (0x00007fcac3834000)
libgobject-2.0.so.0 => /usr/lib/x86_64-linux-gnu/libgobject-2.0.so.0 (0x00007fcac35e3000)
libglib-2.0.so.0 => /lib/x86_64-linux-gnu/libglib-2.0.so.0 (0x00007fcac32da000)
libgtkglext-x11-1.0.so.0 => /usr/lib/libgtkglext-x11-1.0.so.0 (0x00007fcac30d6000)
libgdkglext-x11-1.0.so.0 => /usr/lib/libgdkglext-x11-1.0.so.0 (0x00007fcac2e72000)
libdc1394.so.22 => /usr/lib/x86_64-linux-gnu/libdc1394.so.22 (0x00007fcac2bfd000)
libv4l1.so.0 => /usr/lib/x86_64-linux-gnu/libv4l1.so.0 (0x00007fcac29f7000)
libavcodec.so.54 => /usr/lib/x86_64-linux-gnu/libavcodec.so.54 (0x00007fcac1ca3000)
libavformat.so.54 => /usr/lib/x86_64-linux-gnu/libavformat.so.54 (0x00007fcac1980000)
libavutil.so.52 => /usr/lib/x86_64-linux-gnu/libavutil.so.52 (0x00007fcac175b000)
libswscale.so.2 => /usr/lib/x86_64-linux-gnu/libswscale.so.2 (0x00007fcac1514000)
libz.so.1 => /lib/x86_64-linux-gnu/libz.so.1 (0x00007fcac12fa000)
librt.so.1 => /lib/x86_64-linux-gnu/librt.so.1 (0x00007fcac10f2000)
libopencv_features2d.so.2.4 => /usr/lib/x86_64-linux-gnu/libopencv_features2d.so.2.4 (0x00007fcac0e4e000)
libopencv_calib3d.so.2.4 => /usr/lib/x86_64-linux-gnu/libopencv_calib3d.so.2.4 (0x00007fcac0bb8000)
libopencv_ml.so.2.4 => /usr/lib/x86_64-linux-gnu/libopencv_ml.so.2.4 (0x00007fcac0940000)
libopencv_objdetect.so.2.4 => /usr/lib/x86_64-linux-gnu/libopencv_objdetect.so.2.4 (0x00007fcac06c5000)
libopencv_video.so.2.4 => /usr/lib/x86_64-linux-gnu/libopencv_video.so.2.4 (0x00007fcac0471000)
/lib64/ld-linux-x86-64.so.2 (0x0000560365edd000)
VBoxOGLcrutil.so => /usr/lib/x86_64-linux-gnu/VBoxOGLcrutil.so (0x00007fcac028e000)
libXcomposite.so.1 => /usr/lib/x86_64-linux-gnu/libXcomposite.so.1 (0x00007fcac008b000)
libXdamage.so.1 => /usr/lib/x86_64-linux-gnu/libXdamage.so.1 (0x00007fcabfe88000)
libXfixes.so.3 => /usr/lib/x86_64-linux-gnu/libXfixes.so.3 (0x00007fcabfc81000)
libXext.so.6 => /usr/lib/x86_64-linux-gnu/libXext.so.6 (0x00007fcabfa6f000)
libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007fcabf86b000)
liblzma.so.5 => /lib/x86_64-linux-gnu/liblzma.so.5 (0x00007fcabf648000)
libjbig.so.0 => /usr/lib/x86_64-linux-gnu/libjbig.so.0 (0x00007fcabf43a000)
libIex.so.6 => /usr/lib/x86_64-linux-gnu/libIex.so.6 (0x00007fcabf21c000)
libIlmThread.so.6 => /usr/lib/x86_64-linux-gnu/libIlmThread.so.6 (0x00007fcabf015000)
libgmodule-2.0.so.0 => /usr/lib/x86_64-linux-gnu/libgmodule-2.0.so.0 (0x00007fcabee11000)
libpangocairo-1.0.so.0 => /usr/lib/x86_64-linux-gnu/libpangocairo-1.0.so.0 (0x00007fcabec04000)
libX11.so.6 => /usr/lib/x86_64-linux-gnu/libX11.so.6 (0x00007fcabe8ce000)
libatk-1.0.so.0 => /usr/lib/x86_64-linux-gnu/libatk-1.0.so.0 (0x00007fcabe6ac000)
libcairo.so.2 => /usr/lib/x86_64-linux-gnu/libcairo.so.2 (0x00007fcabe3a1000)
libgdk_pixbuf-2.0.so.0 => /usr/lib/x86_64-linux-gnu/libgdk_pixbuf-2.0.so.0 (0x00007fcabe17f000)
libgio-2.0.so.0 => /usr/lib/x86_64-linux-gnu/libgio-2.0.so.0 (0x00007fcabde0c000)
libpangoft2-1.0.so.0 => /usr/lib/x86_64-linux-gnu/libpangoft2-1.0.so.0 (0x00007fcabdbf7000)
libpango-1.0.so.0 => /usr/lib/x86_64-linux-gnu/libpango-1.0.so.0 (0x00007fcabd9a9000)
libfontconfig.so.1 => /usr/lib/x86_64-linux-gnu/libfontconfig.so.1 (0x00007fcabd76d000)
libXrender.so.1 => /usr/lib/x86_64-linux-gnu/libXrender.so.1 (0x00007fcabd562000)
libXinerama.so.1 => /usr/lib/x86_64-linux-gnu/libXinerama.so.1 (0x00007fcabd35f000)
libXi.so.6 => /usr/lib/x86_64-linux-gnu/libXi.so.6 (0x00007fcabd14f000)
libXrandr.so.2 => /usr/lib/x86_64-linux-gnu/libXrandr.so.2 (0x00007fcabcf45000)
libXcursor.so.1 => /usr/lib/x86_64-linux-gnu/libXcursor.so.1 (0x00007fcabcd3a000)
libffi.so.6 => /usr/lib/x86_64-linux-gnu/libffi.so.6 (0x00007fcabcb32000)
libpcre.so.3 => /lib/x86_64-linux-gnu/libpcre.so.3 (0x00007fcabc8f3000)
libGLU.so.1 => /usr/lib/x86_64-linux-gnu/libGLU.so.1 (0x00007fcabc685000)
libXmu.so.6 => /usr/lib/x86_64-linux-gnu/libXmu.so.6 (0x00007fcabc46c000)
libpangox-1.0.so.0 => /usr/lib/x86_64-linux-gnu/libpangox-1.0.so.0 (0x00007fcabc24c000)
libraw1394.so.11 => /usr/lib/x86_64-linux-gnu/libraw1394.so.11 (0x00007fcabc03e000)
libusb-1.0.so.0 => /lib/x86_64-linux-gnu/libusb-1.0.so.0 (0x00007fcabbe27000)
libv4l2.so.0 => /usr/lib/x86_64-linux-gnu/libv4l2.so.0 (0x00007fcabbc18000)
libxvidcore.so.4 => /usr/lib/x86_64-linux-gnu/libxvidcore.so.4 (0x00007fcabb8da000)
libx264.so.142 => /usr/lib/x86_64-linux-gnu/libx264.so.142 (0x00007fcabb544000)
libvpx.so.1 => /usr/lib/x86_64-linux-gnu/libvpx.so.1 (0x00007fcabb164000)
libvorbisenc.so.2 => /usr/lib/x86_64-linux-gnu/libvorbisenc.so.2 (0x00007fcabac95000)
libvorbis.so.0 => /usr/lib/x86_64-linux-gnu/libvorbis.so.0 (0x00007fcabaa68000)
libtheoraenc.so.1 => /usr/lib/x86_64-linux-gnu/libtheoraenc.so.1 (0x00007fcaba827000)
libtheoradec.so.1 => /usr/lib/x86_64-linux-gnu/libtheoradec.so.1 (0x00007fcaba60e000)
libspeex.so.1 => /usr/lib/x86_64-linux-gnu/libspeex.so.1 (0x00007fcaba3f5000)
libschroedinger-1.0.so.0 => /usr/lib/x86_64-linux-gnu/libschroedinger-1.0.so.0 (0x00007fcaba130000)
libopus.so.0 => /usr/lib/x86_64-linux-gnu/libopus.so.0 (0x00007fcab9ee8000)
libopenjpeg.so.2 => /usr/lib/x86_64-linux-gnu/libopenjpeg.so.2 (0x00007fcab9cc6000)
libmp3lame.so.0 => /usr/lib/x86_64-linux-gnu/libmp3lame.so.0 (0x00007fcab9a38000)
libgsm.so.1 => /usr/lib/x86_64-linux-gnu/libgsm.so.1 (0x00007fcab982a000)
libva.so.1 => /usr/lib/x86_64-linux-gnu/libva.so.1 (0x00007fcab9614000)
librtmp.so.0 => /usr/lib/x86_64-linux-gnu/librtmp.so.0 (0x00007fcab93f9000)
libgnutls.so.26 => /usr/lib/x86_64-linux-gnu/libgnutls.so.26 (0x00007fcab913b000)
libbz2.so.1.0 => /lib/x86_64-linux-gnu/libbz2.so.1.0 (0x00007fcab8f2b000)
libopencv_flann.so.2.4 => /usr/lib/x86_64-linux-gnu/libopencv_flann.so.2.4 (0x00007fcab8cc0000)
libfreetype.so.6 => /usr/lib/x86_64-linux-gnu/libfreetype.so.6 (0x00007fcab8a1c000)
libxcb.so.1 => /usr/lib/x86_64-linux-gnu/libxcb.so.1 (0x00007fcab87fd000)
libpixman-1.so.0 => /usr/lib/x86_64-linux-gnu/libpixman-1.so.0 (0x00007fcab8554000)
libxcb-shm.so.0 => /usr/lib/x86_64-linux-gnu/libxcb-shm.so.0 (0x00007fcab8351000)
libxcb-render.so.0 => /usr/lib/x86_64-linux-gnu/libxcb-render.so.0 (0x00007fcab8148000)
libselinux.so.1 => /lib/x86_64-linux-gnu/libselinux.so.1 (0x00007fcab7f24000)
libresolv.so.2 => /lib/x86_64-linux-gnu/libresolv.so.2 (0x00007fcab7d09000)
libharfbuzz.so.0 => /usr/lib/x86_64-linux-gnu/libharfbuzz.so.0 (0x00007fcab7ab4000)
libthai.so.0 => /usr/lib/x86_64-linux-gnu/libthai.so.0 (0x00007fcab78aa000)
libexpat.so.1 => /lib/x86_64-linux-gnu/libexpat.so.1 (0x00007fcab7680000)
libXt.so.6 => /usr/lib/x86_64-linux-gnu/libXt.so.6 (0x00007fcab7419000)
libudev.so.1 => /lib/x86_64-linux-gnu/libudev.so.1 (0x00007fcab7208000)
libv4lconvert.so.0 => /usr/lib/x86_64-linux-gnu/libv4lconvert.so.0 (0x00007fcab6f8f000)
libogg.so.0 => /usr/lib/x86_64-linux-gnu/libogg.so.0 (0x00007fcab6d85000)
liborc-0.4.so.0 => /usr/lib/x86_64-linux-gnu/liborc-0.4.so.0 (0x00007fcab6b03000)
libgcrypt.so.11 => /lib/x86_64-linux-gnu/libgcrypt.so.11 (0x00007fcab6882000)
libtasn1.so.6 => /usr/lib/x86_64-linux-gnu/libtasn1.so.6 (0x00007fcab666e000)
libp11-kit.so.0 => /usr/lib/x86_64-linux-gnu/libp11-kit.so.0 (0x00007fcab642c000)
libXau.so.6 => /usr/lib/x86_64-linux-gnu/libXau.so.6 (0x00007fcab6227000)
libXdmcp.so.6 => /usr/lib/x86_64-linux-gnu/libXdmcp.so.6 (0x00007fcab6021000)
libgraphite2.so.3 => /usr/lib/x86_64-linux-gnu/libgraphite2.so.3 (0x00007fcab5dfa000)
libdatrie.so.1 => /usr/lib/x86_64-linux-gnu/libdatrie.so.1 (0x00007fcab5bf3000)
libSM.so.6 => /usr/lib/x86_64-linux-gnu/libSM.so.6 (0x00007fcab59eb000)
libICE.so.6 => /usr/lib/x86_64-linux-gnu/libICE.so.6 (0x00007fcab57ce000)
libcgmanager.so.0 => /lib/x86_64-linux-gnu/libcgmanager.so.0 (0x00007fcab55b3000)
libnih.so.1 => /lib/x86_64-linux-gnu/libnih.so.1 (0x00007fcab539b000)
libnih-dbus.so.1 => /lib/x86_64-linux-gnu/libnih-dbus.so.1 (0x00007fcab5190000)
libdbus-1.so.3 => /lib/x86_64-linux-gnu/libdbus-1.so.3 (0x00007fcab4f4b000)
libgpg-error.so.0 => /lib/x86_64-linux-gnu/libgpg-error.so.0 (0x00007fcab4d45000)
libuuid.so.1 => /lib/x86_64-linux-gnu/libuuid.so.1 (0x00007fcab4b40000)
</code></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