title
stringlengths 10
172
| question_id
int64 469
40.1M
| question_body
stringlengths 22
48.2k
| question_score
int64 -44
5.52k
| question_date
stringlengths 20
20
| answer_id
int64 497
40.1M
| answer_body
stringlengths 18
33.9k
| answer_score
int64 -38
8.38k
| answer_date
stringlengths 20
20
| tags
list |
---|---|---|---|---|---|---|---|---|---|
Is there any reason to use Python's generator-based coroutines over async/await?
| 39,671,950 |
<p>Despite its well-known "one way to do it" philosophy, Python (as of version 3.5) supports two ways of writing coroutines:</p>
<ol>
<li><a href="https://www.python.org/dev/peps/pep-0342/" rel="nofollow">enhanced generators</a> (perhaps with <a href="https://www.python.org/dev/peps/pep-0380/" rel="nofollow"><code>yield from</code></a>)</li>
<li><a href="https://www.python.org/dev/peps/pep-0492/" rel="nofollow"><code>async</code> and <code>await</code></a>.</li>
</ol>
<p>Assume we only need to support versions of Python >= 3.5. Is it ever necessary to use the older, generator-based coroutines? Or do <code>async</code>/<code>await</code>-based coroutines completely replace generator-based ones?</p>
| 1 |
2016-09-24T02:37:24Z
| 39,699,293 |
<p>Quoting <a href="https://mail.python.org/pipermail/python-dev/2015-April/139728.html" rel="nofollow">Guido van Rossum himself</a>:</p>
<blockquote>
<p>[...] eventually we'll always be using async functions when coroutines are called for, dedicating generators once again to their pre-PEP-342 role of a particularly efficient way to implement iterators.</p>
</blockquote>
| 0 |
2016-09-26T09:34:14Z
|
[
"python",
"asynchronous",
"async-await",
"generator",
"coroutine"
] |
What is the optimal fps to record an OpenCV video at?
| 39,671,958 |
<p>I'm tinkering around with OpenCV and I'm having some trouble figuring out what fps I should be recording webcam footage. When I record it at <code>15 fps</code> the recorded footage goes much faster than "real life". I was wondering if there is an "optimal" fps at which I can record such that the recording will be <strong>exactly</strong> as long as the time it took to shoot the video?</p>
<p>Here's the program I'm running (though I think that's irrelevant to the question):</p>
<pre><code>import cv2
cap = cv2.VideoCapture(0)
# Define the codec and create VideoWriter object
fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')
fps = 15.0 # Controls the fps of the video created: todo look up optimal fps for webcam
out = cv2.VideoWriter()
success = out.open('../assets/output.mp4v',fourcc, fps, (1280,720),True)
while(cap.isOpened()):
ret, frame = cap.read()
if ret==True:
frame = cv2.flip(frame,1)
# write the flipped frame
out.write(frame)
cv2.imshow('frame',frame)
# If user presses escape key program terminates
userInput = cv2.waitKey(1)
if userInput == 27:
break
else:
break
# Release everything if job is finished
cap.release()
out.release()
cv2.destroyAllWindows()
</code></pre>
| 0 |
2016-09-24T02:40:12Z
| 39,672,039 |
<p>Let's say your camera recording with 25 FPS. If you are capturing 15 FPS while your camera is recording with 25 FPS, the video will be approximately 1.6 times faster than real life.</p>
<p>You can find out frame rate with <code>get(CAP_PROP_FPS)</code> or <code>get(CV_CAP_PROP_FPS)</code> but it's invalid unless the source is a video file.</p>
<p>For cameras or webcams you have to calculate(<em>estimate</em>) FPS programmatically:</p>
<pre><code>num_frames = 240; # Number of frames to capture
print "Capturing {0} frames".format(num_frames)
start = time.time()# Start time
# Grab a few frames
for i in xrange(0, num_frames) :
ret, frame = video.read()
end = time.time() # End time
seconds = end - start # Time elapsed
print "Time taken : {0} seconds".format(seconds)
# Calculate frames per second
fps = num_frames / seconds;
print "Estimated frames per second : {0}".format(fps);
</code></pre>
<p>So this program estimates frame rate of your video source by recording first 240 frames as sample and then calculates delta time. Lastly, the result of a simple division gives you the FPS. </p>
| 1 |
2016-09-24T02:58:04Z
|
[
"python",
"python-3.x",
"opencv"
] |
How to swap columns conditionally in pandas
| 39,671,982 |
<p>I have a pandas dataframe <code>df</code> with 4 columns. For example here is a toy example:</p>
<pre><code>foo1 foo2 foo3 foo4
egg cheese 2 1
apple pear 1 3
french spanish 10 1
</code></pre>
<p>The columns are foo1, foo2, foo3 and foo4</p>
<p>I would like to swap columns foo1 and foo2 and also swap columns foo3 and foo4 when foo3 < foo4. So the result would be:</p>
<pre><code>foo1 foo2 foo3 foo4
cheese egg 1 2
apple pear 1 3
spanish french 1 10
</code></pre>
<p>I can find the rows that need swapping with <code>df[df['foo3'] < df['foo4']]</code> but how can I do the swapping efficiently. My dataframe is large.</p>
| 1 |
2016-09-24T02:47:42Z
| 39,672,184 |
<p>You can use <code>pandas.Series.where</code> function to construct new data frame based on the condition:</p>
<pre><code>pairs = [('foo1', 'foo2'), ('foo3', 'foo4')] # construct pairs of columns that need to swapped
df_out = pd.DataFrame()
# for each pair, swap the values if foo3 < foo4
for l, r in pairs:
df_out[l] = df[l].where(df.foo3 < df.foo4, df[r])
df_out[r] = df[r].where(df.foo3 < df.foo4, df[l])
df_out
# foo1 foo2 foo3 foo4
#0 cheese egg 1 2
#1 apple pear 1 3
#2 spanish french 1 10
</code></pre>
| 1 |
2016-09-24T03:30:08Z
|
[
"python",
"pandas"
] |
How to swap columns conditionally in pandas
| 39,671,982 |
<p>I have a pandas dataframe <code>df</code> with 4 columns. For example here is a toy example:</p>
<pre><code>foo1 foo2 foo3 foo4
egg cheese 2 1
apple pear 1 3
french spanish 10 1
</code></pre>
<p>The columns are foo1, foo2, foo3 and foo4</p>
<p>I would like to swap columns foo1 and foo2 and also swap columns foo3 and foo4 when foo3 < foo4. So the result would be:</p>
<pre><code>foo1 foo2 foo3 foo4
cheese egg 1 2
apple pear 1 3
spanish french 1 10
</code></pre>
<p>I can find the rows that need swapping with <code>df[df['foo3'] < df['foo4']]</code> but how can I do the swapping efficiently. My dataframe is large.</p>
| 1 |
2016-09-24T02:47:42Z
| 39,673,448 |
<p>You can find the rows with <code>df[df['foo3'] < df['foo4']]</code>, yes, but if you use the Boolean series instead, you can easily accomplish your goal:</p>
<pre><code>s = df['foo3'] < df['foo4']
df.loc[s, ['foo1','foo2']] = df.loc[s, ['foo2','foo1']].values
df.loc[s, ['foo3','foo4']] = df.loc[s, ['foo4','foo3']].values
</code></pre>
<p>Note, you need the <code>.values</code> at the end of the RHS to prevent Pandas from aligning on column names, which will undermine the purpose.</p>
| 2 |
2016-09-24T06:50:35Z
|
[
"python",
"pandas"
] |
Macbook OpenEmu Python send keystrokes
| 39,671,998 |
<p>I am really impressed by <a href="https://github.com/pakoito/MarI-O" rel="nofollow">this</a> MarlIO project and want to implement something similar using Python. However, I got the emulator <a href="http://openemu.org/" rel="nofollow">OpenEmu</a> working, however, I don't know how to control the game using Python. </p>
<p>Isn't it just a matter of sending a few keystrokes?! Man, it is not that straightforward on a Mac. </p>
<pre><code>In [41]: cmd1
Out[41]: '\nosascript -e \'tell application "System Events" to key code 48 using {command down}\' \n'
In [42]: cmd2
Out[42]: '\nosascript -e \'tell application "System Events" to keystroke "a"\' \n'
</code></pre>
<p>I want to first use "COMMAND+TAB" to switch to the openEmu and then hit "a" to jump. However, when I ran the two commands, it only switched to the OpenEmu, looks like the keystroke 'a' did not got sent. </p>
<p><a href="http://i.stack.imgur.com/pblXX.png" rel="nofollow"><img src="http://i.stack.imgur.com/pblXX.png" alt="enter image description here"></a></p>
<p>However, when I ran 'cmd2' separately, it was clearly working.
Then I testedit against a different application - sublime, and it seemed to work there. </p>
<p><a href="http://i.stack.imgur.com/bqmqo.png" rel="nofollow"><img src="http://i.stack.imgur.com/bqmqo.png" alt="enter image description here"></a></p>
<p>Can anyone point me to the right direction what I really did wrong with OpenEmu? </p>
| 0 |
2016-09-24T02:50:08Z
| 39,672,064 |
<p>I did something like that a few months ago. The keystrokes are sent. However, System Event keystrokes last virtually no time, so the emulator's input mechanism doesn't pick them up.</p>
<p>I couldn't find a way to ask for a duration with AppleScript, so I ended up solving the problem using <a href="https://developer.apple.com/reference/coregraphics/1658572-quartz_event_services" rel="nofollow">Quartz event taps</a>, which let you do, for instance, "start pressing key, sleep 0.1s, stop pressing key". I did it in Swift, but you should be able to do it in Python with the <code>ctype</code> module.</p>
<p>Also note that it might be difficult to synchronize on a frame basis with the emulator. I <a href="https://github.com/OpenEmu/OpenEmu/pull/2378" rel="nofollow">raised that problem with the project maintainers</a>, but I turned away because of the relatively cold response.</p>
| 0 |
2016-09-24T03:04:40Z
|
[
"python",
"osx",
"emulator",
"osascript"
] |
Errors inserting many rows into postgreSQL with psycopg2
| 39,672,088 |
<p>I have a a number of XML files I need to open and then process to produce a large number of rows that are then inserted into several tables in a remote postgress database.</p>
<p>To extract the XML data I am using <code>xml.etree.ElementTree</code> to parse the XML tree and extract elements as needed. While I am doing a number of things, the basic action is to take a specific element, whether String or Integer and place in one of a number of dictionaries. </p>
<p>After some more processing I have a number of dictionaries that I need to insert into my database. For any single xml file I may produce up to 8-10,000 rows (or queries) across 3 tables. </p>
<p>While testing, I was outputting to sql files and then manually running the query. That is obviously not going to work if I have lots of xml files..</p>
<p>I have therefore tried using <code>psycopg2</code> to automate this process. As I understand it from stack overflow and elsewhere running individual <code>execute</code> functions is painfully slow. Based on <a href="http://stackoverflow.com/questions/8134602/psycopg2-insert-multiple-rows-with-one-query">This stackoverflow question</a> I have attempted to write code as follows:</p>
<pre><code>QueryData = ','.join(cur.mogrify('(%s,%s,%s)', row) for row in myData)
cur.execute('INSERT INTO DBTABLE' + QueryData)
cur.commit()
</code></pre>
<p>where <code>myData</code> is a list of tuples <code>[(a,b,c),(a,b,c),(a,b,c)...]</code> the contents of which are a combination of data extracted by <code>xml.etree.ElementTree</code> and values I have calculated myself.</p>
<p>When I try to actually execute the above code however I get the following error:</p>
<p><code>TypeError: sequence item 0: expected str instance, bytes found</code></p>
<p>OK... if I then try to convert my data (each tuple element) to <code>str()</code> however I get:</p>
<pre><code>TypeError: encoding without a string argument
</code></pre>
<p>Am I just going about this totally wrong? How can I do what I need? I am using Python3.</p>
<p>ADDITIONAL </p>
<p>I was asked to show an example of the data.</p>
<p>Here is the simplest, it is 3 integer values to put into a table. It is of the form: <code>(document_id,item_index,item_code)</code></p>
<p>A typical example would be: <code>(937, 138, 681)</code></p>
<p>My general attempts to convert have been to try:</p>
<pre><code>(str(document_id),str(item_index),str(item_code))
</code></pre>
<p>I have also tried going the other way:</p>
<pre><code>(bytes(document_id,'utf-8'),bytes(item_index,'utf-8'),bytes(item_code,'utf-8'))
</code></pre>
<p>the latter also raises the error: <code>TypeError: encoding without a string argument</code></p>
| 1 |
2016-09-24T03:10:48Z
| 39,673,132 |
<p>you are missing VALUES after the table name, everything else seems correct:</p>
<p>cursorPG.execute("INSERT INTO test <strong>VALUES</strong> "+','.join(cursorPG.mogrify('(%s,%s)',x) for x in mydata))</p>
| 0 |
2016-09-24T06:10:20Z
|
[
"python",
"postgresql",
"python-3.x",
"xml-parsing",
"psycopg2"
] |
Errors inserting many rows into postgreSQL with psycopg2
| 39,672,088 |
<p>I have a a number of XML files I need to open and then process to produce a large number of rows that are then inserted into several tables in a remote postgress database.</p>
<p>To extract the XML data I am using <code>xml.etree.ElementTree</code> to parse the XML tree and extract elements as needed. While I am doing a number of things, the basic action is to take a specific element, whether String or Integer and place in one of a number of dictionaries. </p>
<p>After some more processing I have a number of dictionaries that I need to insert into my database. For any single xml file I may produce up to 8-10,000 rows (or queries) across 3 tables. </p>
<p>While testing, I was outputting to sql files and then manually running the query. That is obviously not going to work if I have lots of xml files..</p>
<p>I have therefore tried using <code>psycopg2</code> to automate this process. As I understand it from stack overflow and elsewhere running individual <code>execute</code> functions is painfully slow. Based on <a href="http://stackoverflow.com/questions/8134602/psycopg2-insert-multiple-rows-with-one-query">This stackoverflow question</a> I have attempted to write code as follows:</p>
<pre><code>QueryData = ','.join(cur.mogrify('(%s,%s,%s)', row) for row in myData)
cur.execute('INSERT INTO DBTABLE' + QueryData)
cur.commit()
</code></pre>
<p>where <code>myData</code> is a list of tuples <code>[(a,b,c),(a,b,c),(a,b,c)...]</code> the contents of which are a combination of data extracted by <code>xml.etree.ElementTree</code> and values I have calculated myself.</p>
<p>When I try to actually execute the above code however I get the following error:</p>
<p><code>TypeError: sequence item 0: expected str instance, bytes found</code></p>
<p>OK... if I then try to convert my data (each tuple element) to <code>str()</code> however I get:</p>
<pre><code>TypeError: encoding without a string argument
</code></pre>
<p>Am I just going about this totally wrong? How can I do what I need? I am using Python3.</p>
<p>ADDITIONAL </p>
<p>I was asked to show an example of the data.</p>
<p>Here is the simplest, it is 3 integer values to put into a table. It is of the form: <code>(document_id,item_index,item_code)</code></p>
<p>A typical example would be: <code>(937, 138, 681)</code></p>
<p>My general attempts to convert have been to try:</p>
<pre><code>(str(document_id),str(item_index),str(item_code))
</code></pre>
<p>I have also tried going the other way:</p>
<pre><code>(bytes(document_id,'utf-8'),bytes(item_index,'utf-8'),bytes(item_code,'utf-8'))
</code></pre>
<p>the latter also raises the error: <code>TypeError: encoding without a string argument</code></p>
| 1 |
2016-09-24T03:10:48Z
| 39,674,631 |
<p>Ok so I have it working... I am however confused as to why my solution worked. I am posting it as an answer but if someone could explain to me what is going on that would be great:</p>
<p>basically this:</p>
<pre><code>QueryData = ','.join(cur.mogrify('(%s,%s,%s)', row) for row in myData)
cur.execute('INSERT INTO DBTABLE' + QueryData)
</code></pre>
<p>had to be changed to:</p>
<pre><code>QueryData = b','.join(cur.mogrify(b'(%s,%s,%s)', row) for row in myData)
cur.execute(b'INSERT INTO DBTABLE' + QueryData)
</code></pre>
<p>Which strikes me as pretty inelegant. </p>
| 0 |
2016-09-24T09:12:48Z
|
[
"python",
"postgresql",
"python-3.x",
"xml-parsing",
"psycopg2"
] |
How to Generate Seeded 2D White Noise
| 39,672,153 |
<p>I am trying to write a function so that <code>f(x, y, seed)</code> returns some float between 0.0 and 1.0. <code>x</code> and <code>y</code> are two floats, and the <code>seed</code> would be an integer. The result should look like a random number, but using the same arguments will always return the same result. I am planning to use this for terrain generation (using Perlin Noise), but the effect should be that white noise could be created from a given seed (with the x and y arguments corresponding to positions in the image).</p>
<p>I have looked into using hash functions to achieve this, but all of the ones I have come across either don't accept floats, don't produce uniform results (so that each number between 0.0 and 1.0 is equally likely), show an obvious pattern, or the result doesn't change much for close co-ordinates)</p>
| 0 |
2016-09-24T03:24:40Z
| 39,672,246 |
<p>Depends on what distribution you're looking to achieve, but e.g. for uniform distribution over a known image size you could do:</p>
<pre><code>width = 100
from random import random
def f(x, y, seed):
rng = random(seed)
rng.jumpahead(x * width + y)
return rng.random()
</code></pre>
<p>Alternatively, if you have the ordinal index of the pixel available instead of x and y, you don't need the grid size:</p>
<pre><code>from random import random
def f(n, seed):
rng = random(seed)
rng.jumpahead(n)
return rng.random()
</code></pre>
| 0 |
2016-09-24T03:43:26Z
|
[
"python",
"random",
"hash",
"noise"
] |
How to Generate Seeded 2D White Noise
| 39,672,153 |
<p>I am trying to write a function so that <code>f(x, y, seed)</code> returns some float between 0.0 and 1.0. <code>x</code> and <code>y</code> are two floats, and the <code>seed</code> would be an integer. The result should look like a random number, but using the same arguments will always return the same result. I am planning to use this for terrain generation (using Perlin Noise), but the effect should be that white noise could be created from a given seed (with the x and y arguments corresponding to positions in the image).</p>
<p>I have looked into using hash functions to achieve this, but all of the ones I have come across either don't accept floats, don't produce uniform results (so that each number between 0.0 and 1.0 is equally likely), show an obvious pattern, or the result doesn't change much for close co-ordinates)</p>
| 0 |
2016-09-24T03:24:40Z
| 39,673,840 |
<p>After looking around for a few more hours, I came across this: <a href="https://groups.google.com/forum/#!msg/proceduralcontent/AuvxuA1xqmE/T8t88r2rfUcJ" rel="nofollow">https://groups.google.com/forum/#!msg/proceduralcontent/AuvxuA1xqmE/T8t88r2rfUcJ</a></p>
<p>In particular, I have used the answer from Adam Smith to make this:</p>
<pre><code>def rot(x, b):
return((x<<b) ^ (x >> (32 - b)))
def pcghash(x, y, seed):
for l in range(0, 3):
x = rot(x^0xcafebabe + y^0xfaceb00c + seed^0xba5eba11, 23)
x = rot(x^0xdeadbeef + y^0x8badf00d + seed^0x5ca1ab1e, 5)
x = rot(x^0xca11ab1e + y^0xfacefeed + seed^0xdeadc0de, 17)
return(x^y^seed)
def noise(x, y, seed):
return(float('0.' + str(pcghash(x, y, seed))[-10:]))
</code></pre>
<p>This takes the coordinates and a seed, and returns a number uniformly distributed between 0.0 and 1.0 (with 10 decimal places). I'm not entirely happy with this, because all of the arguments have to be integers, there are a lot of unused generated bits, and I'm sure the code in the <code>noise()</code> function could be improved to be faster, but this suits my purposes.</p>
| 0 |
2016-09-24T07:40:04Z
|
[
"python",
"random",
"hash",
"noise"
] |
No Sympy two-sided limits?
| 39,672,198 |
<p>I can't get Sympy to handle two-sided limits. Running in a Jupyter notebook, Anaconda installation: </p>
<pre><code>from sympy import *
x = symbols('x')
limit(1/x,x,0)
</code></pre>
<p>gives an answer of <code>oo</code>. Furthermore,</p>
<pre><code>Limit(1/x,x,0)
</code></pre>
<p>prints as a right-sided limit. In fact, all of my two-sided limits 'pretty-print' as right-sided limits. They seem to be evaluated that way, too. Can't find a way to force two-sided. Of course, one could write a short program to remedy this. </p>
<p>What am I doing wrong?</p>
| 1 |
2016-09-24T03:34:43Z
| 39,682,009 |
<p><code>limit</code> has a fourth argument, <code>dir</code>, which specifies a direction:</p>
<pre><code>>>> limit(1/x, x, 0, '+')
oo
>>> limit(1/x, x, 0, '-')
-oo
>>> limit(1/x, x, 0)
oo
</code></pre>
<p>The default is from the right. Bidirectional limits are not directly implemented yet, but you can easily check both directions. </p>
| 1 |
2016-09-24T23:44:50Z
|
[
"python",
"sympy"
] |
Is there a way i can store this variable without it getting reset
| 39,672,293 |
<p>I have this recursive function</p>
<pre><code>def recursive_search(x):
y = []
for i in x:
if (i == tuple(i)) or (i == list(i)) or i == set(i):
recursive_search(i)
else:
y.append(i)
print(y)
print(recursive_search(("re",("cur",("sion",(" ",("foo",["bar",{"baz"}])))))))
</code></pre>
<p>which prints out</p>
<pre><code>['baz']
['bar']
['foo']
[' ']
['sion']
['cur']
['re']
None
</code></pre>
<p>when i set "print(y)" to "return y" it only prints out "['re']". if using global y is unsafe then what is another way i could do this.</p>
| 0 |
2016-09-24T03:51:55Z
| 39,672,327 |
<p>You need to capture the return value and using that to construct your answer:</p>
<pre><code>def recursive_search(x):
y = []
for i in x:
if type(i) in (tuple, list, set):
y.append(recursive_search(i))
else:
y.append(i)
return y
print(recursive_search(("re",("cur",("sion",(" ",("foo",["bar",{"baz"}])))))))
# ['re', ['cur', ['sion', [' ', ['foo', ['bar', ['baz']]]]]]]
</code></pre>
<p>If you need something other than nesting you can do something else with the return.</p>
| 3 |
2016-09-24T03:57:18Z
|
[
"python",
"python-3.x",
"recursion"
] |
Is there a way i can store this variable without it getting reset
| 39,672,293 |
<p>I have this recursive function</p>
<pre><code>def recursive_search(x):
y = []
for i in x:
if (i == tuple(i)) or (i == list(i)) or i == set(i):
recursive_search(i)
else:
y.append(i)
print(y)
print(recursive_search(("re",("cur",("sion",(" ",("foo",["bar",{"baz"}])))))))
</code></pre>
<p>which prints out</p>
<pre><code>['baz']
['bar']
['foo']
[' ']
['sion']
['cur']
['re']
None
</code></pre>
<p>when i set "print(y)" to "return y" it only prints out "['re']". if using global y is unsafe then what is another way i could do this.</p>
| 0 |
2016-09-24T03:51:55Z
| 39,672,360 |
<p>Declare the second argument, which will be every time that the recursive function is called:</p>
<pre><code>def recursive_search(x,y=None):
if y is None:
y = []
for i in x:
if (i == tuple(i)) or (i == list(i)) or i == set(i):
recursive_search(i, y)
else:
y +=[i]
return y[:]
y = recursive_search(("re",("cur",("sion",(" ",("foo",["bar",{"baz"}]))))))
print(y)
z = recursive_search(("a",("brown",("fox",("jumps ",("over",["foo",{"bar"}]))))))
print(z)
['re', 'cur', 'sion', ' ', 'foo', 'bar', 'baz']
['a', 'brown', 'fox', 'jumps ', 'over', 'foo', 'bar']
</code></pre>
| 0 |
2016-09-24T04:03:41Z
|
[
"python",
"python-3.x",
"recursion"
] |
Organizing records to classes
| 39,672,376 |
<p>I'm planning to develop a genetic algorithm for a series of acceleration records in a search to find optimum match with a target.</p>
<p>At this point my data is array-like with a unique ID column, X,Y,Z component info in the second, time in the third etc...</p>
<p>That being said each record has several "attributes". Do you think it would be beneficial to create a (records) class considering the fact I will want to to do a semi-complicated process with it as a next step?</p>
<p>Thanks</p>
| 1 |
2016-09-24T04:07:02Z
| 39,672,721 |
<p>I would say yes. Basically I want to:</p>
<ol>
<li>Take the unique set of data</li>
<li>Filter it so that just a subset is considered (filter parameters can be time of recording for example)</li>
<li>Use a genetic algorithm the filtered data to match on average a target.</li>
</ol>
<p>Step 3 is irrelevant to the post, I just wanted to give the big picture in order to make my question more clear.</p>
| 0 |
2016-09-24T05:03:00Z
|
[
"python",
"class"
] |
How to Invert SVG text with appropriate kerning?
| 39,672,397 |
<p>How can I invert (rotate 180 degrees) a text object so that the text is kerned appropriately?</p>
<p>my example uses python and the svgwrite package, but my question seems about any SVG. suppose using the following code:</p>
<pre><code>dwg = svgwrite.Drawing()
dwg.add(dwg.text(fullName, (int(width/2.),gnameHeight),
font_size=gnameFontSize, text_anchor="middle"))
</code></pre>
<p>generates some text looking like this:</p>
<p><a href="http://i.stack.imgur.com/pvQYb.png" rel="nofollow"><img src="http://i.stack.imgur.com/pvQYb.png" alt="enter image description here"></a></p>
<p><code>dwg.text()</code> objects accept a <code>rotate</code> parameter that is applied to all characters in a text string, so i've used the following coded to reverse the string first:</p>
<pre><code>pcRotate = [180]
ngap = 1
revFullName = fullName
rcl = []
for c in revFullName:
rcl.append(c)
for i in range(ngap):
rcl.append(' ')
rcl.reverse()
revFullName = ''.join(rcl)
dwg.add(dwg.text(revFullName, (int(width/2.),pcnameHeight),
font_size=gnameFontSize, text_anchor="middle", rotate=pcRotate))
</code></pre>
<p>but this produces the very ugly version below:</p>
<p><a href="http://i.stack.imgur.com/irO5B.png" rel="nofollow"><img src="http://i.stack.imgur.com/irO5B.png" alt="enter image description here"></a></p>
<p>and this is using an artificial space gap between characters to make it slightly less unreadable.</p>
<p>what's the best way to tap into whatever kerning is being used by standard text in this inverted situation?</p>
| 0 |
2016-09-24T04:09:47Z
| 39,674,079 |
<p>The <code>rotate</code> attribute of a <code><text></code> element is intended for situations where you want to rotate individual characters. If you want to rotate the whole text object then you should be using a <code>transform</code> instead.</p>
<p><a href="http://pythonhosted.org/svgwrite/classes/mixins.html#transform-mixin" rel="nofollow">http://pythonhosted.org/svgwrite/classes/mixins.html#transform-mixin</a></p>
| 1 |
2016-09-24T08:09:53Z
|
[
"python",
"svg",
"svgwrite"
] |
How to Invert SVG text with appropriate kerning?
| 39,672,397 |
<p>How can I invert (rotate 180 degrees) a text object so that the text is kerned appropriately?</p>
<p>my example uses python and the svgwrite package, but my question seems about any SVG. suppose using the following code:</p>
<pre><code>dwg = svgwrite.Drawing()
dwg.add(dwg.text(fullName, (int(width/2.),gnameHeight),
font_size=gnameFontSize, text_anchor="middle"))
</code></pre>
<p>generates some text looking like this:</p>
<p><a href="http://i.stack.imgur.com/pvQYb.png" rel="nofollow"><img src="http://i.stack.imgur.com/pvQYb.png" alt="enter image description here"></a></p>
<p><code>dwg.text()</code> objects accept a <code>rotate</code> parameter that is applied to all characters in a text string, so i've used the following coded to reverse the string first:</p>
<pre><code>pcRotate = [180]
ngap = 1
revFullName = fullName
rcl = []
for c in revFullName:
rcl.append(c)
for i in range(ngap):
rcl.append(' ')
rcl.reverse()
revFullName = ''.join(rcl)
dwg.add(dwg.text(revFullName, (int(width/2.),pcnameHeight),
font_size=gnameFontSize, text_anchor="middle", rotate=pcRotate))
</code></pre>
<p>but this produces the very ugly version below:</p>
<p><a href="http://i.stack.imgur.com/irO5B.png" rel="nofollow"><img src="http://i.stack.imgur.com/irO5B.png" alt="enter image description here"></a></p>
<p>and this is using an artificial space gap between characters to make it slightly less unreadable.</p>
<p>what's the best way to tap into whatever kerning is being used by standard text in this inverted situation?</p>
| 0 |
2016-09-24T04:09:47Z
| 39,712,870 |
<p>i'm posting this as a self-answer, only to make formatting more clear. two useful hints from @paul-lebeau happily acknowledged. </p>
<p>while the <code>svgwrite</code> package seems solid, its documentation is a bit thin. the two things i wish it had said:</p>
<ol>
<li>The <code>rotate</code> attribute of a <code><text></code> element is intended for situations where you want to rotate individual characters. If you want to rotate the whole text object then you should be using a <a href="http://pythonhosted.org/svgwrite/classes/mixins.html#transform-mixin" rel="nofollow">transform mixin</a> instead.</li>
<li>if you need to center the transformed text with respect to some center (other that the default current user coordinate system), add two additional parameters <code>xctr,yctr</code>. This differs from the doc which calls for a single <code>center</code> argument that is a (2-tuple).</li>
</ol>
<p>the correct code is:</p>
<pre><code>pcRotate = 'rotate(180,%s,%s)' % (int(width/2.),pcnameHeight)
textGroup = svgwrite.container.Group(transform=pcRotate)
textGroup.add(dwg.text(fullName, (int(width/2.),pcnameHeight),
font_size=gnameFontSize, text_anchor="middle"))
dwg.add(textGroup)
</code></pre>
| 0 |
2016-09-26T21:41:46Z
|
[
"python",
"svg",
"svgwrite"
] |
error when training im2txt model
| 39,672,514 |
<p>I was trying to train the <code>im2txt</code> model using Tensorflow that I just built from master branch,</p>
<p>I downloaded all the data sets it needed but when I run the training script:</p>
<pre><code>bazel-bin/im2txt/train \ --input_file_pattern="${MSCOCO_DIR}/train-?????-of-00256" \ --inception_checkpoint_file="${INCEPTION_CHECKPOINT}" \ --train_dir="${MODEL_DIR}/train" \ --train_inception=false \ --number_of_steps=1000000
</code></pre>
<p>It shows the following:</p>
<pre><code>Traceback (most recent call last):
File "/home/rvl224/models/im2txt/bazel-bin/im2txt/train.runfiles/im2txt/im2txt/train.py", line 111, in tf.app.run()
File "/home/rvl224/anaconda2/lib/python2.7/site-packages/tensorflow/python/platform/app.py", line 30, in run sys.exit(main(sys.argv[:1] + flags_passthrough))
File "/home/rvl224/models/im2txt/bazel-bin/im2txt/train.runfiles/im2txt/im2txt/train.py", line 65, in main model.build()
File "/home/rvl224/models/im2txt/bazel-bin/im2txt/train.runfiles/im2txt/im2txt/show_and_tell_model.py", line 358, in build self.build_inputs()
File "/home/rvl224/models/im2txt/bazel-bin/im2txt/train.runfiles/im2txt/im2txt/show_and_tell_model.py", line 165, in build_inputs image = self.process_image(encoded_image, thread_id=thread_id)
File "/home/rvl224/models/im2txt/bazel-bin/im2txt/train.runfiles/im2txt/im2txt/show_and_tell_model.py", line 119, in process_image image_format=self.config.image_format)
File "/home/rvl224/models/im2txt/bazel-bin/im2txt/train.runfiles/im2txt/im2txt/ops/image_processing.py", line 114, in process_image method=tf.image.ResizeMethod.BILINEAR)
TypeError: resize_images() got an unexpected keyword argument 'new_height'
</code></pre>
<p>Is it a problem related to the function <code>resize_images()</code> or I just done something wrong?</p>
<p>Thanks</p>
| 2 |
2016-09-24T04:31:13Z
| 39,682,387 |
<p><strong>Update:</strong> <a href="https://github.com/tensorflow/models/pull/448" rel="nofollow">fix applied</a></p>
<p>Sorry about this! The signature of the function <code>resize_images(...)</code> in TensorFlow was changed last week, which caused this breakage.</p>
<p>I will get a fix in for this shortly. If you would like to use the fix before then, you need to modify the file im2txt/im2txt/ops/image_processing.py.</p>
<p>Simply change this line:</p>
<pre><code>image = tf.image.resize_images(image,
new_height=resize_height,
new_width=resize_width,
method=tf.image.ResizeMethod.BILINEAR)
</code></pre>
<p>to this:</p>
<pre><code>image = tf.image.resize_images(image,
size=[resize_height, resize_width],
method=tf.image.ResizeMethod.BILINEAR)
</code></pre>
| 3 |
2016-09-25T00:50:39Z
|
[
"python",
"tensorflow",
"deep-learning"
] |
Generate non-singular sparse matrix in Python
| 39,672,554 |
<p>When a sparse matrix is generated by <code>scipy.sparse.rand</code>, it can be singular. In fact,the below code raises an error <code>"RuntimeError: superlu failure (singular matrix?) at line 100 in file scipy/sparse/linalg/dsolve/SuperLU/SRC/dsnode_bmod.c"</code>.</p>
<pre><code>dim = 20000
ratio = 0.000133
A = scipy.sparse.rand(dim,dim,ratio)
inv_sparse = scipy.sparse.linalg.inv(A)
</code></pre>
<p>Is there a way to generate non-singular sparse matrix?</p>
<p>What I really want to do is comparing performance (process time) of <code>scipy.sparse.linalg.inv</code> with <code>np.linalg.inv</code>. That's why I need generate random sparse matrix which is not singular.</p>
| 1 |
2016-09-24T04:37:28Z
| 39,676,379 |
<p>The density <code>ratio = 0.000133</code> of your matrix is very low. It means that about one item out of 7518 is non-null. Hence, the probability of each term to be null is about 7517/7518.</p>
<p>Each row is made of 20000 independent terms. So the probability for a row to be null is (7517/7518)^20000=6.99%. Hence, the probability for a row to be non-null is 1-(7517/7518)^20000=93.0%.</p>
<p>Then, the matrix is made of 20000 rows. The rows can be considered as being independent. Hence, the probability that the matrix does not contain null rows is (1-(7517/7518)^20000)^20000=(93.0%)^20000. This probability is very low. </p>
<p>As the matrix is likely to contain a null row, it is often singular.</p>
<p>Moreover, due to the the limited precision of floating-point numbers, programs often consider ill-conditionned matrices as singular. Indeed, in such cases, the computed inverse would be highly unprecise and meaningless.</p>
<p>Finally, to compare the inverse function, it may be better to use matrices known to be invertible... At least, you could try to increase the density so that the probability of a null row becomes very low.</p>
| 1 |
2016-09-24T12:32:45Z
|
[
"python",
"numpy",
"matrix",
"scipy"
] |
what could cause html and script to behave different across iterations of a for loop?
| 39,672,565 |
<p>I'm trying to build a side navigation bar where categories are listed and upon clicking a category a respective sub list of subcategories is shown right below the category. And if the category is clicked again, the sub list contracts.</p>
<p>So I'm running a loop across category objects. Inside this outer loop, I'm including a an inner loop to list subcategories and a script that hides the submenu and slidetoggles it only when a category is clicked. I'm using django template tags to dynamically assign class names for my html elements and also to refer to them in the script. So after all for loop iterations, there is a list of subcategory and a dedicated script for each category and they have unique class names so no chance of an overlap. So the weird part is, this works perfectly for most categories, but some of the categories and their submenu remain open and when clicked on the category the page reloads.</p>
<p>I don't get it, what could cause the exact same code (run in a for loop) to behave so differently?</p>
<p>This is my code:</p>
<pre><code>{% load staticfiles %}
{% load i18n pybb_tags forumindexlistbycat %}
{% catindexlist as catindexlisted %}
{% block body %}<div class="col-sm-12 col-md-12 col-xs-12 col-lg-12 body-container leftsidenavigator" style="margin-top:15px;">
<div class="col-sm-12 col-md-12 col-xs-12 col-lg-12 leftsidenavigator-inner" style="padding:0px;">
<h2><center>Categories</center></h2>
<ul class="catindexlist catlistcat nav-collapse89">
{% for category in catindexlisted %}
<li class="catindexlistitem category-name{{category.name}}{{category.name}}" style="font-weight:600;padding-right:20px;"><a href="">{{category.name}}</a></li>
<ul style="padding:0px;" class="nav-collapse88">
{% for forum in category|forumindexlistbycat %}
<li class="catlistforum{{category.name}}{{category.name}} forum-name" style="padding-right:10px;"><a href="{{ forum.get_absolute_url }}">{{forum.name}}</a></li>
{% endfor %}</ul><script>
$(function() {
$(".catlistforum{{category.name}}{{category.name}}").hide();
$(".category-name{{category.name}}{{category.name}} a").click(function(e) {
e.preventDefault();
$(".catlistforum{{category.name}}{{category.name}}").slideToggle();
if(!($(this).parent('li').siblings('div').children('ul').children('div').is(":visible"))){
$(this).parent('li').siblings('div').children('ul').children('div').is(":visible").slideToggle();
}});
})
</script>
{% endfor %}
</ul>
</div>
</div>
{% endblock %}
{% block theme_script %}<script src="{% static "pinax/js/theme.js" %}"></script>{% endblock %}
</code></pre>
| 10 |
2016-09-24T04:39:26Z
| 39,744,460 |
<p>Is there any chance that the category name contains spaces?</p>
<p>Just a tip: You are not using good practice in your code. IMO you should get your javascript code outside of the forloop and remove <code>{{ category_name }}</code> classes.
<code>catindexlistitem</code> on click should toggle <strong>hidden</strong> class (i noticed you use bootstrap) to it's child ul. </p>
<p>By adding a more generic event listener you simplify your code and by using css you improve performance. In case you want to add effects you still can with css3.</p>
| 1 |
2016-09-28T10:11:36Z
|
[
"javascript",
"jquery",
"python",
"django",
"django-templates"
] |
what could cause html and script to behave different across iterations of a for loop?
| 39,672,565 |
<p>I'm trying to build a side navigation bar where categories are listed and upon clicking a category a respective sub list of subcategories is shown right below the category. And if the category is clicked again, the sub list contracts.</p>
<p>So I'm running a loop across category objects. Inside this outer loop, I'm including a an inner loop to list subcategories and a script that hides the submenu and slidetoggles it only when a category is clicked. I'm using django template tags to dynamically assign class names for my html elements and also to refer to them in the script. So after all for loop iterations, there is a list of subcategory and a dedicated script for each category and they have unique class names so no chance of an overlap. So the weird part is, this works perfectly for most categories, but some of the categories and their submenu remain open and when clicked on the category the page reloads.</p>
<p>I don't get it, what could cause the exact same code (run in a for loop) to behave so differently?</p>
<p>This is my code:</p>
<pre><code>{% load staticfiles %}
{% load i18n pybb_tags forumindexlistbycat %}
{% catindexlist as catindexlisted %}
{% block body %}<div class="col-sm-12 col-md-12 col-xs-12 col-lg-12 body-container leftsidenavigator" style="margin-top:15px;">
<div class="col-sm-12 col-md-12 col-xs-12 col-lg-12 leftsidenavigator-inner" style="padding:0px;">
<h2><center>Categories</center></h2>
<ul class="catindexlist catlistcat nav-collapse89">
{% for category in catindexlisted %}
<li class="catindexlistitem category-name{{category.name}}{{category.name}}" style="font-weight:600;padding-right:20px;"><a href="">{{category.name}}</a></li>
<ul style="padding:0px;" class="nav-collapse88">
{% for forum in category|forumindexlistbycat %}
<li class="catlistforum{{category.name}}{{category.name}} forum-name" style="padding-right:10px;"><a href="{{ forum.get_absolute_url }}">{{forum.name}}</a></li>
{% endfor %}</ul><script>
$(function() {
$(".catlistforum{{category.name}}{{category.name}}").hide();
$(".category-name{{category.name}}{{category.name}} a").click(function(e) {
e.preventDefault();
$(".catlistforum{{category.name}}{{category.name}}").slideToggle();
if(!($(this).parent('li').siblings('div').children('ul').children('div').is(":visible"))){
$(this).parent('li').siblings('div').children('ul').children('div').is(":visible").slideToggle();
}});
})
</script>
{% endfor %}
</ul>
</div>
</div>
{% endblock %}
{% block theme_script %}<script src="{% static "pinax/js/theme.js" %}"></script>{% endblock %}
</code></pre>
| 10 |
2016-09-24T04:39:26Z
| 39,744,628 |
<p>Try writing the javascript function after the outer for loop, sometimes this might overlap and redirect. And also try providing spaces between the names of category inside "li".</p>
| 0 |
2016-09-28T10:18:01Z
|
[
"javascript",
"jquery",
"python",
"django",
"django-templates"
] |
what could cause html and script to behave different across iterations of a for loop?
| 39,672,565 |
<p>I'm trying to build a side navigation bar where categories are listed and upon clicking a category a respective sub list of subcategories is shown right below the category. And if the category is clicked again, the sub list contracts.</p>
<p>So I'm running a loop across category objects. Inside this outer loop, I'm including a an inner loop to list subcategories and a script that hides the submenu and slidetoggles it only when a category is clicked. I'm using django template tags to dynamically assign class names for my html elements and also to refer to them in the script. So after all for loop iterations, there is a list of subcategory and a dedicated script for each category and they have unique class names so no chance of an overlap. So the weird part is, this works perfectly for most categories, but some of the categories and their submenu remain open and when clicked on the category the page reloads.</p>
<p>I don't get it, what could cause the exact same code (run in a for loop) to behave so differently?</p>
<p>This is my code:</p>
<pre><code>{% load staticfiles %}
{% load i18n pybb_tags forumindexlistbycat %}
{% catindexlist as catindexlisted %}
{% block body %}<div class="col-sm-12 col-md-12 col-xs-12 col-lg-12 body-container leftsidenavigator" style="margin-top:15px;">
<div class="col-sm-12 col-md-12 col-xs-12 col-lg-12 leftsidenavigator-inner" style="padding:0px;">
<h2><center>Categories</center></h2>
<ul class="catindexlist catlistcat nav-collapse89">
{% for category in catindexlisted %}
<li class="catindexlistitem category-name{{category.name}}{{category.name}}" style="font-weight:600;padding-right:20px;"><a href="">{{category.name}}</a></li>
<ul style="padding:0px;" class="nav-collapse88">
{% for forum in category|forumindexlistbycat %}
<li class="catlistforum{{category.name}}{{category.name}} forum-name" style="padding-right:10px;"><a href="{{ forum.get_absolute_url }}">{{forum.name}}</a></li>
{% endfor %}</ul><script>
$(function() {
$(".catlistforum{{category.name}}{{category.name}}").hide();
$(".category-name{{category.name}}{{category.name}} a").click(function(e) {
e.preventDefault();
$(".catlistforum{{category.name}}{{category.name}}").slideToggle();
if(!($(this).parent('li').siblings('div').children('ul').children('div').is(":visible"))){
$(this).parent('li').siblings('div').children('ul').children('div').is(":visible").slideToggle();
}});
})
</script>
{% endfor %}
</ul>
</div>
</div>
{% endblock %}
{% block theme_script %}<script src="{% static "pinax/js/theme.js" %}"></script>{% endblock %}
</code></pre>
| 10 |
2016-09-24T04:39:26Z
| 39,745,007 |
<p>My advice would be to clean up your JS by making a single function to handle all the clicks. You are already using class on clicks, so why not have one function handle all the clicks?</p>
<pre><code><script>
$(function() {
// Hide all elements with a class starting with catlistforum
$('[class^="catlistforum"]').hide();
// Assign clicks to all links whose parent has a class starting with catlistforum
// (Though why are you hiding the parents? How will they click the links?)
$('[class^="catlistforum"] a').on("click", function(e) {
e.preventDefault();
// Delegate slideToggle to each click target
$(e.target).slideToggle();
// This seems redundant, but hopefully it will behave the way you want it to behave
if(!($(e.target).parent('li').siblings('div').children('ul').children('div').is(":visible"))) {
$(e.target).parent('li').siblings('div').children('ul').children('div').is(":visible").slideToggle();
}
});
})
</script>
</code></pre>
<p>Of course, if I were you, I would just define two new classes (e.g. <code>catlistforum-hide</code> and <code>catlistforum-toggle</code>) which I would apply to all the elements I wanted to hide and toggle, respectively.</p>
| 0 |
2016-09-28T10:35:29Z
|
[
"javascript",
"jquery",
"python",
"django",
"django-templates"
] |
what could cause html and script to behave different across iterations of a for loop?
| 39,672,565 |
<p>I'm trying to build a side navigation bar where categories are listed and upon clicking a category a respective sub list of subcategories is shown right below the category. And if the category is clicked again, the sub list contracts.</p>
<p>So I'm running a loop across category objects. Inside this outer loop, I'm including a an inner loop to list subcategories and a script that hides the submenu and slidetoggles it only when a category is clicked. I'm using django template tags to dynamically assign class names for my html elements and also to refer to them in the script. So after all for loop iterations, there is a list of subcategory and a dedicated script for each category and they have unique class names so no chance of an overlap. So the weird part is, this works perfectly for most categories, but some of the categories and their submenu remain open and when clicked on the category the page reloads.</p>
<p>I don't get it, what could cause the exact same code (run in a for loop) to behave so differently?</p>
<p>This is my code:</p>
<pre><code>{% load staticfiles %}
{% load i18n pybb_tags forumindexlistbycat %}
{% catindexlist as catindexlisted %}
{% block body %}<div class="col-sm-12 col-md-12 col-xs-12 col-lg-12 body-container leftsidenavigator" style="margin-top:15px;">
<div class="col-sm-12 col-md-12 col-xs-12 col-lg-12 leftsidenavigator-inner" style="padding:0px;">
<h2><center>Categories</center></h2>
<ul class="catindexlist catlistcat nav-collapse89">
{% for category in catindexlisted %}
<li class="catindexlistitem category-name{{category.name}}{{category.name}}" style="font-weight:600;padding-right:20px;"><a href="">{{category.name}}</a></li>
<ul style="padding:0px;" class="nav-collapse88">
{% for forum in category|forumindexlistbycat %}
<li class="catlistforum{{category.name}}{{category.name}} forum-name" style="padding-right:10px;"><a href="{{ forum.get_absolute_url }}">{{forum.name}}</a></li>
{% endfor %}</ul><script>
$(function() {
$(".catlistforum{{category.name}}{{category.name}}").hide();
$(".category-name{{category.name}}{{category.name}} a").click(function(e) {
e.preventDefault();
$(".catlistforum{{category.name}}{{category.name}}").slideToggle();
if(!($(this).parent('li').siblings('div').children('ul').children('div').is(":visible"))){
$(this).parent('li').siblings('div').children('ul').children('div').is(":visible").slideToggle();
}});
})
</script>
{% endfor %}
</ul>
</div>
</div>
{% endblock %}
{% block theme_script %}<script src="{% static "pinax/js/theme.js" %}"></script>{% endblock %}
</code></pre>
| 10 |
2016-09-24T04:39:26Z
| 39,844,080 |
<p>The most probable cause is the use of {{category.name}} for class names. </p>
<p>The code snippet doesn't show what values is accepted for category.name and my guess is it can be user input?
See <a href="http://www.w3schools.com/tags/att_global_class.asp" rel="nofollow">naming rules</a> in section Attribute Values what is valid for class names.</p>
<p>It can be solved using template tag <a href="https://docs.djangoproject.com/es/1.10/ref/templates/builtins/#slugify" rel="nofollow">slugify</a> ({{category.name|slugify}}) but my recommendation is to try re-design the solution a bit.</p>
| 1 |
2016-10-04T04:16:42Z
|
[
"javascript",
"jquery",
"python",
"django",
"django-templates"
] |
Most pythonic way of checking if a Key is in a dictionary and Value is not None
| 39,672,602 |
<p>I am using <code>flask</code> and <code>flask_restful</code> and has something like</p>
<pre><code>self.reqparse = reqparse.RequestParser()
self.reqparse.add_argument('OptionalArg', type=str, default=None)
self.reqparse.add_argument('OptionalArg2', type=str, default=None)
self.__args = self.reqparse.parse_args()
if 'OptionalArg' in self.__args and self.__args['OptionalArg'] is not None:
# Do something with the OptionalArg only
pass
else:
# Do something with all the arguments that are not None.
pass
</code></pre>
<p><a href="http://stackoverflow.com/a/7771511/1809168">Most relevant answer I found.</a></p>
<p>Though the question was asked a couple of years back, I was wondering if there is a much more pythonic way of checking if a <code>Key</code> is in a dictionary and <code>Value</code> is not <code>None</code>.</p>
<p>The reason I mentioned <code>flask</code> and <code>flask_restful</code> is to justify the initialization of <code>Keys</code> with <code>None</code> values within my dictionary.</p>
| 0 |
2016-09-24T04:45:02Z
| 39,672,620 |
<p>Just use <code>dict.get</code> method with optional <code>default</code> parameter. It returns <code>d[key]</code> if <code>key</code> exists in the dictionary <code>d</code> and <code>default</code> value otherwise:</p>
<pre><code>In [1]: d = {1: 'A', 2: None}
In [2]: d.get(1)
Out[2]: 'A'
In [3]: d.get(2)
In [4]: d.get(1) is not None
Out[4]: True
In [5]: d.get(2) is not None
Out[5]: False
In [6]: d.get(3) is not None
Out[6]: False
</code></pre>
<p>For your case:</p>
<pre><code>if self.__args.get('OptionalArg') is not None:
# Do something with the OptionalArg only
pass
else:
# Do something with all the arguments that are not None.
pass
</code></pre>
| 1 |
2016-09-24T04:47:45Z
|
[
"python",
"dictionary"
] |
Read lines from two different files and print line number if match is found [edited]
| 39,672,606 |
<p>I have two files. I want to read each line from file1 and check if it matches with any line in file2. I want this to repeat for each line in file1, and print the line number of file1 whose match was found in file2. So far I have this. It works for test files of 4-5 lines each but when working on large files of over 60k lines, I am getting a blank output</p>
<pre><code> num=0
f1 = open('pdataf.txt', 'r')
f2 = open('splitc.txt', 'r')
fo = open('op.txt', 'w')
for line1 in f1:
for line2 in f2:
num=num+1
if line1==line2:
nummy=str(num)
fo.write(nummy)
fo.write('\n')
break
continue
f1.close()
f2.close()
</code></pre>
| 0 |
2016-09-24T04:45:39Z
| 39,672,778 |
<p>Firstly, you have a syntax error on line 8, replace the line with <code>print(num)</code>.
I don't have a lot of information about your problem, it might be a good idea to clarify, but what I suspect happens is that you have an end line character <code>"\n"</code> at the end of the lines you read.</p>
<p>To get rid of this character, you can use the <code>rstrip()</code> method as discussed in <a href="http://stackoverflow.com/questions/275018/how-can-i-remove-chomp-a-newline-in-python">this topic</a>.</p>
<p>So, I would suggest replacing your code by :</p>
<pre><code>num=0
f1 = open('s.txt', 'r')
f2 = open('p.txt', 'r')
for line1 in f1:
line1 = line1.rstrip()
for line2 in f2:
line2 = line2.rstrip()
if line1==line2:
num=num+1
print(num)
f1.close()
f2.close()
</code></pre>
| 0 |
2016-09-24T05:10:34Z
|
[
"python",
"python-2.7",
"text"
] |
(Python) How to convert my code to python 3 from 2.7
| 39,672,626 |
<p>I'm trying to build a basic website crawler, in Python. However, the code that I've gathered from this website <a href="http://null-byte.wonderhowto.com/news/basic-website-crawler-python-12-lines-code-0132785/" rel="nofollow">here</a> is for python 2.7. I'm wondering how I can code this for python 3 or greater. I've began to try and convert it, but I keep running into errors.</p>
<pre><code>import re
import urllib
textfile = open('depth_1.txt', 'wt')
print("Enter the URL you wish to crawl..")
print('Usage - "http://phocks.org/stumble/creepy/" <-- With the double quotes')
myurl = input("@> ")
for i in re.findall('''href=["'](.[^"']+)["']''', urllib.urlopen(myurl).read(), re.I):
print(i)
for ee in re.findall('''href=["'](.[^"']+)["']''', urllib.urlopen(i).read(), re.I):
print(ee)
textfile.write(ee+'\n')
textfile.close()
</code></pre>
| 1 |
2016-09-24T04:48:09Z
| 39,672,682 |
<h1>Prepare your Python2 code</h1>
<p>Say <code>2.py</code></p>
<pre><code>import re
import urllib
textfile = open('depth_1.txt', 'wt')
print("Enter the URL you wish to crawl..")
print('Usage - "http://phocks.org/stumble/creepy/" <-- With the double quotes')
myurl = input("@> ")
for i in re.findall('''href=["'](.[^"']+)["']''', urllib.urlopen(myurl).read(), re.I):
print(i)
for ee in re.findall('''href=["'](.[^"']+)["']''', urllib.urlopen(i).read(), re.I):
print(ee)
textfile.write(ee+'\n')
textfile.close()
</code></pre>
<h1>Convert it with <code>2to3</code></h1>
<pre><code>2to3 -w 2.py
</code></pre>
<h1>Now look into the directory with <code>dir</code> or <code>ls</code></h1>
<pre><code>> dir
2016-09-24 01:53 533 2.py
2016-09-24 01:51 475 2.py.bak
</code></pre>
<p><code>2.py.bak</code> is your original code and <code>2.py</code> is Python 3 code.</p>
<h2>See what changes have been made</h2>
<pre><code>import re
import urllib.request, urllib.parse, urllib.error
textfile = open('depth_1.txt', 'wt')
print("Enter the URL you wish to crawl..")
print('Usage - "http://phocks.org/stumble/creepy/" <-- With the double quotes')
myurl = eval(input("@> "))
for i in re.findall('''href=["'](.[^"']+)["']''', urllib.request.urlopen(myurl).read(), re.I):
print(i)
for ee in re.findall('''href=["'](.[^"']+)["']''', urllib.request.urlopen(i).read(), re.I):
print(ee)
textfile.write(ee+'\n')
textfile.close()
</code></pre>
<p><strong>This works if you are using only built-ins and standard modules.</strong> In your case, it's ok.</p>
| 1 |
2016-09-24T04:56:51Z
|
[
"python",
"python-2.7",
"python-3.x"
] |
How to translate strings in javascript written in script tags of html in django?
| 39,672,636 |
<p>Hi I am translating a website in hungarian, I have problems with alerts and confirm strings that i have in my templates. I am using <code>gettext('')</code> but these strings are not appearing in po files</p>
<p>my urls.py</p>
<pre><code>urlpatterns = patterns('',
url(r'^jsi18n/$', javascript_catalog, js_info_dict, name='javascript-catalog'),
</code></pre>
<p>I have created po file django.po by running makemessages it has all the strings marked as trans in templates and also strings from <code>*.py</code> files.
then
I have run following command </p>
<pre><code>django-admin.py makemessages -d djangojs -l hu_HU
</code></pre>
<p>its creating <code>djangojs.po</code>.</p>
<p>The strings appearing in this file are all from *.js files in my static folder.</p>
<p>But how do i have my strings used in alerts and confirms that are written in my templates.</p>
<p>here are snippets from my templates.</p>
<pre><code><script>
if($('#id_action').val()=='DEL'){
if(confirm(gettext('Are you sure you want to delete selected author(s) ?'))){
flag_action=true;
}
}
</script>
</code></pre>
<p>In my template i also have something like this which is not appearing in po files either.</p>
<pre><code><li>
<a onclick="if(confirm(gettext('Are you sure you want to delete the selected author?'))){filter_content({{auth.id}},'DEL');return false;}" href="javascript:void(0)">
{% trans 'Delete' %}
</a>
</li>
</code></pre>
<p>The string in gettext is not appearing in any po.</p>
<p>I have included the following in my templates</p>
<pre><code><script type="text/javascript" src="{% url 'javascript-catalog' %}"></script>
</code></pre>
| -1 |
2016-09-24T04:49:56Z
| 39,672,989 |
<blockquote>
<p>Use this </p>
</blockquote>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var alert_var = {% blocktrans %}"Are you sure you want to delete selected author(s) ?" {% endblocktrans %};</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- begin snippet: js hide: false console: true babel: false --></code></pre>
</div>
</div>
</p>
<blockquote>
<p>then use this variable where ever you need</p>
</blockquote>
| 0 |
2016-09-24T05:48:16Z
|
[
"javascript",
"python",
"django"
] |
Extracting column from numpy array - unhashable array
| 39,672,650 |
<p>I have a file of experimental data that I have parsed into a numpy array. I am attempting to extract the first column of the array into a variable using:</p>
<pre><code>Thermo_Col = df[:,[0]]
</code></pre>
<p>where <code>Thermo_Col</code> is the column of temperatures and df is the numpy array</p>
<p>and I get an error</p>
<pre><code>TypeError: unhashable type
</code></pre>
<p>Help</p>
| 0 |
2016-09-24T04:52:00Z
| 39,672,674 |
<p>I think df is not a numpy array, but a DataFrame, try this:</p>
<pre><code>df.iloc[:, [0]]
</code></pre>
| 0 |
2016-09-24T04:55:16Z
|
[
"python",
"numpy"
] |
Power Function using Loops
| 39,672,692 |
<p>I just started Python 2.7.
I am trying to make a program that executes power function (using loops) without using <strong>import. math</strong>
I think I got it except my program does not execute negative exponents.
The output only comes out as 1.
Here is what I have so far. </p>
<pre><code>decimal=float(input('Enter the base number:'))
integer=int(input('Enter the exponent number:'))
def power_function(decimal, integer):
num=1
for function in range(integer):
if integer>0:
num=num*decimal
if integer<0:
num=1/(num*decimal)
return num
print power_function(decimal, integer)
</code></pre>
| 0 |
2016-09-24T04:58:23Z
| 39,672,777 |
<p>Fixing based on range of negative value.</p>
<pre><code>def power_function(decimal, integer):
num=1
if integer>0:
for function in range(integer):
num=num*decimal
if integer<0:
num=1.0 # force floating point division
for function in range(-integer):
num=num/decimal
return num
</code></pre>
| 2 |
2016-09-24T05:10:33Z
|
[
"python",
"python-2.7",
"function",
"loops"
] |
Power Function using Loops
| 39,672,692 |
<p>I just started Python 2.7.
I am trying to make a program that executes power function (using loops) without using <strong>import. math</strong>
I think I got it except my program does not execute negative exponents.
The output only comes out as 1.
Here is what I have so far. </p>
<pre><code>decimal=float(input('Enter the base number:'))
integer=int(input('Enter the exponent number:'))
def power_function(decimal, integer):
num=1
for function in range(integer):
if integer>0:
num=num*decimal
if integer<0:
num=1/(num*decimal)
return num
print power_function(decimal, integer)
</code></pre>
| 0 |
2016-09-24T04:58:23Z
| 39,672,813 |
<p>Simple fix is to use <code>abs(integer)</code> for your <code>range</code>:</p>
<pre><code>def power_function(decimal, integer):
num = 1
for function in range(abs(integer)):
num = num*decimal if integer > 0 else num/decimal
return num
power_function(2, 2)
# 4
power_function(2, -2)
# 0.25
</code></pre>
<p>Or just using reduce:</p>
<pre><code>def power_function(decimal, integer):
op = (lambda a, b: a*b) if integer > 0 else (lambda a, b: a/b)
return reduce(op, [decimal]*abs(integer), 1)
power_function(3, 3)
# 27
</code></pre>
| 0 |
2016-09-24T05:17:20Z
|
[
"python",
"python-2.7",
"function",
"loops"
] |
Python dictionary command to input
| 39,672,731 |
<pre><code>commands = { 'a': 'far' }
while(1 == 1):
print ("{} to{}.".format(commands.key, commands.value[0])
(input("~~~~~Press a key.~~~~~"))
if input(key in commands.keys()
commands.value[1]
if not
print("Not a valid command.")
def far():
print (2 + 2)
</code></pre>
<p>the entire thing seems to be full of syntax errors</p>
| 0 |
2016-09-24T05:04:00Z
| 39,673,081 |
<p>@idjaw's comment is pretty right. It's got more errors than lines of code, which makes me think you need to work on some of the statements in isolation until they make sense, before trying to combine them all together.</p>
<p>Here's a crunch through of syntax / structural errors round 1:</p>
<pre><code># These two are fine
commands = { 'a': 'far' }
while(1 == 1):
# This is broken several times, first print ( ... ) needs matching
# open/close parentheses and you open two but only close one.
# It's missing a close parenthesis at the end.
# Second, commands.key is not a valid thing. commands.keys would be
# but it's a function so it would need to be commands.keys().
# Third, commands.value is not valid either. commands.value() would be.
print ("{} to{}.".format(commands.key, commands.value[0])
# This is valid code, but why is it in parentheses?
(input("~~~~~Press a key.~~~~~"))
# This is broken - input ( ... ) is missing a close parenthesis at the end
# It's also broken because `if` statements need a colon at the end.
# but how come you get commands.keys() right here?
if input(key in commands.keys()
# This is broken - after an `if` statement, code needs to be indented.
# It's also broken because .value isn't a thing.
# and it's broken because there is only one value in the dictionary
# so asking for the second one will crash.
# It's also broken because just stating the second value won't magically
# call a function which matches the string in the value
commands.value[1]
# This is broken - if not ... what?
# and it's missing a colon at the end.
if not
print("Not a valid command.")
def far():
print (2 + 2)
</code></pre>
<p>OK, fix those errors, round 2:</p>
<pre><code># if you put `far` definition at the end, it hasn't been defined
# yet when you try to call it, so it needs to be higher up.
def far():
print (2 + 2)
commands = { 'a': 'far' }
# This is fine, but it would be more idiomatic as `while True:`
while(1 == 1):
# This is still broken, it will format all keys but only one value.
# Even if it formatted all the values it would be broken because
# it would output one line like:
#
# "dict_keys(['a', 'b']) to dict_values(['far', 'near'])"
#
# it needs to be in a loop, outputting one of each at a time.
print ("{} to{}.".format(commands.keys(), commands.values()[0]))
# suspicious - request input but do nothing with the input?
input("~~~~~Press a key.~~~~~")
# This is broken - `key` is not defined here
# and if it was defined it would be broken because `x in y` tests
# if an item is in a collection, and returns True/False
# so this prompts the user with the prompt: "False"
# It's broken again because the result of the input, a string,
# is not stored so `if` is only testing if it's an empty string or not
# and you don't know what they typed in.
if input(key in commands.keys()):
# This is fundamentally unfixable until the design changes,
# also needs a change of approach
commands.values()[0]
# Still broken - whatever you put here won't make sense since you aren't
# storing the user input. Either need to do that, or use `else`
if not something:
print("Not a valid command.")
</code></pre>
<p>Correct those things and you get something like:</p>
<pre><code># define a function to work with
def far():
print (2 + 2)
# mapping of /keyboard keys/ to function names
commands = { 'a': 'far' }
# loop forever
while True:
# Loop over the /dictionary keys/ and /dictionary values/
# printing each one
for keyboard_key, command_name in commands.items():
print("{} to {}".format(keyboard_key, command_name))
# ask the user to type something, and store the return value
entry = input("~~~~~Press a key.~~~~~")
# check if what they /entered/ is in the commands dictionary
# and get the command, or get False if it's not there
command = commands.get(entry, False)
# if it did get something...
if command:
# lookup the function of that name in the local namespace and call it.
# this is ugly but it's the price to pay for
# calling a function when you only have a string
# representing its name.
# Using the function as the dictionary value
# would be more Pythonic but you'd have to change the way
# you prompt the user
locals()[command]()
# otherwise print an error
else:
print("Not a valid command.")
</code></pre>
<p>Try online at repl.it: <a href="https://repl.it/Dgeh" rel="nofollow">https://repl.it/Dgeh</a> </p>
| 2 |
2016-09-24T06:03:08Z
|
[
"python",
"python-3.x"
] |
Selectively flattening a nested JSON structure
| 39,672,892 |
<p>So this is a problem that I have no idea where to even start so even just a pointer in the right direction would be great.</p>
<p>So I have data that looks like so:</p>
<pre><code>data = {
"agg": {
"agg1": [
{
"keyWeWant": "*-20.0",
"asdf": 0,
"asdf": 20,
"asdf": 14,
"some_nested_agg": [
{
"keyWeWant2": 20,
"to": 25,
"doc_count": 4,
"some_nested_agg2": {
"count": 7,
"min": 2,
"max": 5,
"keyWeWant3": 2.857142857142857,
"sum": 20
}
},
{
"keyWeWant2": 25,
"to": 30,
"doc_count": 10,
"some_nested_agg2": {
"count": 16,
"min": 2,
"max": 10,
"keyWeWant3": 6.375,
"sum": 102
}
}
]
},
{
...
},
{
...
},
...
]
}
}
</code></pre>
<p>Now from the example, within 'agg' there are N 'agg1' results, within each 'agg1' result there is a 'keyWeWant'. Each 'agg1' result also has a list of 'some_nested_agg' results which each contain a 'keyWeWant2'. Each 'keyWeWant2' value is associated a single 'keyWeWant' value somewhere up in the hierarchy. Similarly each 'keyWeWant2' also contains a set of results for 'some_nested_agg2' (not a list but rather a map this time). Each of the set of results contains a 'keyWeWant3'.</p>
<p>Now I want to flatten this structure while still preserving the association between 'keyWeWant', 'keyWeWant2', and 'keyWeWant3' (I'm essentially de-normalizing) to get something like so:</p>
<p>What I want the function to look like:</p>
<pre><code>[
{
"keyWeWant" : "*-20",
"keyWeWant2" : 20,
"keyWeWant3" : 2.857142857142857
},
{
"keyWeWant" : "*-20",
"keyWeWant2" : 25,
"keyWeWant3" : 6.375
},
{
...
},
{
...
}
]
</code></pre>
<p>This is an example where there is only depth 3 but there could be arbitrary depth with some nested values being lists and some being arrays/list.</p>
<p>What I would like to do is write a function to take in the keys I want and where to find them, and then go get the keys and denormalize.</p>
<p>Something that looks like:</p>
<pre><code>function_name(data_map, {
"keyWeWant" : ['agg', 'agg1'],
"keyWeWant2" : ['agg', 'agg1', 'some_nested_agg'],
"keyWeWant" : ['agg', 'agg1', 'some_nested_agg', 'some_nested_agg2']
})
</code></pre>
<p>Any ideas? I'm familiar with Java, Clojure, Java-script, and Python and am just looking for a way to solve this that's relatively simple.</p>
| 0 |
2016-09-24T05:31:25Z
| 39,678,562 |
<p>There is probably a better way to solve this particular problem (using some ElasticSearch library or something), but here's a solution in Clojure using your requested input and output data formats. </p>
<p>I placed this test data in a file called <code>data.json</code>:</p>
<pre><code>{
"agg": {
"agg1": [
{
"keyWeWant": "*-20.0",
"asdf": 0,
"asdf": 20,
"asdf": 14,
"some_nested_agg": [
{
"keyWeWant2": 20,
"to": 25,
"doc_count": 4,
"some_nested_agg2": {
"count": 7,
"min": 2,
"max": 5,
"keyWeWant3": 2.857142857142857,
"sum": 20
}
},
{
"keyWeWant2": 25,
"to": 30,
"doc_count": 10,
"some_nested_agg2": {
"count": 16,
"min": 2,
"max": 10,
"keyWeWant3": 6.375,
"sum": 102
}
}]
}]}
}
</code></pre>
<p>Then <a href="https://github.com/dakrone/cheshire" rel="nofollow">Cheshire JSON library</a> parses the data to a Clojure data structure:</p>
<pre><code>(use '[cheshire.core :as cheshire])
(def my-data (-> "data.json" slurp cheshire/parse-string))
</code></pre>
<p>Next the paths to get are defined as follows:</p>
<pre><code>(def my-data-map
{"keyWeWant" ["agg", "agg1"],
"keyWeWant2" ["agg", "agg1", "some_nested_agg"],
"keyWeWant3" ["agg", "agg1", "some_nested_agg", "some_nested_agg2"]})
</code></pre>
<p>It is your <code>data_map</code> above without ":", single quotes changed to double quotes and the last "keyWeWant" changed to "keyWeWant3".</p>
<p><code>find-nested</code> below has the semantics of Clojure's <a href="https://clojuredocs.org/clojure.core/get-in" rel="nofollow"><code>get-in</code></a>, only then it works on maps with vectors, and returns all values instead of one.
When <code>find-nested</code> is given a search vector it finds all values in a nested map where some values can consist of a vector with a list of maps. Every map in the vector is checked.</p>
<pre><code>(defn find-nested
"Finds all values in a coll consisting of maps and vectors.
All values are returned in a tree structure:
i.e, in your problem it returns (20 25) if you call it with
(find-nested ['agg', 'agg1', 'some_nested_agg', 'keyWeWant2']
my-data).
Returns nil if not found."
[ks c]
(let [k (first ks)]
(cond (nil? k) c
(map? c) (find-nested (rest ks) (get c k))
(vector? c) (if-let [e (-> c first (get k))]
(if (string? e) e ; do not map over chars in str
(map (partial find-nested (rest ks)) e))
(find-nested ks (into [] (rest c)))) ; create vec again
:else nil)))
</code></pre>
<p><code>find-nested</code> finds the values for a search path:</p>
<pre><code>(find-nested ["agg", "agg1", "some_nested_agg", "keyWeWant2"] my-data)
; => (20 25)
</code></pre>
<p>If all the paths towards the "keyWeWant's are mapped over <code>my-data</code> these are the slices of a <code>tree</code>:</p>
<blockquote>
<p>(*-20.0<br>
(20 25)<br>
(2.857142857142857 6.375))</p>
</blockquote>
<p>The structure you ask for (all end results with paths getting there) can be obtained from this <code>tree</code> in <code>function-name</code> like this:</p>
<pre><code>(defn function-name
"Transforms data d by finding (nested keys) via data-map m in d and
flattening the structure."
[d m]
(let [tree (map #(find-nested (conj (second %) (first %)) d) m)
leaves (last tree)
leaf-indices (range (count leaves))
results (for [index leaf-indices]
(map (fn [slice]
(if (string? slice)
slice
(loop [node (nth slice index)]
(if node
node
(recur (nth slice (dec index)))))))
tree))
results-with-paths (mapv #(zipmap (keys m) %) results)
json (cheshire/encode results-with-paths)]
json))
</code></pre>
<p><code>results</code> uses a <a href="https://clojuredocs.org/clojure.core/loop" rel="nofollow"><code>loop</code></a> to step back if a <code>leaf-index</code> is larger than that particular slice. I think it will work out for deeper nested structures as well -if a next slice is always double the size of a previous slice or the same size it should work out -, but I have not tested it.</p>
<p>Calling (<code>function-name</code> <code>my-data</code> <code>my-data-map</code>) leads to a JSON string in your requested format:</p>
<blockquote>
<p>[{<br>
"keyWeWant": "<em>-20.0",<br>
"keyWeWant2": 20,<br>
"keyWeWant3": 2.857142857142857 }<br>
{<br>
"keyWeWant": "</em>-20.0",<br>
"keyWeWant2" 25,<br>
"keyWeWant3" 6.375 }]</p>
</blockquote>
<p>/edit
I see you were looking for a relatively simple solution, that this is not. :-) maybe there is one without having it available in a library. I would be glad to find out how it can be simplified.</p>
| 1 |
2016-09-24T16:32:33Z
|
[
"javascript",
"python",
"json",
"elasticsearch",
"clojure"
] |
Selectively flattening a nested JSON structure
| 39,672,892 |
<p>So this is a problem that I have no idea where to even start so even just a pointer in the right direction would be great.</p>
<p>So I have data that looks like so:</p>
<pre><code>data = {
"agg": {
"agg1": [
{
"keyWeWant": "*-20.0",
"asdf": 0,
"asdf": 20,
"asdf": 14,
"some_nested_agg": [
{
"keyWeWant2": 20,
"to": 25,
"doc_count": 4,
"some_nested_agg2": {
"count": 7,
"min": 2,
"max": 5,
"keyWeWant3": 2.857142857142857,
"sum": 20
}
},
{
"keyWeWant2": 25,
"to": 30,
"doc_count": 10,
"some_nested_agg2": {
"count": 16,
"min": 2,
"max": 10,
"keyWeWant3": 6.375,
"sum": 102
}
}
]
},
{
...
},
{
...
},
...
]
}
}
</code></pre>
<p>Now from the example, within 'agg' there are N 'agg1' results, within each 'agg1' result there is a 'keyWeWant'. Each 'agg1' result also has a list of 'some_nested_agg' results which each contain a 'keyWeWant2'. Each 'keyWeWant2' value is associated a single 'keyWeWant' value somewhere up in the hierarchy. Similarly each 'keyWeWant2' also contains a set of results for 'some_nested_agg2' (not a list but rather a map this time). Each of the set of results contains a 'keyWeWant3'.</p>
<p>Now I want to flatten this structure while still preserving the association between 'keyWeWant', 'keyWeWant2', and 'keyWeWant3' (I'm essentially de-normalizing) to get something like so:</p>
<p>What I want the function to look like:</p>
<pre><code>[
{
"keyWeWant" : "*-20",
"keyWeWant2" : 20,
"keyWeWant3" : 2.857142857142857
},
{
"keyWeWant" : "*-20",
"keyWeWant2" : 25,
"keyWeWant3" : 6.375
},
{
...
},
{
...
}
]
</code></pre>
<p>This is an example where there is only depth 3 but there could be arbitrary depth with some nested values being lists and some being arrays/list.</p>
<p>What I would like to do is write a function to take in the keys I want and where to find them, and then go get the keys and denormalize.</p>
<p>Something that looks like:</p>
<pre><code>function_name(data_map, {
"keyWeWant" : ['agg', 'agg1'],
"keyWeWant2" : ['agg', 'agg1', 'some_nested_agg'],
"keyWeWant" : ['agg', 'agg1', 'some_nested_agg', 'some_nested_agg2']
})
</code></pre>
<p>Any ideas? I'm familiar with Java, Clojure, Java-script, and Python and am just looking for a way to solve this that's relatively simple.</p>
| 0 |
2016-09-24T05:31:25Z
| 39,680,033 |
<p>Here is a JavaScript (ES6) function you could use:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function flatten(data, keys) {
var key = keys[0];
if (key in data)
keys = keys.slice(1);
var res = keys.length && Object.keys(data)
.map( key => data[key] )
.filter( val => Object(val) === val )
.reduce( (res, val) => res.concat(flatten(val, keys)), []);
return !(key in data) ? res
: (res || [{}]).map ( obj => Object.assign(obj, { [key]: data[key] }) );
}
// Sample data
var data = {
"agg": {
"agg1": [
{
"keyWeWant": "*-20.0",
"asdf": 0,
"asdf": 20,
"asdf": 14,
"some_nested_agg": [
{
"keyWeWant2": 20,
"to": 25,
"doc_count": 4,
"some_nested_agg2": {
"count": 7,
"min": 2,
"max": 5,
"keyWeWant3": 2.857142857142857,
"sum": 20
}
},
{
"keyWeWant2": 25,
"to": 30,
"doc_count": 10,
"some_nested_agg2": {
"count": 16,
"min": 2,
"max": 10,
"keyWeWant3": 6.375,
"sum": 102
}
}
]
},
]
}
};
// Flatten it by array of keys
var res = flatten(data, ['keyWeWant', 'keyWeWant2', 'keyWeWant3']);
// Output result
console.log(res);</code></pre>
</div>
</div>
</p>
<h3>Alternative using paths</h3>
<p>As noted in comments, the above code does not use path information; it just looks in all arrays. This could be an issue if the keys being looked for also occur in paths that should be ignored.</p>
<p>The following alternative will use path information, which should be passed as an array of sub-arrays, where each sub-array first lists the path keys, and as last element the value key to be retained:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function flatten(data, [path, ...paths]) {
return path && (
Array.isArray(data)
? data.reduce( (res, item) => res.concat(flatten(item, arguments[1])), [] )
: path[0] in data && (
path.length > 1
? flatten(data[path[0]], [path.slice(1), ...paths])
: (flatten(data, paths) || [{}]).map (
item => Object.assign(item, { [path[0]]: data[path[0]] })
)
)
);
}
// Sample data
var data = {
"agg": {
"agg1": [
{
"keyWeWant": "*-20.0",
"asdf": 0,
"asdf": 20,
"asdf": 14,
"some_nested_agg": [
{
"keyWeWant2": 20,
"to": 25,
"doc_count": 4,
"some_nested_agg2": {
"count": 7,
"min": 2,
"max": 5,
"keyWeWant3": 2.857142857142857,
"sum": 20
}
},
{
"keyWeWant2": 25,
"to": 30,
"doc_count": 10,
"some_nested_agg2": {
"count": 16,
"min": 2,
"max": 10,
"keyWeWant3": 6.375,
"sum": 102
}
}
]
},
]
}
};
// Flatten it by array of keys
var res = flatten(data, [
['agg', 'agg1', 'keyWeWant'],
['some_nested_agg', 'keyWeWant2'],
['some_nested_agg2', 'keyWeWant3']]);
// Output result
console.log(res);</code></pre>
</div>
</div>
</p>
| 0 |
2016-09-24T19:15:38Z
|
[
"javascript",
"python",
"json",
"elasticsearch",
"clojure"
] |
Check if a string ends with a decimal in Python 2
| 39,672,916 |
<p>I want to check if a string ends with a decimal of varying numbers, from searching for a while, the closest solution I found was to input values into a tuple and using that as the condition for endswith(). But is there any shorter way instead of inputting every possible combination?</p>
<p>I tried hard coding the end condition but if there are new elements in the list it wont work for those, I also tried using regex it returns other elements together with the decimal elements as well. Any help would be appreciated</p>
<pre><code>list1 = ["abcd 1.01", "zyx 22.98", "efgh 3.0", "qwe -70"]
for e in list1:
if e.endswith('.0') or e.endswith('.98'):
print 'pass'
</code></pre>
<p>Edit: Sorry should have specified that I do not want to have 'qwe -70' to be accepted, only those elements with a decimal point should be accepted</p>
| 1 |
2016-09-24T05:34:59Z
| 39,672,977 |
<p>Your example data leaves many possibilities open:</p>
<p>Last character is a digit:</p>
<pre><code>e[-1].isdigit()
</code></pre>
<p>Everything after the last space is a number:</p>
<pre><code>try:
float(e.rsplit(None, 1)[-1])
except ValueError:
# no number
pass
else:
print "number"
</code></pre>
<p>Using regular expressions:</p>
<pre><code>re.match('[.0-9]$', e)
</code></pre>
| 0 |
2016-09-24T05:46:54Z
|
[
"python",
"list",
"ends-with"
] |
Check if a string ends with a decimal in Python 2
| 39,672,916 |
<p>I want to check if a string ends with a decimal of varying numbers, from searching for a while, the closest solution I found was to input values into a tuple and using that as the condition for endswith(). But is there any shorter way instead of inputting every possible combination?</p>
<p>I tried hard coding the end condition but if there are new elements in the list it wont work for those, I also tried using regex it returns other elements together with the decimal elements as well. Any help would be appreciated</p>
<pre><code>list1 = ["abcd 1.01", "zyx 22.98", "efgh 3.0", "qwe -70"]
for e in list1:
if e.endswith('.0') or e.endswith('.98'):
print 'pass'
</code></pre>
<p>Edit: Sorry should have specified that I do not want to have 'qwe -70' to be accepted, only those elements with a decimal point should be accepted</p>
| 1 |
2016-09-24T05:34:59Z
| 39,672,984 |
<pre><code>suspects = [x.split() for x in list1] # split by the space in between and get the second item as in your strings
# iterate over to try and cast it to float -- if not it will raise ValueError exception
for x in suspects:
try:
float(x[1])
print "{} - ends with float".format(str(" ".join(x)))
except ValueError:
print "{} - does not ends with float".format(str(" ".join(x)))
## -- End pasted text --
abcd 1.01 - ends with float
zyx 22.98 - ends with float
efgh 3.0 - ends with float
qwe -70 - ends with float
</code></pre>
| 0 |
2016-09-24T05:47:54Z
|
[
"python",
"list",
"ends-with"
] |
Check if a string ends with a decimal in Python 2
| 39,672,916 |
<p>I want to check if a string ends with a decimal of varying numbers, from searching for a while, the closest solution I found was to input values into a tuple and using that as the condition for endswith(). But is there any shorter way instead of inputting every possible combination?</p>
<p>I tried hard coding the end condition but if there are new elements in the list it wont work for those, I also tried using regex it returns other elements together with the decimal elements as well. Any help would be appreciated</p>
<pre><code>list1 = ["abcd 1.01", "zyx 22.98", "efgh 3.0", "qwe -70"]
for e in list1:
if e.endswith('.0') or e.endswith('.98'):
print 'pass'
</code></pre>
<p>Edit: Sorry should have specified that I do not want to have 'qwe -70' to be accepted, only those elements with a decimal point should be accepted</p>
| 1 |
2016-09-24T05:34:59Z
| 39,673,044 |
<p>I think this will work for this case:</p>
<pre><code>regex = r"([0-9]+\.[0-9]+)"
list1 = ["abcd 1.01", "zyx 22.98", "efgh 3.0", "qwe -70"]
for e in list1:
str = e.split(' ')[1]
if re.search(regex, str):
print True #Code for yes condition
else:
print False #Code for no condition
</code></pre>
| 0 |
2016-09-24T05:58:04Z
|
[
"python",
"list",
"ends-with"
] |
Check if a string ends with a decimal in Python 2
| 39,672,916 |
<p>I want to check if a string ends with a decimal of varying numbers, from searching for a while, the closest solution I found was to input values into a tuple and using that as the condition for endswith(). But is there any shorter way instead of inputting every possible combination?</p>
<p>I tried hard coding the end condition but if there are new elements in the list it wont work for those, I also tried using regex it returns other elements together with the decimal elements as well. Any help would be appreciated</p>
<pre><code>list1 = ["abcd 1.01", "zyx 22.98", "efgh 3.0", "qwe -70"]
for e in list1:
if e.endswith('.0') or e.endswith('.98'):
print 'pass'
</code></pre>
<p>Edit: Sorry should have specified that I do not want to have 'qwe -70' to be accepted, only those elements with a decimal point should be accepted</p>
| 1 |
2016-09-24T05:34:59Z
| 39,673,077 |
<p>I'd like to propose another solution: using <a href="https://docs.python.org/2/library/re.html" rel="nofollow">regular expressions</a> to search for an ending decimal.</p>
<p>You can define a regular expression for an ending decimal with the following regex <code>[-+]?[0-9]*\.[0-9]+$</code>.</p>
<p>The regex broken apart:</p>
<ul>
<li><code>[-+]?</code>: optional - or + symbol at the beginning</li>
<li><code>[0-9]*</code>: zero or more digits</li>
<li><code>\.</code>: required dot</li>
<li><code>[0-9]+</code>: one or more digits</li>
<li><code>$</code>: must be at the end of the line</li>
</ul>
<p>Then we can test the regular expression to see if it matches any of the members in the list:</p>
<pre><code>import re
regex = re.compile('[-+]?[0-9]*\.[0-9]+$')
list1 = ["abcd 1.01", "zyx 22.98", "efgh 3.0", "qwe -70", "test"]
for e in list1:
if regex.search(e) is not None:
print e + " passes"
else:
print e + " does not pass"
</code></pre>
<p>The output for the previous script is the following:</p>
<pre><code>abcd 1.01 passes
zyx 22.98 passes
efgh 3.0 passes
qwe -70 does not pass
test does not pass
</code></pre>
| 2 |
2016-09-24T06:02:18Z
|
[
"python",
"list",
"ends-with"
] |
Check if a string ends with a decimal in Python 2
| 39,672,916 |
<p>I want to check if a string ends with a decimal of varying numbers, from searching for a while, the closest solution I found was to input values into a tuple and using that as the condition for endswith(). But is there any shorter way instead of inputting every possible combination?</p>
<p>I tried hard coding the end condition but if there are new elements in the list it wont work for those, I also tried using regex it returns other elements together with the decimal elements as well. Any help would be appreciated</p>
<pre><code>list1 = ["abcd 1.01", "zyx 22.98", "efgh 3.0", "qwe -70"]
for e in list1:
if e.endswith('.0') or e.endswith('.98'):
print 'pass'
</code></pre>
<p>Edit: Sorry should have specified that I do not want to have 'qwe -70' to be accepted, only those elements with a decimal point should be accepted</p>
| 1 |
2016-09-24T05:34:59Z
| 39,673,130 |
<p>As you correctly guessed, <code>endswith()</code> is not a good way to look at the solution, given that the number of combinations is basically infinite. The way to go is - as many suggested - a regular expression that would match the end of the string to be a decimal point followed by any count of digits. Besides that, keep the code simple, and readable. The <code>strip()</code> is in there just in case one the input string has an extra space at the end, which would unnecessarily complicate the regex.
You can see this in action at: <a href="https://eval.in/649155" rel="nofollow">https://eval.in/649155</a></p>
<pre><code>import re
regex = r"[0-9]+\.[0-9]+$"
list1 = ["abcd 1.01", "zyx 22.98", "efgh 3.0", "qwe -70"]
for e in list1:
if re.search(regex, e.strip()):
print e, 'pass'
</code></pre>
| 0 |
2016-09-24T06:09:58Z
|
[
"python",
"list",
"ends-with"
] |
Check if a string ends with a decimal in Python 2
| 39,672,916 |
<p>I want to check if a string ends with a decimal of varying numbers, from searching for a while, the closest solution I found was to input values into a tuple and using that as the condition for endswith(). But is there any shorter way instead of inputting every possible combination?</p>
<p>I tried hard coding the end condition but if there are new elements in the list it wont work for those, I also tried using regex it returns other elements together with the decimal elements as well. Any help would be appreciated</p>
<pre><code>list1 = ["abcd 1.01", "zyx 22.98", "efgh 3.0", "qwe -70"]
for e in list1:
if e.endswith('.0') or e.endswith('.98'):
print 'pass'
</code></pre>
<p>Edit: Sorry should have specified that I do not want to have 'qwe -70' to be accepted, only those elements with a decimal point should be accepted</p>
| 1 |
2016-09-24T05:34:59Z
| 39,673,136 |
<p>The flowing maybe help:</p>
<pre><code>import re
reg = re.compile(r'^[a-z]+ \-?[0-9]+\.[0-9]+$')
if re.match(reg, the_string):
do something...
else:
do other...
</code></pre>
| 0 |
2016-09-24T06:11:02Z
|
[
"python",
"list",
"ends-with"
] |
Remove max and min duplicate of a list of number
| 39,672,930 |
<p>I would like to remove ONLY the maximum and minimum duplicate of a list of
numbers. Example: (<strong>1 1 1</strong> 4 4 5 6 <strong>8 8 8</strong>) Result: (<strong>1</strong> 4 4 5 6
<strong>8</strong>)</p>
<p>How do I combine max() min() function with <code>list(set(x))</code>?</p>
<p>Or is there another way?</p>
<pre><code>s = raw_input("Please Input a series of numbers")
numbers = map(int, s.split())
numbers.remove(max(numbers))
numbers.remove(min(numbers))
average = sum(numbers)/float(len(numbers))
print average
</code></pre>
| -3 |
2016-09-24T05:37:49Z
| 39,679,828 |
<pre><code>s = raw_input("Please Input a series of numbers")
numbers = map(int, s.split())
# numbers = [1, 1, 1, 4, 4, 5, 6, 8, 8, 8]
mi = min(numbers)
ma = max(numbers)
b = [mi] + [x for x in numbers if x != mi and x != ma] + [ma]
</code></pre>
| 0 |
2016-09-24T18:49:49Z
|
[
"python"
] |
Remove max and min duplicate of a list of number
| 39,672,930 |
<p>I would like to remove ONLY the maximum and minimum duplicate of a list of
numbers. Example: (<strong>1 1 1</strong> 4 4 5 6 <strong>8 8 8</strong>) Result: (<strong>1</strong> 4 4 5 6
<strong>8</strong>)</p>
<p>How do I combine max() min() function with <code>list(set(x))</code>?</p>
<p>Or is there another way?</p>
<pre><code>s = raw_input("Please Input a series of numbers")
numbers = map(int, s.split())
numbers.remove(max(numbers))
numbers.remove(min(numbers))
average = sum(numbers)/float(len(numbers))
print average
</code></pre>
| -3 |
2016-09-24T05:37:49Z
| 39,680,465 |
<p>Here is a fairly general solution to the problem using some <code>itertools</code> functions. That solution will collapse a repetition of min and max values into a single value wherever that repetition may appear:</p>
<pre><code>from itertools import groupby,starmap,chain
#first we count the sequence length for each group of number in the list
c=[[number,len(list(seq))] for number,seq in groupby(numbers)]
print(c)
#we collapse the repetitions only for min and max
for group in c:
if group[0] == min(numbers) or group[0]== max(numbers):
group[1]=1
print(c)
#we put back the list together
numbers=list(chain(*starmap(lambda x,n : [x]*n, c)))
print(numbers)
</code></pre>
<p>Example output:</p>
<pre><code>>>>numbers=[1,1,1,4,4,5,6,8,8,8]
[1, 4, 4, 5, 6, 8]
>>>numbers=[4,4,1,1,1,5,6,8,8,8]
[4, 4, 1, 5, 6, 8]
#edge case if there are multiple groups of min :
>>>numbers=[4,4,1,1,1,5,1,1,1,6,8,8,8]
[4, 4, 1, 5, 1, 6, 8]
</code></pre>
| 0 |
2016-09-24T20:05:08Z
|
[
"python"
] |
Unselect single option dropdown python webdriver
| 39,673,019 |
<p>I am having an issue unselecting a selected option after selecting it using webdriver. I keep getting error raise NotImplementedError("You may only deselect options of a multi-select")
NotImplementedError: You may only deselect options of a multi-select</p>
<p>How can a selected pull down menu item be unselected? My code is below.</p>
<p>HTML code:</p>
<pre><code><option selected="selected" value=""></option>
<option value="Item 1">Item 1</option>
<option value="Item 2 (1)">Item 2</option>
<option value="Item 3">Item 3</option>
</code></pre>
<p>Python Webdriver:</p>
<pre><code>options = select.find_elements_by_tag_name("option")
for x in range(1,len(options)):
option = options[x]
options_list.append(option.get_attribute("value"))
item_selection = Select(select)
item_selection.select_by_visible_text("Item 1")
time.sleep()
item_selection.deselect_by_visible_text("Item 1")
</code></pre>
| 1 |
2016-09-24T05:54:20Z
| 39,682,714 |
<p>You could use <code>.select_by_index(0)</code> or possibly <code>.select_by_value("")</code>. The first one should work... I'm not sure about the second.</p>
| 0 |
2016-09-25T02:03:22Z
|
[
"python",
"selenium"
] |
Unselect single option dropdown python webdriver
| 39,673,019 |
<p>I am having an issue unselecting a selected option after selecting it using webdriver. I keep getting error raise NotImplementedError("You may only deselect options of a multi-select")
NotImplementedError: You may only deselect options of a multi-select</p>
<p>How can a selected pull down menu item be unselected? My code is below.</p>
<p>HTML code:</p>
<pre><code><option selected="selected" value=""></option>
<option value="Item 1">Item 1</option>
<option value="Item 2 (1)">Item 2</option>
<option value="Item 3">Item 3</option>
</code></pre>
<p>Python Webdriver:</p>
<pre><code>options = select.find_elements_by_tag_name("option")
for x in range(1,len(options)):
option = options[x]
options_list.append(option.get_attribute("value"))
item_selection = Select(select)
item_selection.select_by_visible_text("Item 1")
time.sleep()
item_selection.deselect_by_visible_text("Item 1")
</code></pre>
| 1 |
2016-09-24T05:54:20Z
| 39,685,391 |
<p>The problem is that your dropdown select class does not have multi-select which means that you can only select a item from the dropdown list at a time and for all deselect functions there is a check that if </p>
<pre><code>if not self.is_multiple:
raise NotImplementedError("You may only deselect options of a multi-select")
</code></pre>
<p>and because of which its giving you error which is expected since deselect should only work with multi-select dropdowns.</p>
<p>The work around is use select_by_index() or select_by_value() or select_by_visible_text() of another element to change the selection from the selected one to another.</p>
<p>And if you are practising deselect then try it on page which supports multi-select </p>
| 0 |
2016-09-25T09:35:18Z
|
[
"python",
"selenium"
] |
Python 2.7: Imgur API and getting clear text comments from a post?
| 39,673,147 |
<pre><code>client = ImgurClient(client_id, client_secret, access_token, refresh_token)
for item in client.gallery_item_comments("c1SN8", sort='best'):
print item
</code></pre>
<p>This is my current code. What I'm trying to do is (hopefully) return a list of comment id's from that function. It doesn't do that, and instead outputs this.</p>
<pre><code><imgurpython.imgur.models.comment.Comment object at 0x03D8EFB0>
...
</code></pre>
<p>What I'm asking is if there is any combination of functions from the Imgur api to get a list of comment id's? <a href="https://github.com/Imgur/imgurpython" rel="nofollow">API</a></p>
| 0 |
2016-09-24T06:12:30Z
| 39,673,264 |
<p>In the above code <code>item</code> is a <code>Comment</code> Object representing the comment itself. Because it doesn't have a defined way of how to print the Object, you see <code>imgurpython.imgur.models.comment.Comment</code> telling you the object type and <code>0x03D8EFB0</code> representing the address in memory that object is located at. Do not worry, that is indeed the Comment you're looking for.</p>
<p>Looking at the <a href="https://api.imgur.com/models/comment" rel="nofollow">Imgur API documentation</a> for Comment, you can see the a Comment has the following properties: <code>id</code>, <code>image_id</code>, <code>comment</code>, <code>author</code>, <code>author_id</code>, <code>on_album</code>, <code>album_cover</code>, <code>ups</code>, <code>downs</code>, <code>points</code>, <code>datetime</code>, <code>parent_id</code>, <code>deleted</code>, <code>vote</code>, and <code>children</code>.</p>
<p>You can access each property by accessing <code>item.<property></code> inside the for loop. For example, if you want to print all the <code>id</code>s you can do the following:</p>
<pre><code>client = ImgurClient(client_id, client_secret, access_token, refresh_token)
for item in client.gallery_item_comments("c1SN8", sort='best'):
print item.id
</code></pre>
| 2 |
2016-09-24T06:27:14Z
|
[
"python",
"imgur"
] |
WOL MAC Address not working
| 39,673,174 |
<p>I'm trying to run a python script to send a magic packet to computers on my network. It works on the other computers, but when I try to run the script with my own MAC address I get an error. </p>
<p>This is my python script</p>
<pre><code>#!/usr/bin/env python
#Wake-On-LAN
#
# Copyright (C) 2002 by Micro Systems Marc Balmer
# Written by Marc Balmer, marc@msys.ch, http://www.msys.ch/
# This code is free software under the GPL
import struct, socket
def WakeOnLan(ethernet_address):
# Construct a six-byte hardware address
addr_byte = ethernet_address.split(':')
hw_addr = struct.pack('BBBBBB', int(addr_byte[0], 16),
int(addr_byte[1], 16),
int(addr_byte[2], 16),
int(addr_byte[3], 16),
int(addr_byte[4], 16),
int(addr_byte[5], 16))
# Build the Wake-On-LAN "Magic Packet"...
msg = b'\xff' * 6 + hw_addr * 16
# ...and send it to the broadcast address using UDP
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
s.sendto(msg, ('10.0.0.129', 9))
s.sendto(msg, ('10.0.0.129', 7))
s.close()
# Example use
WakeOnLan('30-5A-3A-03-82-AE')
</code></pre>
<p>With 10.0.0.129 being my local address and 30-5A-3A-03-82-AE being my physical address. </p>
<p>When I try to run the script I get this error</p>
<pre><code>Traceback (most recent call last):
File "C:\xampp\htdocs\wol\wolme.py", line 35, in <module>
WakeOnLan('30-5A-3A-03-82-AE')
File "C:\xampp\htdocs\wol\wolme.py", line 15, in WakeOnLan
hw_addr = struct.pack('BBBBBB', int(addr_byte[0], 16),
ValueError: invalid literal for int() with base 16: '30-5A-3A-03-82-AE'
</code></pre>
<p>Again, no other computer has this problem. Any help appreciated.</p>
| 0 |
2016-09-24T06:15:08Z
| 39,673,465 |
<p>it won't work on any address separated by "-", because of this line:</p>
<pre><code>addr_byte = ethernet_address.split(':')
</code></pre>
<p>just change <code>WakeOnLan('30-5A-3A-03-82-AE')</code> with <code>WakeOnLan('30:5A:3A:03:82:AE')</code> and it will work, or instead change the line that says:</p>
<pre><code>addr_byte = ethernet_address.split(':')
</code></pre>
<p>with</p>
<pre><code>addr_byte = ethernet_address.split('-')
</code></pre>
<p>if you want to use "-" as separators.</p>
<p>Hope this helps!</p>
| 0 |
2016-09-24T06:53:11Z
|
[
"python",
"wake-on-lan"
] |
How can Python keep generating a random list of numbers until it equals to a certain made-up list?
| 39,673,176 |
<p>Background: I was trying to create a code that would make Python generate a pattern from a 3 x 3 grid of dots, such that once a dot is chosen, the next dot can only be adjacent to it, and that no dot can be used twice. The following code is my input into Python for generating a 5-dot pattern for a 3 x 3 grid. </p>
<pre><code>import random
x_arr=[]
y_arr=[]
def addTolist(m,n):
x_arr.append(m)
y_arr.append(n)
grid = [[1,2,3],[4,5,6],[7,8,9]] #rows of dots from top to bottom
dot = random.choice(range(1,10)) #random dot from the grid is chosen
for i in range(3):
for j in range(3):
if dot == grid[i][j]:
x = i
y = j
break
num = [dot]
for i in range(5): # loop 5 times
print('dot:',dot)
# every time empty the list
neighbours = []
x_arr=[]
y_arr=[]
#choosing only the adjacent numbers (neighbours) to the current dot
if y-1 >= 0:
neighbours.append(grid[x][y-1])
addTolist(x,y-1)
if x+1 < 3:
neighbours.append(grid[x+1][y-1])
addTolist(x+1,y-1)
if x-1 >= 0:
neighbours.append(grid[x-1][y-1])
addTolist(x-1,y-1)
if x-1 >= 0:
neighbours.append(grid[x-1][y])
addTolist(x-1,y)
if y+1 < 3:
neighbours.append(grid[x-1][y+1])
addTolist(x-1,y+1)
if y+1 < 3:
neighbours.append(grid[x][y+1])
addTolist(x,y+1)
if x+1 < 3:
neighbours.append(grid[x+1][y+1])
addTolist(x+1,y+1)
if x+1 < 3:
neighbours.append(grid[x+1][y])
addTolist(x+1,y)
dot = random.choice(neighbours)
while dot in num:
dot = random.choice(neighbours)
num.append(dot)
position = neighbours.index(dot)
x = x_arr[position]
y = y_arr[position]
</code></pre>
<p>Output:</p>
<pre><code>('dot:', 6)
('dot:', 2)
('dot:', 3)
('dot:', 5)
('dot:', 7)
</code></pre>
<p>Is there any way that I can keep generating these patterns (without repetition) until it equals to the pattern [1,2,6,9,8] and find how many trials it took to get to this pattern [1,2,6,9,8]? I assume that I would have to get the output into a single list first, but I have been struggling to do so. Any help is greatly appreciated.</p>
| 0 |
2016-09-24T06:15:09Z
| 39,673,317 |
<p>Try this, I think it would work: </p>
<pre><code>import random
x_arr=[]
y_arr=[]
index = 0
pattern = [1,2,6,9,8]
def addTolist(m,n):
x_arr.append(m)
y_arr.append(n)
grid = [[1,2,3],[4,5,6],[7,8,9]] #rows of dots from top to bottom
dot = random.choice(range(1,10)) #random dot from the grid is chosen
guess = 1
while dot!= pattern[index]:
print("Wrong guess",dot)
guess += 1
dot = random.choice(range(1,10))
for i in range(3):
for j in range(3):
if dot == grid[i][j]:
x = i
y = j
break
num = [dot]
print('dot:',dot)
for i in range(4):
index +=1
# every time empty the list
neighbours = []
x_arr=[]
y_arr=[]
#choosing only the adjacent numbers (neighbours) to the current dot
if y-1 >= 0:
neighbours.append(grid[x][y-1])
addTolist(x,y-1)
if x+1 < 3:
neighbours.append(grid[x+1][y-1])
addTolist(x+1,y-1)
if x-1 >= 0:
neighbours.append(grid[x-1][y-1])
addTolist(x-1,y-1)
if x-1 >= 0:
neighbours.append(grid[x-1][y])
addTolist(x-1,y)
if y+1 < 3:
neighbours.append(grid[x-1][y+1])
addTolist(x-1,y+1)
if y+1 < 3:
neighbours.append(grid[x][y+1])
addTolist(x,y+1)
if x+1 < 3:
neighbours.append(grid[x+1][y+1])
addTolist(x+1,y+1)
if x+1 < 3:
neighbours.append(grid[x+1][y])
addTolist(x+1,y)
if pattern[index] not in neighbours: # if wrong Pattern is entered
print("Wrong Pattern can not generate",pattern[index] , "After",pattern[index-1])
break
dot = random.choice(neighbours)
guess += 1
while dot != pattern[index]: # for checking pattern
print("Wrong guess",dot)
dot = random.choice(neighbours)
guess += 1
print('dot:',dot)
num.append(dot)
position = neighbours.index(dot)
x = x_arr[position]
y = y_arr[position]
print("Total guess :",guess)
</code></pre>
<p>Output:</p>
<pre><code>Wrong guess 3
Wrong guess 7
Wrong guess 5
Wrong guess 8
Wrong guess 5
Wrong guess 4
dot: 1
dot: 2
Wrong guess 4
Wrong guess 1
Wrong guess 5
Wrong guess 1
Wrong guess 1
dot: 6
Wrong guess 8
Wrong guess 8
dot: 9
dot: 8
Total guess : 18
</code></pre>
<p><strong>Modifications:</strong></p>
<ul>
<li>Instead of checking unique variable , I am checking for pattern, So I
take <code>pattern</code> list.</li>
<li>I am checking for <code>range(4)</code> instead of <code>5</code> because 1st number is
already generated and so why waste computing 6th random number when
we are not even printing it.</li>
<li>I take <code>guess</code> variable to keep track of number of guesses.</li>
</ul>
<p><strong>Note :</strong> I am checking for if pattern is wrong then it will print wrong pattern .</p>
<p>For example: if pattern =<code>[1,2,3,9,8]</code> it will give output as:</p>
<pre><code>Wrong guess 7
Wrong guess 4
dot: 1
Wrong guess 5
Wrong guess 4
Wrong guess 5
dot: 2
Wrong guess 4
dot: 3
Wrong Pattern can not generate 9 After 3
Total guess : 9
</code></pre>
<p><strong>Updated :</strong> If you want to count whole sequence as the one guess then:</p>
<pre><code>import random
x_arr=[]
y_arr=[]
index = 0
pattern = [1,2,6,9,8]
def addTolist(m,n):
x_arr.append(m)
y_arr.append(n)
guess = 0
while True :
grid = [[1,2,3],[4,5,6],[7,8,9]] #rows of dots from top to bottom
dot = random.choice(range(1,10)) #random dot from the grid is chosen
for i in range(3):
for j in range(3):
if dot == grid[i][j]:
x = i
y = j
break
num = [dot]
for i in range(4):
# every time empty the list
neighbours = []
x_arr=[]
y_arr=[]
#choosing only the adjacent numbers (neighbours) to the current dot
if y-1 >= 0:
neighbours.append(grid[x][y-1])
addTolist(x,y-1)
if x+1 < 3:
neighbours.append(grid[x+1][y-1])
addTolist(x+1,y-1)
if x-1 >= 0:
neighbours.append(grid[x-1][y-1])
addTolist(x-1,y-1)
if x-1 >= 0:
neighbours.append(grid[x-1][y])
addTolist(x-1,y)
if y+1 < 3:
neighbours.append(grid[x-1][y+1])
addTolist(x-1,y+1)
if y+1 < 3:
neighbours.append(grid[x][y+1])
addTolist(x,y+1)
if x+1 < 3:
neighbours.append(grid[x+1][y+1])
addTolist(x+1,y+1)
if x+1 < 3:
neighbours.append(grid[x+1][y])
addTolist(x+1,y)
dot = random.choice(neighbours)
while dot in num :
dot = random.choice(neighbours)
num.append(dot)
position = neighbours.index(dot)
x = x_arr[position]
y = y_arr[position]
guess += 1
if num == pattern :
break
print("Total guess :",guess)
</code></pre>
<p>Output : </p>
<pre><code>Total guess : 12
</code></pre>
<blockquote>
<p><strong>Note :</strong> I don't recommended to use this method as sometimes it gives <strong>total guess is 1</strong> or most of the times it gives you <strong>timeout</strong>
because it is random it may happen that the required sequence may
never gets generated or running time exceeded. SO you can try put limit on the guesses like
instead of <code>while True</code> use <code>for c in range(50):</code> or what over range
you have to give.(And if timeout is coming run the code more number of
times till it gives you answer I tried 8-10 times before I got this
output)</p>
</blockquote>
<p>Hope this will help you.</p>
| 1 |
2016-09-24T06:35:24Z
|
[
"python"
] |
Python - reducing long if-elif lines of code
| 39,673,262 |
<p>I have just started learning python, and while my code is working, I want to reduce my lines of code. I was thinking of using list method, but I couldn't really come up of a solution. I tried searching beforehand, but I couldn't find something related to mine.</p>
<p>For my code, it's like a point moving through one space to another. The possible movements are determined by directions. What I did to determine the movement of the point was to assign a <code>userPoint</code> (which determines where the point is). In order to move, it has to satisfy the conditions set by the space (aka the only available directions represented by <code>userInput.upper()</code>) or else it will not move and print that the input was invalid.</p>
<pre><code>if userInput.upper() == 'QUIT':
break
elif userPoint == 0 and userInput.upper() =='EAST':
userPoint = 1
elif userPoint == 1 and userInput.upper() == 'WEST':
userPoint = 0
elif userPoint == 1 and userInput.upper() == 'EAST':
userPoint = 2
elif userPoint == 1 and userInput.upper() == 'SOUTH':
userPoint = 4
elif userPoint == 2 and userInput.upper() == 'WEST':
userPoint = 1
elif userPoint == 3 and userInput.upper() == 'SOUTH':
userPoint = 6
elif userPoint == 4 and userInput.upper() == 'NORTH':
userPoint = 1
elif userPoint == 4 and userInput.upper() == 'EAST':
userPoint = 5
elif userPoint == 5 and userInput.upper() == 'WEST':
userPoint = 4
elif userPoint == 5 and userInput.upper() == 'SOUTH':
userPoint = 8
elif userPoint == 6 and userInput.upper() == 'NORTH':
userPoint = 3
elif userPoint == 6 and userInput.upper() == 'EAST':
userPoint = 7
elif userPoint == 7 and userInput.upper() == 'WEST':
userPoint = 6
elif userPoint == 7 and userInput.upper() == 'EAST':
userPoint = 8
elif userPoint == 8 and userInput.upper() == 'WEST':
userPoint = 7
elif userPoint == 8 and userInput.upper() =='NORTH':
userPoint = 5
else:
print('Please input a valid direction.\n')
</code></pre>
<p>Thank you very much for the help!</p>
| 1 |
2016-09-24T06:27:12Z
| 39,673,413 |
<p>I'll do it by creating a dictionary mapping
Something like this</p>
<pre><code>mapping = {
0 : {
"EAST" : 1
},
1 : {
"EAST": 2,
"WEST": 1,
"SOUTH": 4
}
}
if userInput.upper() == 'QUIT':
break
else:
userInput = mapping[userPoint][userInput.upper()]
</code></pre>
| 0 |
2016-09-24T06:46:09Z
|
[
"python",
"python-3.x"
] |
Python - reducing long if-elif lines of code
| 39,673,262 |
<p>I have just started learning python, and while my code is working, I want to reduce my lines of code. I was thinking of using list method, but I couldn't really come up of a solution. I tried searching beforehand, but I couldn't find something related to mine.</p>
<p>For my code, it's like a point moving through one space to another. The possible movements are determined by directions. What I did to determine the movement of the point was to assign a <code>userPoint</code> (which determines where the point is). In order to move, it has to satisfy the conditions set by the space (aka the only available directions represented by <code>userInput.upper()</code>) or else it will not move and print that the input was invalid.</p>
<pre><code>if userInput.upper() == 'QUIT':
break
elif userPoint == 0 and userInput.upper() =='EAST':
userPoint = 1
elif userPoint == 1 and userInput.upper() == 'WEST':
userPoint = 0
elif userPoint == 1 and userInput.upper() == 'EAST':
userPoint = 2
elif userPoint == 1 and userInput.upper() == 'SOUTH':
userPoint = 4
elif userPoint == 2 and userInput.upper() == 'WEST':
userPoint = 1
elif userPoint == 3 and userInput.upper() == 'SOUTH':
userPoint = 6
elif userPoint == 4 and userInput.upper() == 'NORTH':
userPoint = 1
elif userPoint == 4 and userInput.upper() == 'EAST':
userPoint = 5
elif userPoint == 5 and userInput.upper() == 'WEST':
userPoint = 4
elif userPoint == 5 and userInput.upper() == 'SOUTH':
userPoint = 8
elif userPoint == 6 and userInput.upper() == 'NORTH':
userPoint = 3
elif userPoint == 6 and userInput.upper() == 'EAST':
userPoint = 7
elif userPoint == 7 and userInput.upper() == 'WEST':
userPoint = 6
elif userPoint == 7 and userInput.upper() == 'EAST':
userPoint = 8
elif userPoint == 8 and userInput.upper() == 'WEST':
userPoint = 7
elif userPoint == 8 and userInput.upper() =='NORTH':
userPoint = 5
else:
print('Please input a valid direction.\n')
</code></pre>
<p>Thank you very much for the help!</p>
| 1 |
2016-09-24T06:27:12Z
| 39,673,429 |
<p>Notice that whenever <code>userInput</code> is East, the effect is to add one to <code>userDirection</code>.</p>
<p>You can shorten the long line, by testing for <code>userInput</code>, and calcuating <code>userDirection</code>.</p>
<pre><code>if userInput.upper == "EAST":
userDirection += 1
elif userInput.upper == "SOUTH":
userDirection += 3
elif # etc.
</code></pre>
| 0 |
2016-09-24T06:48:41Z
|
[
"python",
"python-3.x"
] |
Python - reducing long if-elif lines of code
| 39,673,262 |
<p>I have just started learning python, and while my code is working, I want to reduce my lines of code. I was thinking of using list method, but I couldn't really come up of a solution. I tried searching beforehand, but I couldn't find something related to mine.</p>
<p>For my code, it's like a point moving through one space to another. The possible movements are determined by directions. What I did to determine the movement of the point was to assign a <code>userPoint</code> (which determines where the point is). In order to move, it has to satisfy the conditions set by the space (aka the only available directions represented by <code>userInput.upper()</code>) or else it will not move and print that the input was invalid.</p>
<pre><code>if userInput.upper() == 'QUIT':
break
elif userPoint == 0 and userInput.upper() =='EAST':
userPoint = 1
elif userPoint == 1 and userInput.upper() == 'WEST':
userPoint = 0
elif userPoint == 1 and userInput.upper() == 'EAST':
userPoint = 2
elif userPoint == 1 and userInput.upper() == 'SOUTH':
userPoint = 4
elif userPoint == 2 and userInput.upper() == 'WEST':
userPoint = 1
elif userPoint == 3 and userInput.upper() == 'SOUTH':
userPoint = 6
elif userPoint == 4 and userInput.upper() == 'NORTH':
userPoint = 1
elif userPoint == 4 and userInput.upper() == 'EAST':
userPoint = 5
elif userPoint == 5 and userInput.upper() == 'WEST':
userPoint = 4
elif userPoint == 5 and userInput.upper() == 'SOUTH':
userPoint = 8
elif userPoint == 6 and userInput.upper() == 'NORTH':
userPoint = 3
elif userPoint == 6 and userInput.upper() == 'EAST':
userPoint = 7
elif userPoint == 7 and userInput.upper() == 'WEST':
userPoint = 6
elif userPoint == 7 and userInput.upper() == 'EAST':
userPoint = 8
elif userPoint == 8 and userInput.upper() == 'WEST':
userPoint = 7
elif userPoint == 8 and userInput.upper() =='NORTH':
userPoint = 5
else:
print('Please input a valid direction.\n')
</code></pre>
<p>Thank you very much for the help!</p>
| 1 |
2016-09-24T06:27:12Z
| 39,674,190 |
<p>It seems like the user is moving through a sort of labyrinth that looks like this:</p>
<pre class="lang-none prettyprint-override"><code>2--1--0
|
5--4 3
| |
8--7--6
</code></pre>
<p>We can store the valid connections as a list of sets. For example, <code>{0, 1}</code> represents a connection that goes from 0 to 1 and from 1 to 0. Sets have no ordering, so <code>{0, 1}</code> and <code>{1, 0}</code> are the same thing.</p>
<pre><code>if userInput.upper() == 'QUIT':
break
connections = [{0,1}, {1,2}, {1,4}, {3,6}, {4,5}, {5,8}, {6,7}, {7,8}]
if userInput.upper() == 'EAST':
newUserPoint = userPoint + 1
elif userInput.upper() == 'WEST':
newUserPoint = userPoint - 1
elif userInput.upper() == 'SOUTH':
newUserPoint = userPoint + 3
elif userInput.upper() == 'NORTH':
newUserPoint = userPoint - 3
else:
newUserPoint = None
movementIsValid = {userPoint, newUserPoint} in connections
if movementIsValid:
userPoint = newUserPoint
else:
print('Please input a valid direction.\n')
</code></pre>
<p>To learn about how lists and sets are used, you can check out the tutorial (<a href="https://docs.python.org/3.5/tutorial/introduction.html#lists" rel="nofollow">lists</a>, <a href="https://docs.python.org/3.5/tutorial/datastructures.html#sets" rel="nofollow">sets</a>). In the code above, we calculate the new point and then check if there is a connection from the old point to the new point.</p>
<p>There is still some repetition that we can get rid of when we calculate the new point.</p>
<pre><code>if userInput.upper() == 'QUIT':
break
directions = {'EAST': 1, 'WEST': -1, 'SOUTH': 3, 'NORTH': -3}
connections = [{0,1}, {1,2}, {1,4}, {3,6}, {4,5}, {5,8}, {6,7}, {7,8}]
if userInput.upper() in directions:
userDirection = directions[userInput.upper()]
newUserPoint = userPoint + userDirection
else:
newUserPoint = None
movementIsValid = {userPoint, newUserPoint} in connections
if movementIsValid:
userPoint = newUserPoint
else:
print('Please input a valid direction.\n')
</code></pre>
<p>In this solution, we use a <a href="https://docs.python.org/3.5/tutorial/datastructures.html#dictionaries" rel="nofollow">dictionary</a> for the directions.</p>
<p>I've used a lot of concepts that might be new for you, you can read about them in the links I've given, and if you get stuck anywhere you can ask a new question here on StackOverflow.</p>
| 0 |
2016-09-24T08:23:57Z
|
[
"python",
"python-3.x"
] |
How do I programmatically create a vertical custom keyboard layout with python using the telegram bot api?
| 39,673,316 |
<p>I'm trying to create a card-based game bot using the telepot api wrapper for telegram, but I can't figure out how to make it use a vertical layout instead of a horizontal layout</p>
<p>sample code:</p>
<pre><code>keyboard = []
for card in data['current_games'][userGame]['players'][messageLocationID]['cards']:
button = [KeyboardButton(text=card)]
keyboard += button
</code></pre>
<p>Then I use the sendMessage() method with the ReplyKeyboardMarkup() method, but it creates a row of buttons that are tall and thin, which affects the display of the text.</p>
<p>Is there a step I'm missing? I was able to create a square of keys using:</p>
<pre><code>keyboard = [[KeyboardButton(text='0'), KeyboardButton(text='1'), KeyboardButton(text='2'), KeyboardButton(text='3')],
[KeyboardButton(text='4'), KeyboardButton(text='5'), KeyboardButton(text='6'), KeyboardButton(text='7')],
[KeyboardButton(text='8'), KeyboardButton(text='9'), KeyboardButton(text='10'), KeyboardButton(text='11')],
[KeyboardButton(text='12'), KeyboardButton(text='13'), KeyboardButton(text='14'), KeyboardButton(text='15')]]
</code></pre>
<p>I only created a keyboard using the second method because I was able to create it manually instead of programmatically, but I don't have a way to process the card list without accessing each card in sequence since it's a dynamic list that changes with each turn.</p>
<p>I looked in the api notes but I couldn't find anything that I was able to use</p>
<p>I assumed based on the results of the second keyboard that I would be able to create vertical rows by making each card be an array so it would be nested inside the original array, but that proved to not be the case in my experience</p>
<p>Am I missing a step?</p>
| 0 |
2016-09-24T06:35:21Z
| 39,755,476 |
<p>Since keyboard in telegram is an <em>array of array of strings</em>, <strong>at first</strong> you should create a "row of buttons" (first array) and <strong>only after that</strong> add it to keyboard (second array) <em>as one element</em>. Something like this:</p>
<pre><code>keyboard = []
row1 = ["card1", "card2", "card3"]
keyboard.append(row1)
row2 = ["card4", "card5", "card6"]
keyboard.append(row2)
print (keyboard)
>>>
[['card1', 'card2', 'card3'], ['card4', 'card5', 'card6']]
</code></pre>
<p>You may put it into a cycle, so it would be created dynamicly as you wish.</p>
| 0 |
2016-09-28T18:50:58Z
|
[
"python",
"telegram",
"python-telegram-bot"
] |
While loop returned nothing at all and removing duplicates of min max
| 39,673,339 |
<p>1) upon entering input >> 1 2 3 4 5 6 7
the result returned nothing. Must be the while loop i supposed? </p>
<p>2) Also for input such as >> 1 1 1 5 5 7 7 7 7
how do i remove duplicate of 1 and 7? ; meaning duplicate of min and max.
I plan to average the number input by removing duplicate of min and max.
Do i combine max() min() function with list(set(x)) or is there another way round?</p>
<p>New to python here. WHILE permitted only. Do not suggest For</p>
<pre><code>even_sum, odd_sum = 0,0
evencount, oddcount = 0,0
count=0
n=0
s = raw_input("Please Input a series of numbers")
numbers = map(int, s.split())
while count<numbers:
if numbers[n]%2==0:
evencount = evencount +1# len(numbers)
even_sum += num
count=count+1
n=n+1
else:
oddcount = oddcount+1#len(numbers)
odd_sum += num
count=count+1
n=n+1
max123 = max(numbers)
min123 = min(numbers)
difference = max123 - min123
print numbers
numbers.remove(max(numbers))
numbers.remove(min(numbers))
average = sum(numbers)/float(len(numbers))
print "The summation of even and odd numbers are " + str(even_sum) + " and " + str(odd_sum)
print "The difference between biggest and smallest number is " + str(difference)
print "The count of even numbers and odd numbers are " + str(evencount) + " & " + str(oddcount)
print average
</code></pre>
| 0 |
2016-09-24T06:38:06Z
| 39,673,553 |
<p>This is wrong:</p>
<pre><code>while count<numbers:
</code></pre>
<p>You are comparing a number to a list. That is valid, but it does not do what you might expect. <code>count<numbers</code> is always true, so you are stuck in an infinite loop. Try it:</p>
<pre><code>>>> 1000000 < [1, 2]
True
</code></pre>
<p>What you want to do instead is iterate through all numbers.</p>
<pre><code>for number in numbers:
if number % 2 == 0:
...
</code></pre>
<p>You don't need <code>count</code> and you don't need <code>n</code> either.</p>
<hr>
<p>Also, the <code>else:</code> should be indented, otherwise it will never be executed with this code.</p>
<hr>
<p><strong>Handicap mode</strong> (without <code>for</code>)</p>
<pre><code>n = 0
odd_count = 0
odd_sum = 0
while n < len(numbers):
number = numbers[n]
if number % 2:
odd_count += 1
odd_sum += number
n += 1
# "even" values can be calculated from odds and totals
</code></pre>
| 0 |
2016-09-24T07:03:59Z
|
[
"python"
] |
While loop returned nothing at all and removing duplicates of min max
| 39,673,339 |
<p>1) upon entering input >> 1 2 3 4 5 6 7
the result returned nothing. Must be the while loop i supposed? </p>
<p>2) Also for input such as >> 1 1 1 5 5 7 7 7 7
how do i remove duplicate of 1 and 7? ; meaning duplicate of min and max.
I plan to average the number input by removing duplicate of min and max.
Do i combine max() min() function with list(set(x)) or is there another way round?</p>
<p>New to python here. WHILE permitted only. Do not suggest For</p>
<pre><code>even_sum, odd_sum = 0,0
evencount, oddcount = 0,0
count=0
n=0
s = raw_input("Please Input a series of numbers")
numbers = map(int, s.split())
while count<numbers:
if numbers[n]%2==0:
evencount = evencount +1# len(numbers)
even_sum += num
count=count+1
n=n+1
else:
oddcount = oddcount+1#len(numbers)
odd_sum += num
count=count+1
n=n+1
max123 = max(numbers)
min123 = min(numbers)
difference = max123 - min123
print numbers
numbers.remove(max(numbers))
numbers.remove(min(numbers))
average = sum(numbers)/float(len(numbers))
print "The summation of even and odd numbers are " + str(even_sum) + " and " + str(odd_sum)
print "The difference between biggest and smallest number is " + str(difference)
print "The count of even numbers and odd numbers are " + str(evencount) + " & " + str(oddcount)
print average
</code></pre>
| 0 |
2016-09-24T06:38:06Z
| 39,673,837 |
<pre><code>#This is modified code i did mark (#error) where your program didn't work
even_sum, odd_sum = 0,0
evencount, oddcount = 0,0
count=0
n=0
s = raw_input("Please Input a series of numbers")
numbers = map(int, s.split())
print (numbers)
while count<len(numbers): #error thats a list you have to convert that in to int
if numbers[n]%2==0:
evencount = evencount +1# len(numbers)
even_sum += numbers[n] #error index and variable not defined
count=count+1
n=n+1
else: #indented error
oddcount = oddcount+1#len(numbers)
odd_sum += numbers[n] #error index and variable not defined
count=count+1
n=n+1
max123 = max(numbers)
min123 = min(numbers)
difference = max123 - min123
numbers.remove(max(numbers))
numbers.remove(min(numbers))
average = sum(numbers)/float(len(numbers))
print "The summation of even and odd numbers are " + str(even_sum) + " and " + str(odd_sum)
print "The difference between biggest and smallest number is " + str(difference)
print "The count of even numbers and odd numbers are " + str(evencount) + " & " + str(oddcount)
</code></pre>
| 0 |
2016-09-24T07:39:54Z
|
[
"python"
] |
django upload multiple file and then save the path to database
| 39,673,341 |
<p>I want to upload multiple image files using form, and the images then save in the <code>./static/</code>, the path of the images then save to database, when I use <code>request.FIELS.getlist("files")</code> in for, when using the <code>save()</code>, there is only one image's name save in databse, and the real images not save in the <code>./static/</code></p>
<p><strong>models.py</strong></p>
<pre><code>class User(models.Model):
username = models.CharField(max_length=200)
headImg = models.FileField(upload_to='./upload/')
is_excuted = models.BooleanField(default=False)
time = models.DateField(default=timezone.now)
score = models.DecimalField(max_digits=2, decimal_places=2, default=0.00)
</code></pre>
<p><strong>view.py</strong></p>
<pre><code>class UserForm(forms.Form):
username = forms.CharField()
def register(request):
if request.method == "POST":
uf = UserForm(request.POST, request.FILES)
if uf.is_valid():
username = uf.cleaned_data['username']
for f in request.FILES.getlist("files"):
user = User()
user.username = username
user.headImg = f.name
user.save()
return HttpResponse('upload ok!')
else:
uf = UserForm()
return render_to_response('register.html',{'uf':uf})
</code></pre>
| 0 |
2016-09-24T06:38:24Z
| 39,679,700 |
<p>You can use <a href="https://github.com/Chive/django-multiupload" rel="nofollow">django-multiupload</a> copying example from git.</p>
<pre><code># forms.py
from django import forms
from multiupload.fields import MultiFileField
class UploadForm(forms.Form):
attachments = MultiFileField(min_num=1, max_num=3, max_file_size=1024*1024*5)
# If you need to upload media files, you can use this:
attachments = MultiMediaField(
min_num=1,
max_num=3,
max_file_size=1024*1024*5,
media_type='video' # 'audio', 'video' or 'image'
)
# For images (requires Pillow for validation):
attachments = MultiImageField(min_num=1, max_num=3, max_file_size=1024*1024*5)
# models.py
from django.db import models
class Attachment(models.Model):
file = models.FileField(upload_to='attachments')
# views.py
from django.views.generic.edit import FormView
from .forms import UploadForm
from .models import Attachment
class UploadView(FormView):
template_name = 'form.html'
form_class = UploadForm
success_url = '/done/'
def form_valid(self, form):
for each in form.cleaned_data['attachments']:
Attachment.objects.create(file=each)
return super(UploadView, self).form_valid(form)
</code></pre>
| 0 |
2016-09-24T18:35:49Z
|
[
"python",
"django",
"database"
] |
How to extract rows from an numpy array based on the content?
| 39,673,377 |
<p>As title, for example, I have an 2d numpy array, like the one below, </p>
<pre><code>[[33, 21, 1],
[33, 21, 2],
[32, 22, 0],
[33, 21, 3],
[34, 34, 1]]
</code></pre>
<p>and I want to extract these rows orderly based on the content in the first and the second column, in this case, I want to get 3 different 2d numpy arrays, as below, </p>
<pre><code>[[33, 21, 1],
[33, 21, 2],
[33, 21, 3]]
</code></pre>
<p>and </p>
<pre><code>[[32, 22, 0]]
</code></pre>
<p>and </p>
<pre><code>[[34, 34, 1]]
</code></pre>
<p>What function in numpy could I use to do this? I think the point is to distinguish different rows with their first and second columns. If elements in these columns are the same, then the specific rows are categorized in the same output array. <strong>I want to write a python function to do this kind of job, because I could have a much more bigger array than the one above.</strong> Feel free to give me advice, thank you.</p>
| 3 |
2016-09-24T06:42:51Z
| 39,673,729 |
<p>You would use boolean indexing to do this. To obtain the three examples you give (in the same order as you posted them, where <code>x</code> is your original 2d array), you could write:</p>
<pre><code>numpy.atleast_2d( x[ x[:,1]==21 ] )
numpy.atleast_2d( x[ x[:,2]==0 ] )
numpy.atleast_2d( x[ x[:,2]==1 ] )
</code></pre>
<p>The first should be interpreted as saying 'extract the rows of <code>x</code> where the element in the second column equals 21' and so on. There is a page in the scipy docs that explains how to use indexing in numpy <a href="http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html" rel="nofollow" title="here">here</a>. Since you required that the returned arrays all be 2D, I have used the <code>atleast_2d</code> function.</p>
| 1 |
2016-09-24T07:25:59Z
|
[
"python",
"arrays",
"numpy"
] |
How to extract rows from an numpy array based on the content?
| 39,673,377 |
<p>As title, for example, I have an 2d numpy array, like the one below, </p>
<pre><code>[[33, 21, 1],
[33, 21, 2],
[32, 22, 0],
[33, 21, 3],
[34, 34, 1]]
</code></pre>
<p>and I want to extract these rows orderly based on the content in the first and the second column, in this case, I want to get 3 different 2d numpy arrays, as below, </p>
<pre><code>[[33, 21, 1],
[33, 21, 2],
[33, 21, 3]]
</code></pre>
<p>and </p>
<pre><code>[[32, 22, 0]]
</code></pre>
<p>and </p>
<pre><code>[[34, 34, 1]]
</code></pre>
<p>What function in numpy could I use to do this? I think the point is to distinguish different rows with their first and second columns. If elements in these columns are the same, then the specific rows are categorized in the same output array. <strong>I want to write a python function to do this kind of job, because I could have a much more bigger array than the one above.</strong> Feel free to give me advice, thank you.</p>
| 3 |
2016-09-24T06:42:51Z
| 39,674,145 |
<p>Here's an approach to handle many such groupings -</p>
<pre><code># Sort array based on second column
sorted_a = a[np.argsort(a[:,1])]
# Get shifting indices for first col. Split along axis=0 using those.
shift_idx = np.unique(sorted_a[:,1],return_index=True)[1][1:]
out = np.split(sorted_a,shift_idx)
</code></pre>
<p>Alternatively, for performance efficiency purposes, we can get <code>shift_idx</code>, like so -</p>
<pre><code>shift_idx = np.flatnonzero(sorted_a[1:,1] > sorted_a[:-1,1])+1
</code></pre>
<p>Sample run -</p>
<pre><code>In [27]: a
Out[27]:
array([[33, 21, 1],
[33, 21, 2],
[32, 22, 0],
[33, 21, 3],
[34, 34, 1]])
In [28]: sorted_a = a[np.argsort(a[:,1])]
In [29]: np.split(sorted_a,np.unique(sorted_a[:,1],return_index=True)[1][1:])
Out[29]:
[array([[33, 21, 1],
[33, 21, 2],
[33, 21, 3]]), array([[32, 22, 0]]), array([[34, 34, 1]])]
</code></pre>
| 1 |
2016-09-24T08:18:45Z
|
[
"python",
"arrays",
"numpy"
] |
How to extract rows from an numpy array based on the content?
| 39,673,377 |
<p>As title, for example, I have an 2d numpy array, like the one below, </p>
<pre><code>[[33, 21, 1],
[33, 21, 2],
[32, 22, 0],
[33, 21, 3],
[34, 34, 1]]
</code></pre>
<p>and I want to extract these rows orderly based on the content in the first and the second column, in this case, I want to get 3 different 2d numpy arrays, as below, </p>
<pre><code>[[33, 21, 1],
[33, 21, 2],
[33, 21, 3]]
</code></pre>
<p>and </p>
<pre><code>[[32, 22, 0]]
</code></pre>
<p>and </p>
<pre><code>[[34, 34, 1]]
</code></pre>
<p>What function in numpy could I use to do this? I think the point is to distinguish different rows with their first and second columns. If elements in these columns are the same, then the specific rows are categorized in the same output array. <strong>I want to write a python function to do this kind of job, because I could have a much more bigger array than the one above.</strong> Feel free to give me advice, thank you.</p>
| 3 |
2016-09-24T06:42:51Z
| 39,771,892 |
<p>The <a href="https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP" rel="nofollow">numpy_indexed</a> package (disclaimer: I am its author) contains functionality to efficiently perform these type of operations:</p>
<pre><code>import numpy_indexed as npi
npi.group_by(a[:, :2]).split(a)
</code></pre>
| 1 |
2016-09-29T13:37:46Z
|
[
"python",
"arrays",
"numpy"
] |
Matplotlib: align xtick labels
| 39,673,434 |
<p>I have generated the following plot using the code below. I would like to position the <code>xtick</code> labels at appropriate place. Currently, it is misleading and the first label <code>12/06</code> is missing.</p>
<p><a href="http://i.stack.imgur.com/HBYbL.png" rel="nofollow"><img src="http://i.stack.imgur.com/HBYbL.png" alt="enter image description here"></a></p>
<p>The code is as follows:</p>
<pre><code>import matplotlib.pyplot as plt
import datetime as dt
import matplotlib.dates as mdates
list_date =
['2016-06-12',
'2016-06-13',
'2016-06-14',
'2016-06-15',
'2016-06-16',
'2016-06-17',
'2016-06-18',
'2016-06-19',
'2016-06-20',
'2016-06-21',
'2016-06-22',
'2016-06-23',
'2016-06-24',
'2016-06-25',
'2016-06-26',
'2016-06-27',
'2016-06-28',
'2016-06-29',
'2016-06-30',
'2016-07-01',
'2016-07-02',
'2016-07-03',
'2016-07-04',
'2016-07-05',
'2016-07-06',
'2016-07-07',
'2016-07-08',
'2016-07-09']
list_count =
[9490,
595442,
566104,
664133,
655221,
612509,
607395,
597703,
613051,
635764,
705905,
535869,
583516,
630818,
641495,
697591,
578071,
547280,
561775,
581784,
594175,
552944,
545131,
493400,
604280,
510182,
518883,
413648]
date = [dt.datetime.strptime(d,'%Y-%m-%d').date() for d in list_date]
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%d/%m'))
plt.gca().xaxis.set_major_locator(mdates.DayLocator(interval=2))
plt.bar(date, list_count, align = 'center')
plt.gcf().autofmt_xdate()
plt.grid()
plt.xlabel("Period from 12/06/2016 to 09/07/2016")
plt.ylabel("Daily hits")
plt.title("Count of daily visitors")
plt.show()
</code></pre>
| 0 |
2016-09-24T06:49:03Z
| 39,673,580 |
<p>You can customize the position of the x-ticks by explicitly passing a list, e.g. to mark every date in your list with a tick, you would do</p>
<pre><code>plt.gca().xaxis.set_ticks(date)
</code></pre>
<p>instead of</p>
<pre><code>plt.gca().xaxis.set_major_locator(mdates.DayLocator(interval=2))
</code></pre>
<p>to avoid over-dense ticks, you could pass e.g. <code>date[::2]</code>.</p>
| 1 |
2016-09-24T07:06:57Z
|
[
"python",
"python-2.7",
"matplotlib",
"data-visualization"
] |
Split and check first 8 digits are met
| 39,673,640 |
<p>I have some data that looks like this, when reading this data from a file, is there a way to only add to the list if the first 8 digits are met?</p>
<pre><code>11111111 ABC Data1
</code></pre>
<p>my current method is only splitting the space in between</p>
<pre><code>Number = descr.split(' ')[0]
</code></pre>
| 0 |
2016-09-24T07:14:06Z
| 39,945,261 |
<p>If you want to only add a 8 digit number from an input string, do it as shown below</p>
<pre><code>descr = input()
reqd_int = int( descr.split(' ')[0:8] )
</code></pre>
<p>This will fail if the input contains less than 8 integers at the start.</p>
<p>The other option is to use regular expressions, use it as shown below</p>
<pre><code>import re
reqd_int = int(re.search('\d{8}', descr))
</code></pre>
<p>What the re.search() function does is,for the first paramete, <code>\d</code> stands for single integers and the <code>{8}</code> tells it to look 8 such contagious block of integers.</p>
<p>You can look up more on regular expressions <a href="https://duckduckgo.com/?q=regex+cheat+sheet&ia=cheatsheet" rel="nofollow">here</a>.</p>
| 0 |
2016-10-09T15:28:03Z
|
[
"python",
"python-3.x"
] |
Script which replaces specific words in text by asterisks (Python)
| 39,673,720 |
<p>I tried to create a function which finds a censored word (which is an argument of the function) in a text (which is a second argument) and replaces all the instances of the word with astrerisks. </p>
<pre><code>def censor(text, word):
if word in text:
position = text.index(word)
new_text = text[0: position] + "*"*len(word) + text[position+len(word):]
censor(new_text,word)
else:
return text
phrase_with = raw_input("Type the sentence")
foo= raw_input("Type the censored word")
print censor(phrase_with, foo)
</code></pre>
<p>But when I call the function inside the function itself it stops working. </p>
<p>And returns "<strong>None</strong>". Why? How can I make it work? </p>
<p>And what are the rules of callling a function within the same function?</p>
| 0 |
2016-09-24T07:24:44Z
| 39,673,800 |
<p>You need to return the recursive result like this: </p>
<pre><code>def censor(text, word):
if word in text:
position = text.index(word)
new_text = text[0: position] + "*"*len(word) + text[position+len(word):]
return censor(new_text,word) # <-- Add return here
else:
return text
phrase_with_fuck = raw_input("Type the sentence")
fuck = raw_input("Type the censored word")
print censor(phrase_with_fuck, fuck)
</code></pre>
<p>This happens because the function ends in the <code>if</code> statement, resulting None.</p>
| 0 |
2016-09-24T07:36:04Z
|
[
"python"
] |
elasticsearch-py 2.4.0 for python does not contain delete_by_query() function.
| 39,673,888 |
<p>elasticsearch-py 2.4.0 for python does not contain delete_by_query() function. So How can I delete documents based on the query in elasticsearch 2.4.0 library?</p>
| 0 |
2016-09-24T07:46:09Z
| 39,676,774 |
<p>From Elasticsearch version 2.x, delete_by_query feature has been removed and moved as plugin. Reference <a href="https://www.elastic.co/guide/en/elasticsearch/plugins/current/delete-by-query-plugin-reason.html" rel="nofollow">here</a></p>
<p>If you want to delete multiple documents using python, use <a href="http://elasticsearch-py.readthedocs.io/en/master/helpers.html" rel="nofollow">bulk helpers</a></p>
<p>Generate the list of document ids using search query and pass the list to bulk delete.</p>
| 0 |
2016-09-24T13:19:51Z
|
[
"python",
"django",
"elasticsearch"
] |
TypeError: sequence item 0 expected str instance, bytes found
| 39,673,901 |
<p>I am doing python challenge but when in mission 6 I met some problems:</p>
<pre><code>comments = []
comments.append(file_zip.getinfo('%s.txt'%name).comment)
print(''.join(comments))
</code></pre>
<p>but this give me the error</p>
<p>TypeError: sequence item 0: expected str instance, bytes found</p>
<p>I looked for the answer, and have a try like this:</p>
<pre><code>print(b''.join(comments))
</code></pre>
<p>it works.</p>
<pre><code> b'***************************************************************\n****************************************************************\n** **\n** OO OO XX YYYY GG GG EEEEEE NN NN **\n** OO OO XXXXXX YYYYYY GG
GG EEEEEE NN NN **\n** OO OO XXX XXX YYY YY GG GG EE NN NN **\n** OOOOOOOO XX XX YY GGG EEEEE NNNN **\n** OOOOOOOO XX XX YY GGG EEEEE NN **\n** OO OO XXX XXX YYY YY GG GG EE NN **\n**
OO OO XXXXXX YYYYYY GG GG EEEEEE NN **\n** OO OO XX YYYY GG GG EEEEEE NN
</code></pre>
<p>I think it regards <code>'/n'</code> as a char and print it,but I don't want that, how can I make it work?</p>
| 0 |
2016-09-24T07:47:48Z
| 39,675,192 |
<p>The issue is that <code>file_zip.getinfo('%s.txt'%name).comment</code> apparently returns a <code>bytes</code> object(s). When you try and join on an <code>str</code>, namely <code>''.join(..)</code> you get the error:</p>
<pre><code>''.join([b'hello', b'\n', b'world'])
TypeError: sequence item 0: expected str instance, bytes found
</code></pre>
<p>Joining on <code>b''</code> is a viable alternative but, as you note, it doesn't escape special characters like <code>'\n'</code>; that's expected behavior for <code>bytes</code> instances. </p>
<p>You can either <code>decode</code> the string after it has been <code>join</code>ed on <code>b''</code>:</p>
<pre><code>print(b''.join(comments).decode())
</code></pre>
<p>Or, <code>decode</code> every element of <code>comments</code> with <code>map</code> and <code>join</code> on an empty string <code>''</code> as you originally attempted:</p>
<pre><code>print(''.join(map(bytes.decode, comments)))
</code></pre>
| 0 |
2016-09-24T10:13:50Z
|
[
"python",
"string",
"python-3.x"
] |
How do i get list instead of list of list?
| 39,673,932 |
<p>I am trying to read a text file with the following format <code>"a b c d e f g h"</code>. I take a new empty list <code>word = []</code></p>
<p>My code is:</p>
<pre><code>f = open("letters.txt")
word = []
for line in f:
line = line.split(" ")
word.append(line)
print(word)
</code></pre>
<p>However, it has given me a list of list like this:</p>
<pre><code>[['a', 'b', 'c', 'd', 'e', 'f']]
</code></pre>
<p>But I want to get it in a single list instead?</p>
<p>eg:</p>
<pre><code>['a', 'b', 'c']
</code></pre>
| -3 |
2016-09-24T07:51:25Z
| 39,673,959 |
<p>Try like this,</p>
<pre><code>word = open("letters.txt").read().split()
</code></pre>
<p><strong>Result</strong></p>
<pre><code>['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
</code></pre>
| 0 |
2016-09-24T07:54:56Z
|
[
"python",
"list",
"readfile"
] |
How do i get list instead of list of list?
| 39,673,932 |
<p>I am trying to read a text file with the following format <code>"a b c d e f g h"</code>. I take a new empty list <code>word = []</code></p>
<p>My code is:</p>
<pre><code>f = open("letters.txt")
word = []
for line in f:
line = line.split(" ")
word.append(line)
print(word)
</code></pre>
<p>However, it has given me a list of list like this:</p>
<pre><code>[['a', 'b', 'c', 'd', 'e', 'f']]
</code></pre>
<p>But I want to get it in a single list instead?</p>
<p>eg:</p>
<pre><code>['a', 'b', 'c']
</code></pre>
| -3 |
2016-09-24T07:51:25Z
| 39,674,004 |
<p>You can print your line instead.</p>
<pre><code>f = open("letters.txt")
for line in f:
line = line.split(" ")
print line
</code></pre>
| 0 |
2016-09-24T08:01:50Z
|
[
"python",
"list",
"readfile"
] |
How do i get list instead of list of list?
| 39,673,932 |
<p>I am trying to read a text file with the following format <code>"a b c d e f g h"</code>. I take a new empty list <code>word = []</code></p>
<p>My code is:</p>
<pre><code>f = open("letters.txt")
word = []
for line in f:
line = line.split(" ")
word.append(line)
print(word)
</code></pre>
<p>However, it has given me a list of list like this:</p>
<pre><code>[['a', 'b', 'c', 'd', 'e', 'f']]
</code></pre>
<p>But I want to get it in a single list instead?</p>
<p>eg:</p>
<pre><code>['a', 'b', 'c']
</code></pre>
| -3 |
2016-09-24T07:51:25Z
| 39,674,007 |
<p>@Rahul's answer is correct. But this should help you understands when not to use <code>append</code></p>
<p><code>append(x)</code> adds x as a new element on the end of the list. It doesn't matter what x is <code>extend</code> would have worked.</p>
<pre><code>>>> l = []
>>> l.append(1)
>>> l.append('a')
>>> l.append({1,2,3})
>>> l.append([1,2,3])
>>> l
[1, 'a', set([1, 2, 3]), [1, 2, 3]]
>>>
>>>
>>> l = []
>>> l.extend(1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
>>> l.extend([1])
>>> l.extend([4,5,6])
>>> l
[1, 4, 5, 6]
</code></pre>
| 0 |
2016-09-24T08:02:15Z
|
[
"python",
"list",
"readfile"
] |
How do i get list instead of list of list?
| 39,673,932 |
<p>I am trying to read a text file with the following format <code>"a b c d e f g h"</code>. I take a new empty list <code>word = []</code></p>
<p>My code is:</p>
<pre><code>f = open("letters.txt")
word = []
for line in f:
line = line.split(" ")
word.append(line)
print(word)
</code></pre>
<p>However, it has given me a list of list like this:</p>
<pre><code>[['a', 'b', 'c', 'd', 'e', 'f']]
</code></pre>
<p>But I want to get it in a single list instead?</p>
<p>eg:</p>
<pre><code>['a', 'b', 'c']
</code></pre>
| -3 |
2016-09-24T07:51:25Z
| 39,674,056 |
<p>You should know what data is in each variable in each line of the code. If you don't know - print it and then you will know.</p>
<p>I'll do it for you this time ;)</p>
<pre><code>f = open("letters.txt")
# f is an open file object. BTW, you never close it.
# Consider: with open("letters.txt", "rt") as f:
word = []
# 'word' is a list. That is strange, why not 'words = []'?
for line in f:
# 'line' is a string. Fine.
line = line.split(" ")
# 'line' is no longer a string. Not fine.
# This is perfectly valid code, but bad practice.
# Don't change the type of data stored in a variable,
# or you'll run into problems understanding what your code does.
# Make a new variable, if you need one, e.g. 'line_words'.
# Anyway, 'line' is now a list of words. Whatever.
word.append(line)
# This added a list (line) into another list (word).
# Now it is a list of lists. There is your error.
# 'word += line' would do what you wanted.
</code></pre>
<p>All together:</p>
<pre><code>with open("letters.txt", "rt") as f:
words = []
for line in f:
words += line.split()
</code></pre>
| 0 |
2016-09-24T08:07:10Z
|
[
"python",
"list",
"readfile"
] |
How do i get list instead of list of list?
| 39,673,932 |
<p>I am trying to read a text file with the following format <code>"a b c d e f g h"</code>. I take a new empty list <code>word = []</code></p>
<p>My code is:</p>
<pre><code>f = open("letters.txt")
word = []
for line in f:
line = line.split(" ")
word.append(line)
print(word)
</code></pre>
<p>However, it has given me a list of list like this:</p>
<pre><code>[['a', 'b', 'c', 'd', 'e', 'f']]
</code></pre>
<p>But I want to get it in a single list instead?</p>
<p>eg:</p>
<pre><code>['a', 'b', 'c']
</code></pre>
| -3 |
2016-09-24T07:51:25Z
| 39,674,098 |
<p>You can try like this after getting your current result:</p>
<pre><code>import itertools
a = [["a","b"], ["c"]]
print list(itertools.chain.from_iterable(a))
</code></pre>
| 0 |
2016-09-24T08:11:48Z
|
[
"python",
"list",
"readfile"
] |
How do i get list instead of list of list?
| 39,673,932 |
<p>I am trying to read a text file with the following format <code>"a b c d e f g h"</code>. I take a new empty list <code>word = []</code></p>
<p>My code is:</p>
<pre><code>f = open("letters.txt")
word = []
for line in f:
line = line.split(" ")
word.append(line)
print(word)
</code></pre>
<p>However, it has given me a list of list like this:</p>
<pre><code>[['a', 'b', 'c', 'd', 'e', 'f']]
</code></pre>
<p>But I want to get it in a single list instead?</p>
<p>eg:</p>
<pre><code>['a', 'b', 'c']
</code></pre>
| -3 |
2016-09-24T07:51:25Z
| 39,675,251 |
<p><a href="https://docs.python.org/2/library/stdtypes.html#str.split" rel="nofollow"><code>split</code></a> returns a list </p>
<blockquote>
<p>Return a list of the words in the string, using sep as the delimiter string.</p>
</blockquote>
<p>This list is appended <em>as a whole</em> at the end of <code>word</code>. This is why you get a list of lists </p>
<pre><code>word [
[ result of split of first line ]
[ result of split of second line ]
[ result of split of third line ]
[ ... ]
]
</code></pre>
<p>If you want to add each element of the list, instead of appending the list as a whole, you may use <a href="https://docs.python.org/2/tutorial/datastructures.html#more-on-lists" rel="nofollow"><code>extend</code></a>, i.e.</p>
<pre><code>for line in f:
a = line.split(" ")
word.extend(a)
</code></pre>
<p>Although you might want to strip the trailing newline with <a href="https://docs.python.org/2/library/string.html#string.rstrip" rel="nofollow"><code>rstrip</code></a>, when reading multiple lines</p>
<pre><code>a = line.rstrip().split(" ")
</code></pre>
<p>or just use <code>None</code> as word separator</p>
<blockquote>
<p>If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a None separator returns [].</p>
</blockquote>
<pre><code>a = line.split()
</code></pre>
| 0 |
2016-09-24T10:20:04Z
|
[
"python",
"list",
"readfile"
] |
How do i get list instead of list of list?
| 39,673,932 |
<p>I am trying to read a text file with the following format <code>"a b c d e f g h"</code>. I take a new empty list <code>word = []</code></p>
<p>My code is:</p>
<pre><code>f = open("letters.txt")
word = []
for line in f:
line = line.split(" ")
word.append(line)
print(word)
</code></pre>
<p>However, it has given me a list of list like this:</p>
<pre><code>[['a', 'b', 'c', 'd', 'e', 'f']]
</code></pre>
<p>But I want to get it in a single list instead?</p>
<p>eg:</p>
<pre><code>['a', 'b', 'c']
</code></pre>
| -3 |
2016-09-24T07:51:25Z
| 39,675,797 |
<p>Or you can simply kind of <strong>unflatten</strong> your list:</p>
<pre><code>ls = [['a', 'b', 'c', 'd', 'e', 'f']]
ls = [i for sub_list in ls for i in sub_list]
</code></pre>
<p>The result will be:</p>
<pre><code>>>> ls
['a', 'b', 'c', 'd', 'e', 'f']
</code></pre>
| 0 |
2016-09-24T11:27:24Z
|
[
"python",
"list",
"readfile"
] |
Unknowing odoo Data base logout issue
| 39,673,951 |
<p>Database logout unnecessarily and trying to login once again it give error:email/password is wrong in odoo/postgresql.(i noted down the email and password) and these fields are can't be wrong.
i made a changes in inherited sale module report.xml file(qweb)</p>
<pre><code><strong t-field="company.partner_id" style="font-size:18px;"
t-field-options='{"widget": "contact", "fields": ["name"]}'> </strong>
</code></pre>
<p>to </p>
<pre><code><strong t-field="company.partner_id" style="font-size:20px;"
t-field-options='{"widget": "contact", "fields": ["name"]}'></strong>
</code></pre>
<p>when i revert back original code tried login once but not at all logging into database. help me to solve the problem.</p>
| 0 |
2016-09-24T07:54:00Z
| 39,716,258 |
<p>you must have mistyped your password when you changed it, the change in your qweb view is not related.</p>
<p>The solution is to log in to your postgre database directly and change your admin password using this SQL command:</p>
<pre><code>UPDATE res_users SET password='your-new-password' WHERE id=1;
</code></pre>
| 0 |
2016-09-27T04:57:53Z
|
[
"python",
"postgresql",
"openerp",
"odoo-9"
] |
How to decode a 16-bit ASCII data to an integer when you have it in a string of 2 characters in python using struct module?
| 39,673,995 |
<p>Here is my code. <strong>Ideally both struct.unpack and encode('hex') and changing it back to int should be the same right?</strong></p>
<p>INPUT -</p>
<blockquote>
<p>But, they are <strong>not</strong> the same in this case when you give a .wav file with nchannels = 1, samplewidth = 2, framerate = 44100, comptype = "None", compname = "Not compressed"</p>
</blockquote>
<p>SAMPLE OUTPUT -</p>
<blockquote>
<p>-15638 == eac2 == 27330</p>
<p>-15302 == 3ac4 == 15044</p>
<p>-14905 == c7c5 == 18373</p>
<p>-14449 == 8fc7 == 4039</p>
<p><em>The left and right hand-side should be equal right?</em></p>
</blockquote>
<pre><code>import wave
import sys
import struct
audiofile = wave.open(sys.argv[1], 'r')
# reading a file (normal file open)
print audiofile.getparams()
# (nchannels, sampwidth, framerate, nframes, comptype, compname)
for i in range(audiofile.getnframes()):
frame = audiofile.readframes(1)
# reading each frame (Here frame is 16 bits [.wav format of each frame])
print struct.unpack('<h', frame)[0], ' == ',
# struct.unpack(fmt, string) --- for more info about fmt -> https://docs.python.org/2/library/struct.html
# If we it is two samples per frame, then we get a tuple with two values -> left and right samples
value = int(frame.encode('hex'), 16)
# getting the 16-bit value [each frame is 16 bits]
if(value > 32767):
value -= 2**16
# because wav file format specifies 2's compliment as in even the negative values are there
print frame.encode('hex') , ' == ', value
audiofile.close()
</code></pre>
| 0 |
2016-09-24T08:00:40Z
| 39,674,066 |
<p>The difference is between big-endian and little-endian encoding.</p>
<p>Your struct is big-endian, while the conversion with hex is little-endian.</p>
| 0 |
2016-09-24T08:08:18Z
|
[
"python",
"codec",
"wave"
] |
How to print cloned list once and load them in dictionary in Python?
| 39,674,028 |
<ol>
<li><p>my input file: </p>
<pre><code>cs 124456 powerful
cs 124456 powerful
me 125454 easy
me 125455 easy
me 125455 easy
ec 125555 done
ec 127678 fine
ec 127678 fine
ci 127678 fine
ci 127678 fine
eee 125678 good
eee 125678 good
eee 125678 good
eee 125678 bad`
</code></pre></li>
<li><p>Expected output:</p>
<pre><code>no.name reg perform
1.cs 124456 powerful
2.me 125454 easy
3.me 125455 easy
4.ec 125555 done
5.ec 127678 fine
6.ci 127678 fine
7.eee 125678 good
8.eee 125678 bad
</code></pre></li>
<li><p>my code:</p>
<pre><code> import os
os.chdir("d:/filer")
import re
def first(line):
f=re.findall("[a-z]+",line,flags=0)
return f
def num(line):
n=re.findall("\d{6}",line,flags=0)
return n
with open("once.txt","r") as sa:
for line in sa.readlines():
home=first(line)
number=num(line)
x=home[0]
y=number[0]
z=home[1]
if x!=0 and y!=0 and z!=0:
print [x,y,z]
</code></pre></li>
<li><p>I opened file and read them line by line. Then I extracted those numbers and text using regular expression and stored in list with indexes. Now I want only lists which are unique and not cloned. Then load them to dictionary. Can somebody help me?</p></li>
</ol>
| 0 |
2016-09-24T08:04:48Z
| 39,676,281 |
<p>In order to prevent cloning, you may use a <a href="https://docs.python.org/3.6/tutorial/datastructures.html#sets" rel="nofollow"><code>set()</code></a> like so:</p>
<pre><code>results = set() # Construct a set
with open("once.txt","r") as sa:
for line in sa.readlines():
home=first(line)
number=num(line)
x=home[0]
y=number[0]
z=home[1]
if x!=0 and y!=0 and z!=0:
if (x,y,z) not in results: # Check if the set already contains the result
results.add((x,y,z)) # If it doesn't, add to the set and print.
print [x,y,z]
</code></pre>
<hr>
<p>I also suggest organizing your code a little. You can just create 1 regex for clarity like so:</p>
<pre><code>results = set() # Construct a set
with open("once.txt","r") as sa:
count = 0
for line in sa: # No need for readlines()
match = re.match(r"(\w+)\s+(\d+)\s+(\w+)")
if match is None:
continue
result = match.groups()
if result not in results: # Check if the set already contains the result
count += 1
results.add(result) # If it doesn't, add to the set and print.
print count, result
</code></pre>
| 0 |
2016-09-24T12:21:18Z
|
[
"python",
"list",
"python-2.7",
"fileparsing"
] |
Ambari 2.4.1.0 Build Failure
| 39,674,072 |
<p>When I trying to build ambari version 2.4.1.0 in ubuntu 14.04, but it failed while building ambari metrics grafana below is the error am getting, Please suggest if I done something wrong the commend used to build the metrics is </p>
<pre><code> mvn -B clean install package jdeb:jdeb -DnewVersion=2.4.1.0.0 -DskipTests -Dpython.ver="python >= 2.6"
[INFO] --- jdeb:1.0.1:jdeb (default-cli) @ ambari-metrics-grafana ---
[WARNING] Creating empty debian package.
[ERROR] Failed to create debian package /home/hdfs/ambari/ambari/ambari-metrics/ambari-metrics-grafana/target/ambari-metrics-grafana_2.1.0.0.0_all.deb
org.vafer.jdeb.PackagingException: "/home/hdfs/ambari/ambari/ambari-metrics/ambari-metrics-grafana/src/main/package/deb/control" is not a valid 'control' directory)
at org.vafer.jdeb.maven.DebMaker.makeDeb(DebMaker.java:186)
at org.vafer.jdeb.maven.DebMojo.execute(DebMojo.java:409)
at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:134)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:207)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:116)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:80)
at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:51)
at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128)
at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:307)
at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:193)
at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:106)
at org.apache.maven.cli.MavenCli.execute(MavenCli.java:863)
at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:288)
at org.apache.maven.cli.MavenCli.main(MavenCli.java:199)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
at org.codehaus.plexus.c
</code></pre>
<p>lassworlds.launcher.Launcher.main(Launcher.java:356)</p>
| 0 |
2016-09-24T08:09:14Z
| 39,804,738 |
<p>in the pom.xml file - [ambari-metrics/ambari-metrics-grafana/]. Please add the following:</p>
<pre><code><plugin>
<groupId>org.vafer</groupId>
<artifactId>jdeb</artifactId>
<version>1.0.1</version>
<executions>
<execution>
<!--Stub execution on direct plugin call - workaround for ambari deb build process-->
<id>stub-execution</id>
<phase>none</phase>
<goals>
<goal>jdeb</goal>
</goals>
</execution>
</executions>
<configuration>
<skip>true</skip>
<attach>false</attach>
<submodules>false</submodules>
<controlDir>${project.basedir}/../src/main/package/deb/control</controlDir>
</configuration>
</plugin>
</code></pre>
<p>This may resolve the above problem</p>
| 0 |
2016-10-01T08:54:36Z
|
[
"python",
"maven",
"ambari"
] |
sorting arrays in numpy by row
| 39,674,073 |
<p>I would like to sort an array in numpy by the first row.</p>
<p>For example :</p>
<pre><code>import numpy as np
test = np.array([[1334.71601720318, 930.9757468052002, 1018.7038817663818],
[0.0, 1.0, 2.0],
[ np.array([[ 667, 1393],
[1961, 474]]),
np.array([[ 673, 1389],
[ 847, 1280]]),
np.array([[ 726, 1077],
[ 898, 961]])]], dtype=object)
</code></pre>
<p>I want to sort the row :</p>
<pre><code>[1334.71601720318, 930.9757468052002, 1018.7038817663818]
</code></pre>
<p>to obtain : </p>
<pre><code>np.array([[930.9757468052002, 1018.7038817663818, 1334.71601720318],
[1.0, 2.0 ,0.0],
[ np.array([[ 673, 1389],
[ 847, 1280]]),
np.array([[ 726, 1077],
[ 898, 961]])],
np.array([[ 667, 1393],
[1961, 474]])], dtype=object)
</code></pre>
<p>---- EDIT LATER ----</p>
<p>I tried with : sorted(test, key=lambda row: row[1])
But i got an error message : "The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()"</p>
| 1 |
2016-09-24T08:09:21Z
| 39,674,430 |
<p>I think <code>test[:, np.argsort( test[0] ) ]</code> should do the trick.</p>
| 1 |
2016-09-24T08:51:47Z
|
[
"python",
"sorting",
"numpy",
"scipy"
] |
sqlite3.OperationalError: no such column: USA
| 39,674,146 |
<p>I am moving data from one database to another with the following statment </p>
<pre><code> cursor.execute("\
INSERT INTO table (ID, Country)\
SELECT ID, Country\
FROM database.t\
WHERE Country = `USA`\
GROUP BY Country\
;")
</code></pre>
<p>But I get the error</p>
<pre><code> sqlite3.OperationalError: no such column: USA
</code></pre>
<p>Can't figure out why</p>
| 0 |
2016-09-24T08:18:45Z
| 39,674,202 |
<p>Use single quotes, not backticks, when referring to a string literal in your SQLite query:</p>
<pre><code>INSERT INTO table (ID, Country)
SELECT ID, Country
FROM database.t
WHERE Country = 'USA'
GROUP BY Country
</code></pre>
| 1 |
2016-09-24T08:25:00Z
|
[
"python",
"sqlite"
] |
how to make request in python instead of curl
| 39,674,195 |
<h2> Here is the curl command:</h2>
<pre><code>curl 'http://ecard.bupt.edu.cn/User/ConsumeInfo.aspx'
-H 'Cookie: ASP.NET_SessionId=4mzmi0whscqg4humcs5fx0cf; .NECEID=1; .NEWCAPEC1=$newcapec$:zh-CN_CAMPUS; .ASPXAUTSSM=A91571BB81F620690376AF422A09EEF8A7C4F6C09978F36851B8DEDFA56C19C96A67EBD8BBD29C385C410CBC63D38135EFAE61BF49916E0A6B9AB582C9CB2EEB72BD9DE20D64A51C09474E676B188D937B84E601A981C02F51AA9C85A08EABCC1D30D7B9299E02A45D427B08A44AEBB0'
-H 'Origin: http://ecard.bupt.edu.cn'
-H 'Accept-Encoding: gzip, deflate'
-H 'Accept-Language: zh-CN,zh;q=0.8,en;q=0.6,zh-TW;q=0.4'
-H 'Upgrade-Insecure-Requests: 1'
-H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36'
-H 'Content-Type: application/x-www-form-urlencoded'
-H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'
-H 'Cache-Control: max-age=0' -H 'Referer: http://ecard.bupt.edu.cn/User/ConsumeInfo.aspx'
-H 'Connection: keep-alive'
--data '__EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATE=%2FwEPDwUINDEyMzA5NDkPFgIeCFNvcnRUeXBlBQNBU0MWAmYPZBYCAgMPZBYCAgMPZBYCAgQPPCsAEQMADxYEHgtfIURhdGFCb3VuZGceC18hSXRlbUNvdW50ZmQBEBYAFgAWAAwUKwAAFgJmD2QWAmYPZBYCAgEPZBYCAgEPDxYEHghDc3NDbGFzcwUKU29ydEJ0X0FzYx4EXyFTQgICZGQYAQUiY3RsMDAkQ29udGVudFBsYWNlSG9sZGVyMSRncmlkVmlldw88KwAMAQhmZBb11RlvPBlQn5fbuqe6uh8BRZJ2jUZ5U17xEnRM%2BnbF&__VIEWSTATEGENERATOR=D99777FC&__EVENTVALIDATION=%2FwEdAAgtbl4l0SdCQqYpyy3Ex39BEoHXgPeD%2Fa3eEKPr2bG0rY8WyuyQajjUbeopYM%2Fne68pyn2l0BPEWPPnyd6MfoDZVQGbFRIKjb%2FOTPkkCDIIaJ3X6W3VKO%2FV036Pdf6jf06OTFulzGhY80%2FZ1HbCJJ6LR5Lg6mLp72ibUCB3VipRJuK11qmW%2BSDe3IOvbK4oNUdV5%2FxmkXw25tTwfJ8P8OS2&ctl00%24ContentPlaceHolder1%24rbtnType=0&ctl00%24ContentPlaceHolder1%24txtStartDate=2016-09-17&ctl00%24ContentPlaceHolder1%24txtEndDate=2016-09-24&ctl00%24ContentPlaceHolder1%24btnSearch=%E6%9F%A5++%E8%AF%A2' --compressed
</code></pre>
<h2>I want to use request to get the return message to analyse, but i'm confused about this.</h2>
<h2>Thanks!</h2>
| 0 |
2016-09-24T08:24:34Z
| 39,674,349 |
<p>You can use python <a href="http://docs.python-requests.org/en/master/" rel="nofollow">requests</a> module. The answer would be something like:</p>
<pre><code>response = requests.get('http://ecard.bupt.edu.cn/User/ConsumeInfo.aspx',
headers={'Origin': 'http://ecard.bupt.edu.cn'},
data={'__EVENTTARGET': '', 'rbtnType':0},
cookies={'.NECEID': 1}
)
</code></pre>
<p>I didn't put all parameters there but I think this example is enough to figure out how to send exact the same request you want. The only thing I am not sure is <code>--compressed</code> flag - as I understand from docs it is something more specific to curl(correct me if I'm wrong)</p>
| 1 |
2016-09-24T08:40:34Z
|
[
"python",
"curl"
] |
Iteration over a sub-list of dictionaries -Python
| 39,674,224 |
<p>I have a list of dictionaries e.g.:</p>
<pre><code>list_d = [{"a":1},{"b":2,"c":3}]
</code></pre>
<p><em>(case 1)</em></p>
<pre><code>for item in list_d:
# add values of each sub-list's dicts
</code></pre>
<p><em>(case 2)</em></p>
<pre><code>for item in list_d[1]:
# add values of the specific sub-list of dict
</code></pre>
<p>(case1) it returns the sum of each sub-list's dict values.</p>
<p>(case2) returns only the keys of the dictionaries.</p>
<p>Is there an efficient way to get the dictionaries of the sub-list(case2) so to add the values?</p>
| 0 |
2016-09-24T08:28:14Z
| 39,674,456 |
<p>Here's one way to do it:</p>
<pre><code>reduce(lambda x,y: x + sum(y.values()), list_d, 0)
</code></pre>
<p>That is, starting with 0 (as the first <code>x</code>), add the sum of all values in each <code>dict</code> within <code>list_d</code>.</p>
<p>Here's another way:</p>
<pre><code>sum(sum(x.values()) for x in list_d)
</code></pre>
<p>That is, sum the (sum of values for each <code>dict</code> in <code>list_d</code>).</p>
| 0 |
2016-09-24T08:53:49Z
|
[
"python"
] |
Iteration over a sub-list of dictionaries -Python
| 39,674,224 |
<p>I have a list of dictionaries e.g.:</p>
<pre><code>list_d = [{"a":1},{"b":2,"c":3}]
</code></pre>
<p><em>(case 1)</em></p>
<pre><code>for item in list_d:
# add values of each sub-list's dicts
</code></pre>
<p><em>(case 2)</em></p>
<pre><code>for item in list_d[1]:
# add values of the specific sub-list of dict
</code></pre>
<p>(case1) it returns the sum of each sub-list's dict values.</p>
<p>(case2) returns only the keys of the dictionaries.</p>
<p>Is there an efficient way to get the dictionaries of the sub-list(case2) so to add the values?</p>
| 0 |
2016-09-24T08:28:14Z
| 39,674,488 |
<p>As Antti points out it is unclear what you are asking for. I would recommend you having a look at the built-in tools in Python for <a href="https://docs.python.org/2/howto/functional.html" rel="nofollow">Functional programming</a></p>
<p>Consider the following examples:</p>
<pre><code>from operator import add
list_d = [{"a":1},{"b":2,"c":3}]
case_1 = map(lambda d: sum(d.values()), list_d)
case_2 = reduce(add, map(lambda d: sum(d.values()), list_d))
</code></pre>
| 0 |
2016-09-24T08:56:44Z
|
[
"python"
] |
Chat System Using Django and Node Js
| 39,674,246 |
<p>I am hoping to make a chat System for a project as an assignment in Node Js and I am a beginner at Node JS ..Can anyone help me where should i start off Node js??? Any good books and tutorials ?? I am using django .. </p>
| 0 |
2016-09-24T08:30:56Z
| 39,674,724 |
<p>I guess its better that you start with Django. It is a very good framework. This <a href="https://www.youtube.com/watch?v=PsorlkAF83s" rel="nofollow">video</a> would help you understand more.</p>
| 0 |
2016-09-24T09:23:09Z
|
[
"python",
"node.js",
"django"
] |
Chat System Using Django and Node Js
| 39,674,246 |
<p>I am hoping to make a chat System for a project as an assignment in Node Js and I am a beginner at Node JS ..Can anyone help me where should i start off Node js??? Any good books and tutorials ?? I am using django .. </p>
| 0 |
2016-09-24T08:30:56Z
| 39,674,754 |
<p>You definitely will need <a href="http://www.django-rest-framework.org/" rel="nofollow">django rest framework</a>. It will help you with making talk node-js with django backend.</p>
| 0 |
2016-09-24T09:27:51Z
|
[
"python",
"node.js",
"django"
] |
Chat System Using Django and Node Js
| 39,674,246 |
<p>I am hoping to make a chat System for a project as an assignment in Node Js and I am a beginner at Node JS ..Can anyone help me where should i start off Node js??? Any good books and tutorials ?? I am using django .. </p>
| 0 |
2016-09-24T08:30:56Z
| 39,678,321 |
<p>I personally use <a href="http://socket.io/" rel="nofollow">socket.io</a> with Node.js to create a chat application. You can find the documentation of socket.io client and server <a href="http://socket.io/docs/" rel="nofollow">here</a>.</p>
<p>You can integrate with any platform on client side.
Hope this will be helpful for you !!</p>
| 0 |
2016-09-24T16:06:16Z
|
[
"python",
"node.js",
"django"
] |
Chat System Using Django and Node Js
| 39,674,246 |
<p>I am hoping to make a chat System for a project as an assignment in Node Js and I am a beginner at Node JS ..Can anyone help me where should i start off Node js??? Any good books and tutorials ?? I am using django .. </p>
| 0 |
2016-09-24T08:30:56Z
| 39,682,116 |
<p>You can also check out <a href="http://Django%20Channels" rel="nofollow">https://channels.readthedocs.io/en/latest/</a> . It elegantly handles apps that require real-time browser push like chat.</p>
| 0 |
2016-09-25T00:02:53Z
|
[
"python",
"node.js",
"django"
] |
Python - why its not able to find the window title?
| 39,674,374 |
<p>I have following code and its unable to activate the window title "Stack Overflow" and sending the f11 to wrong GUI. </p>
<p>Is this a Python bug? Why its not working?</p>
<pre><code>import subprocess
from subprocess import Popen
import win32com.client as comctl
import time
def chromes():
url='https://stackoverflow.com'
cmd='C:/Users/tpt/AppData/Local/Chromium/Application/chrome.exe'
Popen([cmd, url, '--window-position=0,0', '--user-data-dir=C:\\iplay'])
chromes()
time.sleep(5)
wsh =comctl.Dispatch("WScript.Shell")
aa = wsh.AppActivate("Stack Overflow")
wsh.SendKeys("{F11}")
</code></pre>
| 0 |
2016-09-24T08:43:53Z
| 39,675,255 |
<p>Like this :</p>
<pre><code>import win32gui
import win32api
import win32con
def enumHandler(hwnd, lParam):
if win32gui.IsWindowVisible(hwnd):
if 'Stack Overflow' in win32gui.GetWindowText(hwnd):
win32api.PostMessage(hwnd, win32con.WM_KEYDOWN, win32con.VK_F11, 0)
win32gui.EnumWindows(enumHandler, None)
</code></pre>
<p>But no idea about which tab effected ?</p>
| 1 |
2016-09-24T10:20:17Z
|
[
"python",
"windows",
"google-chrome",
"chromium"
] |
Simple tensorflow linear model
| 39,674,394 |
<p>Here train_X(shape=m,64) and train_Y(m,1) are numpy arrays where m is my number of training samples.</p>
<pre><code>print('train and test array computed')
print(train_X[:2])
print(train_Y[:2])
</code></pre>
<p>Output of these lines is</p>
<pre><code>train and test array computed
[[ 8.10590000e+01 8.91460000e+01 1.00000000e+02 1.00000000e+02
0.00000000e+00 5.26000000e-01 5.80000000e-01 5.80000000e-01
5.80000000e-01 5.80000000e-01 8.00000000e-01 6.66670000e+01
6.36160000e+01 8.36000000e-01 1.17300000e+00 5.80000000e-01
6.48860000e+01 5.80000000e-01 1.73640000e+01 -2.07250000e+01
5.81000000e-01 0.00000000e+00 5.80000000e-01 5.80000000e-01
7.00000000e-03 5.80000000e-01 -5.44000000e-01 -2.36000000e-01
5.80000000e-01 5.81000000e-01 5.81000000e-01 5.80000000e-01
5.80000000e-01 5.80000000e-01 5.80000000e-01 5.80000000e-01
0.00000000e+00 4.00000000e-01 2.10000000e-02 1.00000000e+00
1.00021000e+02 8.18080000e+01 5.71000000e-01 5.48000000e-01
6.14000000e-01 5.80000000e-01 7.62000000e-01 0.00000000e+00
1.00000000e+02 1.00000000e+02 0.00000000e+00 1.00000000e+02
1.00000000e+02 1.16100000e+00 5.80000000e-01 6.56000000e-01
5.80000000e-01 5.80000000e-01 5.81000000e-01 5.80000000e-01
1.00000000e+02 5.80000000e-01 0.00000000e+00 5.80000000e-01]
[ 5.12680000e+01 4.87480000e+01 1.00000000e+02 1.00000000e+02
0.00000000e+00 4.18000000e-01 4.44000000e-01 4.44000000e-01
4.44000000e-01 4.44000000e-01 5.00000000e-01 6.66670000e+01
3.83570000e+01 9.03000000e-01 1.10000000e+00 4.44000000e-01
5.63070000e+01 4.44000000e-01 1.85220000e+01 1.94233000e+02
4.44000000e-01 0.00000000e+00 4.44000000e-01 4.44000000e-01
1.00000000e-03 4.44000000e-01 -8.12000000e-01 -3.53000000e-01
4.44000000e-01 4.44000000e-01 4.44000000e-01 4.44000000e-01
4.44000000e-01 4.44000000e-01 4.44000000e-01 4.44000000e-01
0.00000000e+00 5.00000000e-01 2.00000000e-03 1.00000000e+00
1.00002000e+02 6.91780000e+01 4.42000000e-01 4.29000000e-01
4.59000000e-01 4.44000000e-01 6.66000000e-01 0.00000000e+00
5.00000000e+01 5.00000000e+01 0.00000000e+00 5.00000000e+01
5.00000000e+01 8.88000000e-01 4.44000000e-01 4.75000000e-01
4.44000000e-01 4.44000000e-01 4.44000000e-01 4.44000000e-01
5.00000000e+01 4.44000000e-01 -5.00000000e+01 4.44000000e-01]]
[ 0.44378 0.6821 ]
</code></pre>
<p>Here is the relevant part of my program.</p>
<pre><code>rng = np.random
# Parameters
learning_rate = 0.01
training_epochs = 1000
display_step = 50
# Training Data
n_samples = train_X.shape[0]
n_features = train_X.shape[1]
# tf Graph Input
X = tf.placeholder(tf.float32,[None,n_features])
Y = tf.placeholder(tf.float32,[None,1])
# Set model weights
W = tf.Variable(tf.random_normal([n_features,1],mean=0,stddev=(np.sqrt(6/n_features+
1+1))), name="weight")
b = tf.Variable(tf.random_normal([1,1],
mean=0,
stddev=(np.sqrt(6/n_features+1+1)),
name="bias"))
# Construct a linear model
pred = tf.add(tf.mul(X, W), b)
# Mean squared error
cost = tf.reduce_sum(tf.pow(pred-Y, 2))/(2*n_samples)
# Gradient descent
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)
# Initializing the variables
init = tf.initialize_all_variables()
print('starting the session')
# Launch the graph
with tf.Session() as sess:
sess.run(init)
# Fit all training data
for epoch in range(training_epochs):
for (x, y) in zip(train_X, train_Y):
sess.run(optimizer, feed_dict={X: x, Y: y})
# Display logs per epoch step
if (epoch+1) % display_step == 0:
c = sess.run(cost, feed_dict={X: train_X, Y:train_Y})
print("Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(c), \
"W=", sess.run(W), "b=", sess.run(b))
print("Optimization Finished!")
training_cost = sess.run(cost, feed_dict={X: train_X, Y: train_Y})
print("Training cost=", training_cost, "W=", sess.run(W), "b=", sess.run(b), '\n')
# Graphic display
# plt.plot(train_X, train_Y, 'ro', label='Original data')
# plt.plot(train_X, sess.run(W) * train_X + sess.run(b), label='Fitted line')
# plt.legend()
# plt.show()
# Testing example, as requested (Issue #2)
print("Testing... (Mean square loss Comparison)")
testing_cost = sess.run(
tf.reduce_sum(tf.pow(pred - Y, 2)) / (2 * test_X.shape[0]),
feed_dict={X: test_X, Y: test_Y}) # same function as cost above
print("Testing cost=", testing_cost)
print("Absolute mean square loss difference:", abs(
training_cost - testing_cost))
# plt.plot(test_X, test_Y, 'bo', label='Testing data')
# plt.plot(train_X, sess.run(W) * train_X + sess.run(b), label='Fitted line')
# plt.legend()
# plt.show()
</code></pre>
<p>I am struggling to make it work for a long time but it never worked. I gives me the error.</p>
<pre><code>Traceback (most recent call last):
File "q.py", line 158, in <module>
sess.run(optimizer, feed_dict={X: x, Y: y})
File "/home/tensorflow/anaconda3/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 382, in run
run_metadata_ptr)
File "/home/tensorflow/anaconda3/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 640, in _run
% (np_val.shape, subfeed_t.name, str(subfeed_t.get_shape())))
ValueError: Cannot feed value of shape (64,) for Tensor 'Placeholder:0', which has shape '(?, 64)'
</code></pre>
<p>The problem is in line <em>sess.run(optimizer, feed_dict={X: x, Y: y})</em></p>
| 0 |
2016-09-24T08:46:54Z
| 39,680,153 |
<p>I think the error is that you're zipping (x, y) in zip(train_X, train_Y): so this will give one x and one y example. </p>
<p>you instead want to directly feed in trainX and trainY like so:</p>
<pre><code>feed_dict={X: train_X, Y:train_Y}
</code></pre>
<p>You can check that this is the case by running </p>
<pre><code>for (x, y) in zip(train_X, train_Y):
print(x.shape,y.shape) # I guess this will be 64 and 1 for x and y resp.
sess.run(optimizer, feed_dict={X: x, Y: y})
</code></pre>
<p>you want it to have shape X = (#,64)</p>
| 1 |
2016-09-24T19:28:30Z
|
[
"python",
"python-3.x",
"numpy",
"tensorflow",
"linear-regression"
] |
Variable scope in python code
| 39,674,426 |
<pre><code>from sys import exit
def gold_room():
print "This room is full of gold. How much do you take?"
choice = raw_input("> ")
if "0" in choice or "1" in choice:
how_much = int(choice)
else:
dead("Man, learn to type a number.")
if how_much < 50:
print "Nice, you're not greedy, you win!"
exit(0)
else:
dead("You greedy bastard!")
def dead(why):
print why
exit(0)
</code></pre>
<p>1) How does the <code>dead</code> method is called inside <code>gold_room</code> method as the definition of <code>dead</code> method is below the calling statement?</p>
<p>2) How does the variable <code>how_much</code> accessed outside of its scope? It was declared and initialized inside the indented block -</p>
<pre><code> if "0" in choice or "1" in choice:
how_much = int(choice)
</code></pre>
<p>And according to my understanding, its scope should be ended here in this block. Then how it is used further in this condition - <code>if how_much < 50</code> ?</p>
| -1 |
2016-09-24T08:51:06Z
| 39,674,607 |
<p>There is no "dead" method built into Python. The reason why the interpreter tells you that it is not defined is because you haven't defined it.</p>
<p>Python does not have block scope. Variables defined inside a function are visible from that point on, until the end of the function.</p>
<p><strong>edit after the first question was changed</strong> It doesn't matter in which order the functions are defined, as long as they are both defined at the time they are <em>called</em>. Presumably, you have some code at the end of that module which calls <code>gold_room</code>, after both functions are defined.</p>
| 1 |
2016-09-24T09:10:11Z
|
[
"python",
"python-2.7",
"scope"
] |
Python: UnicodeEncodeError when printing accented characters
| 39,674,428 |
<p>Using Python 2.7.11</p>
<pre><code>#!/usr/bin/python
# -*- coding: utf-8 -*-
print 'ÃÃÅÃÅ'
print u'ÃÃÃÃÅ'
</code></pre>
<p>With the following result:</p>
<pre><code>âüâëâ¼Ãâ£â¼Ã
Traceback (most recent call last):
File "C:\Users\RaseR\Desktop\testing.py", line 4, in <module>
print u'âüâëâûâ£â¼Ã'
File "C:\Python27\lib\encodings\cp850.py", line 12, in encode
return codecs.charmap_encode(input,errors,encoding_map)
UnicodeEncodeError: 'charmap' codec can't encode character u'\u0150' in
position 4: character maps to <undefined>
</code></pre>
<p>If necessary:</p>
<p>Notepad++ with encoding UTF-8</p>
<p>Windows 10 Console w/ Lucida Console Font</p>
| -2 |
2016-09-24T08:51:13Z
| 39,674,617 |
<p>When you <code>print</code>, you are printing to standard output. Standard output uses some encoding and everything has to be converted to that encoding.</p>
<p>In my case:</p>
<pre><code>>>> sys.stdout.encoding
'cp852'
>>> u'\u0150'.encode(sys.stdout.encoding)
'\x8a'
>>> print u'\u0150'
Å
>>> print '\x8a'
Å
</code></pre>
<p>In your case, it seems that the Å character does not exist in the encoding used by stdout, so the conversion fails. There is no way to print that.</p>
<p>You can encode it manually, specifying what to do with characters which cannot be encoded:</p>
<pre><code>>>> print u'\u0150'.encode(sys.stdout.encoding, 'replace')
Å
</code></pre>
<p>With a character which it cannot encode:</p>
<pre><code>>>> print u'\u0150\u1234'.encode(sys.stdout.encoding, 'replace')
Å?
</code></pre>
| -1 |
2016-09-24T09:11:30Z
|
[
"python",
"unicode",
"utf-8",
"decode",
"encode"
] |
How to typecast a list as my own custom Matrix class?
| 39,674,455 |
<p>I have a <code>Matrix</code> class:</p>
<pre><code>class Matrix(object):
def __init__(self,row,col):
self.row=row
self.col=col
self.matlist=[]
self.create()
def create(self):
for i in range(self.row):
rowlist=[]
for j in range(self.col):
element=input("Enter Row: {} Col: {} : ".format(i+1,j+1))
rowlist.append(element)
self.matlist.append(rowlist)
def __str__(self):
j=str()
for i in range(len(self.matlist)):
for j in range(len(self.matlist[i])):
j+=str(self.matlist[i][j])+" "
j+="\n"
return j
def __add__(self,y):
newmatrix=[]
el1=self.matlist
el2=y.matlist
if (len(el1)==len(el2)) and (len(el1[0])==len(el2[0])):
for i in range(len(el1)):
newlist=[]
for j in range(len(el1[i])):
m=el1[i][j]+el2[i][j]
newlist.append(m)
newmatrix.append(newlist)
return newmatrix
</code></pre>
<p>and I have created two matrix objects:</p>
<pre><code>m=Matrix(2,2)
n=Matrix(2,2)
</code></pre>
<p>and then I add the Matrices:</p>
<pre><code>k=m+n
</code></pre>
<p>which calls the <code>__add__()</code> method which returns a <code>list</code>. But I want it to return it as a <code>Matrix</code> object so that when I try to print it, the <code>__str__()</code> method gets called and the <code>list</code> dosent simply get printed. Is there some way to typecast that <code>list</code> into <code>Matrix</code>?</p>
| -1 |
2016-09-24T08:53:47Z
| 39,698,198 |
<p>Something like this should work.</p>
<p>First, a classmethod to create a matrix from a list:</p>
<pre><code>class Matrix(object):
def __init__(self, row=None, col=None):
self.matlist = []
if row and col:
self.row = row
self.col = col
self.create()
@classmethod
def fromlist(cls, list):
res = Matrix()
for row in list:
res.matlist.append(row)
return res
</code></pre>
<p>Then, the <code>__add__</code> method uses said method to return a <code>Matrix</code>:</p>
<pre><code>def __add__(self,y):
newmatrix=[]
el1=self.matlist
el2=y.matlist
if (len(el1)==len(el2)) and (len(el1[0])==len(el2[0])):
for i in range(len(el1)):
newlist=[]
for j in range(len(el1[i])):
m=el1[i][j]+el2[i][j]
newlist.append(m)
newmatrix.append(newlist)
return Matrix.fromlist(newmatrix)
</code></pre>
<p>Note that there are some checks you should do. For example, this code doesn't check that all the rows are the same size. Other check you didn't consider in your code is that when adding two <code>Matrix</code> object, they both should be the same size.</p>
| 0 |
2016-09-26T08:39:10Z
|
[
"python",
"python-2.7",
"matrix"
] |
Python binary to multi- hex
| 39,674,508 |
<p>I am trying to read a file in binary and return for example "ffffff" a series of 6 hex codes. does this make sense? The code I have (below) only returns a list of 2 so it looks like "ff"</p>
<pre><code>fp = open(f, 'rb')
hex_list = ("{:02x}".format(ord(c)) for c in fp.read())
</code></pre>
<p>i am specifically looking to make this return something like</p>
<pre><code>['ab0012', 'ffbaf0']
</code></pre>
<p>not like</p>
<pre><code>['ab', '00', '12', 'ff', 'ba', 'f0']
</code></pre>
<p>any help would be appreciated thanks. </p>
| 0 |
2016-09-24T08:58:35Z
| 39,674,646 |
<p>How about this:</p>
<pre><code>fp = open(f, 'rb')
hex_list = ["{:02x}".format(ord(c)) for c in fp.read()]
return [''.join(hex_list[n:n+3]) for n in range(0, len(hex_list), 3)]
</code></pre>
| 1 |
2016-09-24T09:14:22Z
|
[
"python",
"format",
"hex",
"bin",
"ord"
] |
Searching an element in a list of double-nested dictionaries with generator
| 39,674,560 |
<p>I have a list of dictionaris. In every dictionary, i need to use values, which are in the dictionaries, which are in the dictionaries:</p>
<pre><code>[{'Cells': {'Address': 'Ðижний ÐиÑелÑнÑй пеÑеÑлок, дом 3, ÑÑÑоение 1',
'AdmArea': 'ЦенÑÑалÑнÑй админиÑÑÑаÑивнÑй окÑÑг',
'District': 'ÐеÑанÑкий Ñайон',
'IsNetObject': 'неÑ',
'Name': 'Юнион Ðжек',
'OperatingCompany': None,
'PublicPhone': [{'PublicPhone': '(495) 621-19-63'}],
'SeatsCount': 30,
'SocialPrivileges': 'неÑ',
'geoData': {'coordinates': [37.62158794615201, 55.76536695660836],
'type': 'Point'},
'global_id': 20660594},
'Id': 'ae3e9479-070f-4d66-9429-de3acd8427ac',
'Number': 1},
{'Cells': {'Address': 'пÑоÑÐ¿ÐµÐºÑ ÐиÑа, дом 91, коÑпÑÑ 1',
'AdmArea': 'СевеÑо-ÐоÑÑоÑнÑй админиÑÑÑаÑивнÑй окÑÑг',
'District': 'ÐÑÑанкинÑкий Ñайон',
'IsNetObject': 'неÑ',
'Name': 'ÐÐ°Ñ Â«Ðжонни ÐÑин Ðаб»',
'OperatingCompany': None,
'PublicPhone': [{'PublicPhone': '(495) 602-45-85'}],
'SeatsCount': 50,
'SocialPrivileges': 'неÑ',
'geoData': {'coordinates': [37.635709999611, 55.805575000159],
'type': 'Point'},
'global_id': 20660628},
'Id': 'c5301186-00bb-4a1f-af03-6f3237292a51',
'Number': 2},
</code></pre>
<p>I'm given coordinates <code>[lattitude, attitude]</code>. I want to find the smallest distance between given coordinates and coordinates in dictionaries. So i need to iterate over dictionaries and calculate the distance.
I'am quite new, but i want to be more proffesional with using a generator to find the distance. But, using <code>__next__()</code>, will stop iterating as soon as it meets the condition, so i'am just dont if it is possible. </p>
<p><strong>So, to be short: What is the most efficient way to find the smallest distance from a given spot in this data structure?</strong> </p>
| 1 |
2016-09-24T09:04:40Z
| 39,674,656 |
<p>First, let's assume you have a function get_distance() which finds distance between two points with lat and long. I can describe it, but I think for now it is not the point of the question. Then, the code will be look like:</p>
<pre><code>cells = {...} # your data is here
point = [..] # coordinates of the point
distances = {get_distance(point, cell['Cells']['geoData']['coordinates']): cell['Id'] for cell in cells} # I don't know do you need a whole entry to be found or only `Id`
closest_id = distances[min(distances.keys())]
</code></pre>
<p>Off course it is only of possible solutions. I've made it with dict comprehension but sometimes it is more easy to rea to do it with suaul <code>for</code> loop. Please let me know if something is unclear.</p>
<p>If you also have problems with writing <code>get_distance</code> function - here is an one of examples: <a href="http://stackoverflow.com/questions/15736995/how-can-i-quickly-estimate-the-distance-between-two-latitude-longitude-points">How can I quickly estimate the distance between two (latitude, longitude) points?</a> (of course it needs to be modified a bit to look like get_distance function)</p>
| 1 |
2016-09-24T09:15:19Z
|
[
"python",
"dictionary"
] |
A different number of features in the SVC.coef_ and samples
| 39,674,590 |
<p>I downloaded the data.</p>
<pre><code>news = datasets.fetch_20newsgroups(subset='all', categories=['alt.atheism', 'sci.space'])
vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(newsgroups.data)
y = news.target
print(X.shape)
</code></pre>
<p>The shape of X is <code>(1786, 28382)</code></p>
<p>Next I trained the model and got the coef_ shape</p>
<pre><code>clf = svm.SVC(kernel='linear', random_state=241, C = 1.0000000000000001e-05)
clf.fit(X, y)
data = clf.coef_[0].data
print(data.shape)
</code></pre>
<p>The shape is <code>(27189,)</code></p>
<p>Why the number of features are different?</p>
| 0 |
2016-09-24T09:08:16Z
| 39,675,841 |
<p>So in short everything is fine, your weight matrix is in clf.coef_. And it has valid shape, it is a regular numpy array (or scipy sparse array if data is sparse). You can do all needed operations on it, index it etc. What you tried, the .data field is attribute which holds <strong>internal</strong> storage of the array, which can be of different shape (since it might ignore some redundancies etc.), but the point is you should not use this internal attribute of numpy array for your purpose. It is exposed for low level methods, not for just reading out</p>
| 1 |
2016-09-24T11:32:17Z
|
[
"python",
"machine-learning",
"svm",
"data-analysis"
] |
Neural Network LSTM Keras multiple inputs
| 39,674,713 |
<p>I am trying to implement an <a href="https://keras.io/layers/recurrent/#lstm">LSTM with Keras</a>. My inputs and outputs are like in a regression, that is, I have one timeseries y with T observations that I am trying to predict, and I have N (in my case around 20) input vectors (timeseries) of T observations each that I want to use as inputs.</p>
<p>I know that LSTM's in Keras require a <code>3D tensor with shape (nb_samples, timesteps, input_dim)</code> as an input. However, I am not entirely sure how the input should look like in my case, as I have just one sample of T observations for each input, not multiple samples, i.e. I think that would translate to <code>(nb_samples=1, timesteps=T, input_dim=N)</code>. However, is it better to split each of my inputs into samples of length T/M? T is around a few million observations for me, so how long should each sample in that case be, i.e., how would I choose M?</p>
<p>Also, am I right in that this tensor should look something like:</p>
<p><code>[[[a_11, a_12, ..., a_1M], [a_21, a_22, ..., a_2M], ..., [a_N1, a_N2, ..., a_NM]], [[b_11, b_12, ..., b_1M], [b_21, b_22, ..., b_2M], ..., [b_N1, b_N2, ..., b_NM]], ..., [[x_11, x_12, ..., a_1M], [x_21, x_22, ..., x_2M], ..., [x_N1, x_N2, ..., x_NM]]]</code>, where M and N defined as before and x corresponds to the last sample that I would have obtained from splitting as discussed above? </p>
<p>Given a pandas dataframe with T observations in each column, and N columns, one for each input, how can I create such an input to feed to Keras?</p>
<p>In addition, how should I choose the batch size? It seems that Keras only accepts batch sizes that are multiples of <code>nb_samples</code>? Also, when after I have fitted the model, it seems that I can only predict out-of-sample for inputs that are again of a length that is a multiple of the batch size? How does this work in practice?</p>
<p><strong>I would highly appreciate it if someone could show me a full worked example of an LSTM in Keras (and worst case in another python package, or if that's also not possible in another language) for a situation similar to the one I described: i.e. with one output timeseries and multiple input timeseries (just like in a regression), showing how to fit the model in-sample and then predict out-of-sample.</strong></p>
<p>Thanks very much in advance :)!</p>
| 8 |
2016-09-24T09:21:49Z
| 39,922,569 |
<p><strong>Tensor shape</strong></p>
<p>You're right that Keras is expecting a 3D tensor for an LSTM neural network, but I think the piece you are missing is that Keras expects that <em>each observation can have multiple dimensions</em>. </p>
<p>For example, in Keras I have used word vectors to represent documents for natural language processing. Each word in the document is represented by an n-dimensional numerical vector (so if <code>n = 2</code> the word 'cat' would be represented by something like <code>[0.31, 0.65]</code>). To represent a single document, the word vectors are lined up in sequence (e.g. 'The cat sat.' = <code>[[0.12, 0.99], [0.31, 0.65], [0.94, 0.04]]</code>). A document would be a single sample in a Keras LSTM.</p>
<p>This is analogous to your time series observations. A document is like a time series, and a word is like a single observation in your time series, but in your case it's just that the representation of your observation is just <code>n = 1</code> dimensions.</p>
<p>Because of that, I think your tensor should be something like <code>[[[a1], [a2], ... , [aT]], [[b1], [b2], ..., [bT]], ..., [[x1], [x2], ..., [xT]]]</code>, where <code>x</code> corresponds to <code>nb_samples</code>, <code>timesteps = T</code>, and <code>input_dim = 1</code>, because each of your observations is only one number.</p>
<p><strong>Batch size</strong></p>
<p>Batch size should be set to maximize throughput without exceeding the memory capacity on your machine, per this <a href="http://stats.stackexchange.com/questions/153531/what-is-batch-size-in-neural-network">Cross Validated post</a>. As far as I know your input does not need to be a multiple of your batch size, neither when training the model and making predictions from it.</p>
<p><strong>Examples</strong></p>
<p>If you're looking for sample code, on the <a href="https://github.com/fchollet/keras/tree/master/examples" rel="nofollow">Keras Github</a> there are a number of examples using LSTM and other network types that have sequenced input.</p>
| 1 |
2016-10-07T17:05:16Z
|
[
"python",
"neural-network",
"keras",
"recurrent-neural-network",
"lstm"
] |
Neural Network LSTM Keras multiple inputs
| 39,674,713 |
<p>I am trying to implement an <a href="https://keras.io/layers/recurrent/#lstm">LSTM with Keras</a>. My inputs and outputs are like in a regression, that is, I have one timeseries y with T observations that I am trying to predict, and I have N (in my case around 20) input vectors (timeseries) of T observations each that I want to use as inputs.</p>
<p>I know that LSTM's in Keras require a <code>3D tensor with shape (nb_samples, timesteps, input_dim)</code> as an input. However, I am not entirely sure how the input should look like in my case, as I have just one sample of T observations for each input, not multiple samples, i.e. I think that would translate to <code>(nb_samples=1, timesteps=T, input_dim=N)</code>. However, is it better to split each of my inputs into samples of length T/M? T is around a few million observations for me, so how long should each sample in that case be, i.e., how would I choose M?</p>
<p>Also, am I right in that this tensor should look something like:</p>
<p><code>[[[a_11, a_12, ..., a_1M], [a_21, a_22, ..., a_2M], ..., [a_N1, a_N2, ..., a_NM]], [[b_11, b_12, ..., b_1M], [b_21, b_22, ..., b_2M], ..., [b_N1, b_N2, ..., b_NM]], ..., [[x_11, x_12, ..., a_1M], [x_21, x_22, ..., x_2M], ..., [x_N1, x_N2, ..., x_NM]]]</code>, where M and N defined as before and x corresponds to the last sample that I would have obtained from splitting as discussed above? </p>
<p>Given a pandas dataframe with T observations in each column, and N columns, one for each input, how can I create such an input to feed to Keras?</p>
<p>In addition, how should I choose the batch size? It seems that Keras only accepts batch sizes that are multiples of <code>nb_samples</code>? Also, when after I have fitted the model, it seems that I can only predict out-of-sample for inputs that are again of a length that is a multiple of the batch size? How does this work in practice?</p>
<p><strong>I would highly appreciate it if someone could show me a full worked example of an LSTM in Keras (and worst case in another python package, or if that's also not possible in another language) for a situation similar to the one I described: i.e. with one output timeseries and multiple input timeseries (just like in a regression), showing how to fit the model in-sample and then predict out-of-sample.</strong></p>
<p>Thanks very much in advance :)!</p>
| 8 |
2016-09-24T09:21:49Z
| 40,005,797 |
<p>Below is an example that sets up time series data to train an LSTM. The model output is nonsense as I only set it up to demonstrate how to build the model.</p>
<pre><code>import pandas as pd
import numpy as np
# Get some time series data
df = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/timeseries.csv")
df.head()
</code></pre>
<p>Time series dataframe:</p>
<pre><code>Date A B C D E F G
0 2008-03-18 24.68 164.93 114.73 26.27 19.21 28.87 63.44
1 2008-03-19 24.18 164.89 114.75 26.22 19.07 27.76 59.98
2 2008-03-20 23.99 164.63 115.04 25.78 19.01 27.04 59.61
3 2008-03-25 24.14 163.92 114.85 27.41 19.61 27.84 59.41
4 2008-03-26 24.44 163.45 114.84 26.86 19.53 28.02 60.09
</code></pre>
<p>You can build put inputs into a vector and then use pandas <code>.cumsum()</code> function to build the sequence for the time series:</p>
<pre><code># Put your inputs into a single list
df['single_input_vector'] = df[input_cols].apply(tuple, axis=1).apply(list)
# Double-encapsulate list so that you can sum it in the next step and keep time steps as separate elements
df['single_input_vector'] = df.single_input_vector.apply(lambda x: [list(x)])
# Use .cumsum() to include previous row vectors in the current row list of vectors
df['cumulative_input_vectors'] = df.single_input_vector.cumsum()
</code></pre>
<p>The output can be set up in a similar way, but it will be a single vector instead of a sequence:</p>
<pre><code># If your output is multi-dimensional, you need to capture those dimensions in one object
# If your output is a single dimension, this step may be unnecessary
df['output_vector'] = df[output_cols].apply(tuple, axis=1).apply(list)
</code></pre>
<p>The input sequences have to be the same length to run them through the model, so you need to pad them to be the max length of your cumulative vectors:</p>
<pre><code># Pad your sequences so they are the same length
from keras.preprocessing.sequence import pad_sequences
max_sequence_length = df.cumulative_input_vectors.apply(len).max()
# Save it as a list
padded_sequences = pad_sequences(df.cumulative_input_vectors.tolist(), max_sequence_length).tolist()
df['padded_input_vectors'] = pd.Series(padded_sequences).apply(np.asarray)
</code></pre>
<p>Training data can be pulled from the dataframe and put into numpy arrays. <strong>Note that the input data that comes out of the dataframe will not make a 3D array. It makes an array of arrays, which is not the same thing.</strong></p>
<p>You can use hstack and reshape to build a 3D input array.</p>
<pre><code># Extract your training data
X_train_init = np.asarray(df.padded_input_vectors)
# Use hstack to and reshape to make the inputs a 3d vector
X_train = np.hstack(X_train_init).reshape(len(df),max_sequence_length,len(input_cols))
y_train = np.hstack(np.asarray(df.output_vector)).reshape(len(df),len(output_cols))
</code></pre>
<p>To prove it:</p>
<pre><code>>>> print(X_train_init.shape)
(11,)
>>> print(X_train.shape)
(11, 11, 6)
>>> print(X_train == X_train_init)
False
</code></pre>
<p>Once you have training data you can define the dimensions of your input layer and output layers.</p>
<pre><code># Get your input dimensions
# Input length is the length for one input sequence (i.e. the number of rows for your sample)
# Input dim is the number of dimensions in one input vector (i.e. number of input columns)
input_length = X_train.shape[1]
input_dim = X_train.shape[2]
# Output dimensions is the shape of a single output vector
# In this case it's just 1, but it could be more
output_dim = len(y_train[0])
</code></pre>
<p>Build the model:</p>
<pre><code>from keras.models import Model, Sequential
from keras.layers import LSTM, Dense
# Build the model
model = Sequential()
# I arbitrarily picked the output dimensions as 4
model.add(LSTM(4, input_dim = input_dim, input_length = input_length))
# The max output value is > 1 so relu is used as final activation.
model.add(Dense(output_dim, activation='relu'))
model.compile(loss='mean_squared_error',
optimizer='sgd',
metrics=['accuracy'])
</code></pre>
<p>Finally you can train the model and save the training log as history:</p>
<pre><code># Set batch_size to 7 to show that it doesn't have to be a factor or multiple of your sample size
history = model.fit(X_train, y_train,
batch_size=7, nb_epoch=3,
verbose = 1)
</code></pre>
<p>Output:</p>
<pre><code>Epoch 1/3
11/11 [==============================] - 0s - loss: 3498.5756 - acc: 0.0000e+00
Epoch 2/3
11/11 [==============================] - 0s - loss: 3498.5755 - acc: 0.0000e+00
Epoch 3/3
11/11 [==============================] - 0s - loss: 3498.5757 - acc: 0.0000e+00
</code></pre>
<p>That's it. Use <code>model.predict(X)</code> where <code>X</code> is the same format (other than the number of samples) as <code>X_train</code> in order to make predictions from the model.</p>
| 1 |
2016-10-12T18:25:12Z
|
[
"python",
"neural-network",
"keras",
"recurrent-neural-network",
"lstm"
] |
Python list zeroth element mix up
| 39,674,723 |
<p>I want to write a function decode(chmod) that takes a three digit permissions number as a string and returns the permissions that it grants.
It seems to be working unless I ask for the zeroth element. I couldn't figure out why so.</p>
<pre><code>def decode(chmod):
liste = [int(i)for i in str(chmod)]
chmod = ["None", "Execute only", "Write only",
"Write and Execute", "Read only",
"Read and Execute", "Read and Write",
"Read Write and Execute"]
for i in liste:
print chmod[i]
return liste
print decode(043)
</code></pre>
| 0 |
2016-09-24T09:22:56Z
| 39,674,745 |
<p>You need quotes around 043. Try '043'.</p>
| 1 |
2016-09-24T09:26:11Z
|
[
"python",
"list",
"zero"
] |
Python list zeroth element mix up
| 39,674,723 |
<p>I want to write a function decode(chmod) that takes a three digit permissions number as a string and returns the permissions that it grants.
It seems to be working unless I ask for the zeroth element. I couldn't figure out why so.</p>
<pre><code>def decode(chmod):
liste = [int(i)for i in str(chmod)]
chmod = ["None", "Execute only", "Write only",
"Write and Execute", "Read only",
"Read and Execute", "Read and Write",
"Read Write and Execute"]
for i in liste:
print chmod[i]
return liste
print decode(043)
</code></pre>
| 0 |
2016-09-24T09:22:56Z
| 39,674,818 |
<p>(Assuming you want to pass an integer)</p>
<p>043 is base 8 is same as 35 in base 10. You are therefore passing the integer 35 to the decode function.</p>
<p>Try changing the <code>str</code> -> <code>oct</code></p>
<pre><code>liste = [int(i) for i in oct(chmod)[2:]] #Use [2:] in Py3, and [1:] in Py2
</code></pre>
| 1 |
2016-09-24T09:34:37Z
|
[
"python",
"list",
"zero"
] |
Logs are lost due to log rotation of logging module
| 39,674,786 |
<p>I have written some devops related migration tool in python which runs for several hours (like 50-60 hours for each cluster migration activity). I used python's logging module in the tool to log relevant information. The log automatically rotates every 24 hours. As a result, the old log file gets zipped into .gz format and a new empty file (with same name) gets created. However, in the new file I cannot find any logs (that I thought would contain logs after the log rotation)</p>
<p>I tried googling this problem, but couldn't find relevant information. Would highly appreciate any help regarding this.</p>
<p>code snippet:
<code>
import logging
LOG = logging.getLogger(<strong>name</strong>)</p>
<p>def setup_logging(logfile, levelName):
filename = logfile
try:
level = getattr(logging, levelName.upper())
except:
print 'Invalid loglevel:%s' % levelName
logging.basicConfig(filename=filename,
level=level,
format='%(asctime)s [%(levelname)s] [%(filename)s:%(lineno)s - %(funcName)s()] %(message)s')</p>
<p></code></p>
<p>After setting up logging like that I use something like:</p>
<p>LOG.info('') / LOG.warning('')</p>
| 0 |
2016-09-24T09:30:31Z
| 39,681,566 |
<p>Ok. So I found a way to handle this kind of scenario by using WatchedFileHandler as suggested here:</p>
<p><a href="http://stackoverflow.com/questions/9106795/python-logging-and-rotating-files">Python logging and rotating files</a></p>
| 0 |
2016-09-24T22:35:10Z
|
[
"python",
"python-2.7",
"logging"
] |
Python - Alternative for using numpy array as key in dictionary
| 39,674,863 |
<p>I'm pretty new to Python numpy. I was attempted to use numpy array as the key in dictionary in one of my functions and then been told by Python interpreter that numpy array is not hashable. I've just found out that one way to work this issue around is to use <code>repr()</code> function to convert numpy array to a string but it seems very expensive. Is there any better way to achieve same effect?</p>
<p>Update: I could create a new class to contain the numpy array, which seems to be right way to achieve what I want. Just wondering if there is any better method?</p>
<p>update 2: Using a class to contain data in the array and then override <code>__hash__</code> function is acceptable, however, I'd prefer the solution provided by @hpaulj. Convert the <code>array/list</code> to a <code>tuple</code> fits my need in a better way as it does not require an additional class. </p>
| 0 |
2016-09-24T09:39:39Z
| 39,678,913 |
<p>After done some researches and reading through all comments. I think I've known the answer to my own question so I'd just write them down.</p>
<ol>
<li>Write a class to contain the data in the <code>array</code> and then override <code>__hash__</code> function to amend the way how it is <strong>hashed</strong> as mentioned by <a href="http://stackoverflow.com/users/3051961/zdar">ZdaR</a></li>
<li>Convert this <code>array</code> to a <code>tuple</code>, which makes the list <strong>hashable</strong> instantaneously.Thanks to <a href="http://stackoverflow.com/users/901925/hpaulj">hpaulj</a></li>
</ol>
<p>I'd prefer method No.2 because it fits my need better, as well as simpler. However, using a class might bring some additional benefits so it could also be useful.</p>
| 2 |
2016-09-24T17:09:17Z
|
[
"python",
"arrays",
"numpy",
"dictionary"
] |
Is There Complete Overlap Between `pd.pivot_table` and `pd.DataFrame.groupby` + `pd.DataFrame.unstack`?
| 39,674,876 |
<p>(Please note that there's a question <a href="http://stackoverflow.com/questions/34702815/pandas-group-by-and-pivot-table-difference">Pandas: group by and Pivot table difference</a>, but this question is different.)</p>
<p>Suppose you start with a DataFrame</p>
<pre><code>df = pd.DataFrame({'a': ['x'] * 2 + ['y'] * 2, 'b': [0, 1, 0, 1], 'val': range(4)})
>>> df
Out[18]:
a b val
0 x 0 0
1 x 1 1
2 y 0 2
3 y 1 3
</code></pre>
<p>Now suppose you want to make the index <code>a</code>, the columns <code>b</code>, the values in a cell <code>val</code>, and specify what to do if there are two or more values in a resulting cell:</p>
<pre><code>b 0 1
a
x 0 1
y 2 3
</code></pre>
<p>Then you can do this either through</p>
<pre><code>df.val.groupby([df.a, df.b]).sum().unstack()
</code></pre>
<p>or through</p>
<pre><code>pd.pivot_table(df, index='a', columns='b', values='val', aggfunc='sum')
</code></pre>
<p>So it seems to me that there's a simple correspondence between correspondence between the two (given one, you could almost write a script to transform it into the other). I also thought of more complex cases with hierarchical indices / columns, but I still see no difference.</p>
<p>Is there something I've missed? </p>
<ul>
<li><p>Are there operations that can be performed using one and not the other? </p></li>
<li><p>Ar there, perhaps, operations easier to perform using one over the other? </p></li>
<li><p>If not, why not deprecate <code>pivot_tale</code>? <code>groupby</code> seems much more general.</p></li>
</ul>
| 2 |
2016-09-24T09:40:47Z
| 39,683,922 |
<p>If I understood the source code for <code>pivot_table(index, columns, values, aggfunc)</code> correctly it's tuned up equivalent for:</p>
<pre><code>df.groupby([index + columns]).agg(aggfunc).unstack(columns)
</code></pre>
<p><strong>plus:</strong></p>
<ul>
<li>margins (subtotals and grand totals as <a href="http://stackoverflow.com/questions/39674876/is-there-complete-overlap-between-pd-pivot-table-and-pd-dataframe-groupby#comment66651719_39674876">@ayhan has already said</a>)</li>
<li><code>pivot_table()</code> also removes extra multi-levels from columns axis (see example below)</li>
<li>convenient <code>dropna</code> parameter: Do not include columns whose entries are all NaN</li>
</ul>
<p>Demo: (I took this DF from the docstring [source code for <code>pivot_table()</code>])</p>
<pre><code>In [40]: df
Out[40]:
A B C D
0 foo one small 1
1 foo one large 2
2 foo one large 2
3 foo two small 3
4 foo two small 3
5 bar one large 4
6 bar one small 5
7 bar two small 6
8 bar two large 7
In [41]: df.pivot_table(index=['A','B'], columns='C', values='D', aggfunc=[np.sum,np.mean])
Out[41]:
sum mean
C large small large small
A B
bar one 4.0 5.0 4.0 5.0
two 7.0 6.0 7.0 6.0
foo one 4.0 1.0 2.0 1.0
two NaN 6.0 NaN 3.0
</code></pre>
<p>pay attention at the top level column: <code>D</code></p>
<pre><code>In [42]: df.groupby(['A','B','C']).agg([np.sum, np.mean]).unstack('C')
Out[42]:
D
sum mean
C large small large small
A B
bar one 4.0 5.0 4.0 5.0
two 7.0 6.0 7.0 6.0
foo one 4.0 1.0 2.0 1.0
two NaN 6.0 NaN 3.0
</code></pre>
<blockquote>
<p>why not deprecate pivot_tale? groupby seems much more general.</p>
</blockquote>
<p>IMO, because it's very easy to use and very convenient!
;)</p>
| 1 |
2016-09-25T06:02:49Z
|
[
"python",
"pandas",
"group-by",
"pivot-table"
] |
Web scraping using regex
| 39,674,898 |
<p>I'm running into a wall why this code does not work, even thought it's the same code as on an online tutorial <a href="http://www.youtube.com/watch?v=5FoSwMZ4uJg&t=6m22s" rel="nofollow">Python Web Scraping Tutorial 5 (Network Requests)</a>. I tried running the code also via online Python interpreter.</p>
<pre><code>import urllib
import re
htmltext = urllib.urlopen("https://www.google.com/finance?q=AAPL")
regex = '<span id="ref_[^.]*_l">(.+?)</span>'
pattern = re.compile(regex)
results = re.findall(pattern,htmltext)
results
</code></pre>
<p>I get:</p>
<pre><code>re.pyc in findall(pattern, string, flags)
175
176 Empty matches are included in the result."""
--> 177 return _compile(pattern, flags).findall(string)
178
179 if sys.hexversion >= 0x02020000:
TypeError: expected string or buffer
</code></pre>
<p>Expected result(s):</p>
<pre><code>112.71
</code></pre>
<p>Help appreciated. I tried using "read()" on the url but that didn't work. According to documentation even empty results should be included. Thanks</p>
| -3 |
2016-09-24T09:42:59Z
| 39,675,032 |
<p>The problem is that you have not actually read the HTML from the request.</p>
<pre><code>htmltext = urllib.urlopen("https://www.google.com/finance?q=AAPL").read()
</code></pre>
| 0 |
2016-09-24T09:56:23Z
|
[
"python",
"regex",
"web-scraping",
"typeerror"
] |
Web scraping using regex
| 39,674,898 |
<p>I'm running into a wall why this code does not work, even thought it's the same code as on an online tutorial <a href="http://www.youtube.com/watch?v=5FoSwMZ4uJg&t=6m22s" rel="nofollow">Python Web Scraping Tutorial 5 (Network Requests)</a>. I tried running the code also via online Python interpreter.</p>
<pre><code>import urllib
import re
htmltext = urllib.urlopen("https://www.google.com/finance?q=AAPL")
regex = '<span id="ref_[^.]*_l">(.+?)</span>'
pattern = re.compile(regex)
results = re.findall(pattern,htmltext)
results
</code></pre>
<p>I get:</p>
<pre><code>re.pyc in findall(pattern, string, flags)
175
176 Empty matches are included in the result."""
--> 177 return _compile(pattern, flags).findall(string)
178
179 if sys.hexversion >= 0x02020000:
TypeError: expected string or buffer
</code></pre>
<p>Expected result(s):</p>
<pre><code>112.71
</code></pre>
<p>Help appreciated. I tried using "read()" on the url but that didn't work. According to documentation even empty results should be included. Thanks</p>
| -3 |
2016-09-24T09:42:59Z
| 39,676,185 |
<p>If you follow the tutorial until the end :) :</p>
<pre><code>% python2
>>> import urllib
>>> data = urllib.urlopen('https://www.google.com/finance/getprices?q=AAPL&x=NASD&i=10&p=25m&f=c&auto=1').read()
>>> print data.split()[-1]
112.71
</code></pre>
<p>Never use regex to web scrape</p>
<p>I make improvement to fetch last array element simpler</p>
| 0 |
2016-09-24T12:11:31Z
|
[
"python",
"regex",
"web-scraping",
"typeerror"
] |
Running single test in unittest python
| 39,674,968 |
<p>I have a test_method() in a directory /tests. I want to run a single test from the command line. Instead of using test_module.TestClass.test_method I wish to just mention it as</p>
<p>$ ./test-runner test_method</p>
<p>and let the discover decide the test_method belongs to which test_module and in which TestClass. I am able to get the test_module by running a search based on strings in all test_modules present as test_module is python file. But how to get the TestClass holding the test_method within the file? Any idea?</p>
| 1 |
2016-09-24T09:49:28Z
| 39,675,491 |
<p>Instead of doing that yourself, you ought to use <a href="http://nose.readthedocs.io/en/latest/" rel="nofollow">nose</a> with the <code>nosetests</code> command, or, better, use <a href="http://doc.pytest.org/en/latest/" rel="nofollow">py-test</a> (and <a href="https://testrun.org/tox/latest/" rel="nofollow">tox</a>).</p>
<p>The classic usage with unit test is to add a main in your module:</p>
<pre><code>if __name__ == "__main__":
unittest.main()
</code></pre>
<p>See the <a href="https://docs.python.org/2/library/unittest.html#basic-example" rel="nofollow">Basic example</a> in the doc</p>
<p>The main function has parameters used to choose the tests to run. See <a href="https://docs.python.org/2/library/unittest.html#unittest.main" rel="nofollow">unittest.main</a> in the doc. </p>
| 0 |
2016-09-24T10:48:28Z
|
[
"python",
"python-unittest"
] |
python heapq sorting list wrong?
| 39,675,066 |
<p>I am trying to sort lists into one list that contain numbers and names of sections, sub sections and sub sub sections. The program looks like this:</p>
<pre><code>import heapq
sections = ['1. Section', '2. Section', '3. Section', '4. Section', '5. Section', '6. Section', '7. Section', '8. Section', '9. Section', '10. Section', '11. Section', '12. Section']
subsections = ['1.1 Subsection', '1.2 Subsection', '1.3 Subsection', '1.4 Subsection', '2.1 Subsection', '4.1 My subsection', '7.1 Subsection', '8.1 Subsection', '12.1 Subsection']
subsubsections = ['1.2.1 Subsubsection', '1.2.2 Subsubsection', '1.4.1 Subsubsection', '2.1.1 Subsubsection', '7.1.1 Subsubsection', '8.1.1 Subsubsection', '12.1.1 Subsubsection']
sorted_list = list(heapq.merge(sections, subsections, subsubsections))
print(sorted_list)
</code></pre>
<p>What I get out is this:</p>
<pre><code>['1. Section', '1.1 Subsection', '1.2 Subsection', '1.2.1 Subsubsection', '1.2.2 Subsubsection', '1.3 Subsection', '1.4 Subsection', '1.4.1 Subsubsection', '2. Section', '2.1 Subsection', '2.1.1 Subsubsection', '3. Section', '4. Section', '4.1 My subsection', '5. Section', '6. Section', '7. Section', '7.1 Subsection', '7.1.1 Subsubsection', '8. Section', '8.1 Subsection', '12.1 Subsection', '8.1.1 Subsubsection', '12.1.1 Subsubsection', '9. Section', '10. Section', '11. Section', '12. Section']
</code></pre>
<p>My 12th subsection, and sub sub section is located within 8th section, not 12th.</p>
<p>Why is this happening? The original lists are sorted, and it all goes good, apparently up to number 10. </p>
<p>I'm not sure why this is happening and is there a way to better sort this into a 'tree' based on the numbers in the lists? I'm building a table of contents of sorts, and this will return (once I filter the list out)</p>
<pre><code>1. Section
1.1 Subsection
1.2 Subsection
1.2.1 Subsubsection
1.2.2 Subsubsection
1.3 Subsection
1.4 Subsection
1.4.1 Subsubsection
2. Section
2.1 Subsection
2.1.1 Subsubsection
3. Section
4. Section
4.1 My subsection
5. Section
6. Section
7. Section
7.1 Subsection
7.1.1 Subsubsection
8. Section
8.1 Subsection
12.1 Subsection
8.1.1 Subsubsection
12.1.1 Subsubsection
9. Section
10. Section
11. Section
12. Section
</code></pre>
<p>Notice the 12.1 Subsection behind 8.1 Subsection and 12.1.1 Subsubsection behind 8.1.1 Subsubsection.</p>
| 1 |
2016-09-24T10:00:59Z
| 39,675,168 |
<p>Your lists may <strong>appear</strong> sorted, to a human eye. But to Python, your inputs are not fully sorted, because it sorts strings <em>lexicographically</em>. That means that <code>'12'</code> comes before <code>'8'</code> in sorted order, because only the first <em>characters</em> are compared.</p>
<p>As such, the merge is completely correct; the string starting <code>'12.1'</code> is encountered after the <code>'8.1'</code> string was seen, but the one starting with <code>'8.1.1'</code> is sorted afterwards.</p>
<p>You'll have to extract <em>tuples of integers</em> from the strings with a key function to sort correctly:</p>
<pre><code>section = lambda s: [int(d) for d in s.partition(' ')[0].split('.') if d]
heapq.merge(sections, subsections, subsubsections, key=section))
</code></pre>
<p>Note that the <code>key</code> argument is only available in Python 3.5 and up; you'd have to do a manual decorate-merge-undecorate dance in earlier versions.</p>
<p>Demo (using Python 3.6):</p>
<pre><code>>>> section = lambda s: [int(d) for d in s.partition(' ')[0].split('.') if d]
>>> sorted_list = list(heapq.merge(sections, subsections, subsubsections, key=section))
>>> from pprint import pprint
>>> pprint(sorted_list)
['1. Section',
'1.1 Subsection',
'1.2 Subsection',
'1.2.1 Subsubsection',
'1.2.2 Subsubsection',
'1.3 Subsection',
'1.4 Subsection',
'1.4.1 Subsubsection',
'2. Section',
'2.1 Subsection',
'2.1.1 Subsubsection',
'3. Section',
'4. Section',
'4.1 My subsection',
'5. Section',
'6. Section',
'7. Section',
'7.1 Subsection',
'7.1.1 Subsubsection',
'8. Section',
'8.1 Subsection',
'8.1.1 Subsubsection',
'9. Section',
'10. Section',
'11. Section',
'12. Section',
'12.1 Subsection',
'12.1.1 Subsubsection']
</code></pre>
<p>The keyed merge is easily backported to Python 3.3 and 3.4:</p>
<pre><code>import heapq
def _heappop_max(heap):
lastelt = heap.pop()
if heap:
returnitem = heap[0]
heap[0] = lastelt
heapq._siftup_max(heap, 0)
return returnitem
return lastelt
def _heapreplace_max(heap, item):
returnitem = heap[0]
heap[0] = item
heapq._siftup_max(heap, 0)
return returnitem
def merge(*iterables, key=None, reverse=False):
h = []
h_append = h.append
if reverse:
_heapify = heapq._heapify_max
_heappop = _heappop_max
_heapreplace = _heapreplace_max
direction = -1
else:
_heapify = heapify
_heappop = heappop
_heapreplace = heapreplace
direction = 1
if key is None:
for order, it in enumerate(map(iter, iterables)):
try:
next = it.__next__
h_append([next(), order * direction, next])
except StopIteration:
pass
_heapify(h)
while len(h) > 1:
try:
while True:
value, order, next = s = h[0]
yield value
s[0] = next() # raises StopIteration when exhausted
_heapreplace(h, s) # restore heap condition
except StopIteration:
_heappop(h) # remove empty iterator
if h:
# fast case when only a single iterator remains
value, order, next = h[0]
yield value
yield from next.__self__
return
for order, it in enumerate(map(iter, iterables)):
try:
next = it.__next__
value = next()
h_append([key(value), order * direction, value, next])
except StopIteration:
pass
_heapify(h)
while len(h) > 1:
try:
while True:
key_value, order, value, next = s = h[0]
yield value
value = next()
s[0] = key(value)
s[2] = value
_heapreplace(h, s)
except StopIteration:
_heappop(h)
if h:
key_value, order, value, next = h[0]
yield value
yield from next.__self__
</code></pre>
<p>A decorate-sort-undecorate merge is as simple as:</p>
<pre><code>def decorate(iterable, key):
for elem in iterable:
yield key(elem), elem
sorted = [v for k, v in heapq.merge(
decorate(sections, section), decorate(subsections, section)
decorate(subsubsections, section))]
</code></pre>
<p>Because your input is already sorted, using a merge sort is more efficient. As a last resort, you could just use <code>sorted()</code> however:</p>
<pre><code>from itertools import chain
result = sorted(chain(sections, subsections, subsubsections), key=section)
</code></pre>
| 4 |
2016-09-24T10:11:26Z
|
[
"python",
"sorting"
] |
python heapq sorting list wrong?
| 39,675,066 |
<p>I am trying to sort lists into one list that contain numbers and names of sections, sub sections and sub sub sections. The program looks like this:</p>
<pre><code>import heapq
sections = ['1. Section', '2. Section', '3. Section', '4. Section', '5. Section', '6. Section', '7. Section', '8. Section', '9. Section', '10. Section', '11. Section', '12. Section']
subsections = ['1.1 Subsection', '1.2 Subsection', '1.3 Subsection', '1.4 Subsection', '2.1 Subsection', '4.1 My subsection', '7.1 Subsection', '8.1 Subsection', '12.1 Subsection']
subsubsections = ['1.2.1 Subsubsection', '1.2.2 Subsubsection', '1.4.1 Subsubsection', '2.1.1 Subsubsection', '7.1.1 Subsubsection', '8.1.1 Subsubsection', '12.1.1 Subsubsection']
sorted_list = list(heapq.merge(sections, subsections, subsubsections))
print(sorted_list)
</code></pre>
<p>What I get out is this:</p>
<pre><code>['1. Section', '1.1 Subsection', '1.2 Subsection', '1.2.1 Subsubsection', '1.2.2 Subsubsection', '1.3 Subsection', '1.4 Subsection', '1.4.1 Subsubsection', '2. Section', '2.1 Subsection', '2.1.1 Subsubsection', '3. Section', '4. Section', '4.1 My subsection', '5. Section', '6. Section', '7. Section', '7.1 Subsection', '7.1.1 Subsubsection', '8. Section', '8.1 Subsection', '12.1 Subsection', '8.1.1 Subsubsection', '12.1.1 Subsubsection', '9. Section', '10. Section', '11. Section', '12. Section']
</code></pre>
<p>My 12th subsection, and sub sub section is located within 8th section, not 12th.</p>
<p>Why is this happening? The original lists are sorted, and it all goes good, apparently up to number 10. </p>
<p>I'm not sure why this is happening and is there a way to better sort this into a 'tree' based on the numbers in the lists? I'm building a table of contents of sorts, and this will return (once I filter the list out)</p>
<pre><code>1. Section
1.1 Subsection
1.2 Subsection
1.2.1 Subsubsection
1.2.2 Subsubsection
1.3 Subsection
1.4 Subsection
1.4.1 Subsubsection
2. Section
2.1 Subsection
2.1.1 Subsubsection
3. Section
4. Section
4.1 My subsection
5. Section
6. Section
7. Section
7.1 Subsection
7.1.1 Subsubsection
8. Section
8.1 Subsection
12.1 Subsection
8.1.1 Subsubsection
12.1.1 Subsubsection
9. Section
10. Section
11. Section
12. Section
</code></pre>
<p>Notice the 12.1 Subsection behind 8.1 Subsection and 12.1.1 Subsubsection behind 8.1.1 Subsubsection.</p>
| 1 |
2016-09-24T10:00:59Z
| 39,675,262 |
<p>As explained in other answer you have to specify a sorting method, otherwise python will sort the strings lexicographically. If you are using python 3.5+ you can use <code>key</code> argument in <code>merge</code> function, in pyhton 3.5- you can use <code>itertools.chain</code> and <code>sorted</code>, and as a general approach you can use regex in order to find the numbers and convert them to int :</p>
<pre><code>In [18]: from itertools import chain
In [19]: import re
In [23]: sorted(chain.from_iterable((sections, subsections, subsubsections)),
key = lambda x: [int(i) for i in re.findall(r'\d+', x)])
Out[23]:
['1. Section',
'1.1 Subsection',
'1.2 Subsection',
'1.2.1 Subsubsection',
'1.2.2 Subsubsection',
'1.3 Subsection',
'1.4 Subsection',
'1.4.1 Subsubsection',
'2. Section',
'2.1 Subsection',
'2.1.1 Subsubsection',
'3. Section',
'4. Section',
'4.1 My subsection',
'5. Section',
'6. Section',
'7. Section',
'7.1 Subsection',
'7.1.1 Subsubsection',
'8. Section',
'8.1 Subsection',
'8.1.1 Subsubsection',
'9. Section',
'10. Section',
'11. Section',
'12. Section',
'12.1 Subsection',
'12.1.1 Subsubsection']
</code></pre>
| 4 |
2016-09-24T10:20:38Z
|
[
"python",
"sorting"
] |
Generating normal distribution in order python, numpy
| 39,675,085 |
<p>I am able to generate random samples of normal distribution in numpy like this.</p>
<pre><code>>>> mu, sigma = 0, 0.1 # mean and standard deviation
>>> s = np.random.normal(mu, sigma, 1000)
</code></pre>
<p>But they are in random order, obviously. How can I generate numbers in order, that is, values should rise and fall like in a normal distribution.</p>
<p>In other words, I want to create a curve (gaussian) with mu and sigma and <code>n</code> number of points which I can input.</p>
<p>How to do this?</p>
| -3 |
2016-09-24T10:02:22Z
| 39,676,042 |
<p>To (1) generate a random sample of x-coordinates of size n (from the normal distribution) (2) evaluate the normal distribution at the x-values (3) sort the x-values by the magnitude of the normal distribution at their positions, this will do the trick:</p>
<pre><code>import numpy as np
mu,sigma,n = 0.,1.,1000
def normal(x,mu,sigma):
return ( 2.*np.pi*sigma**2. )**-.5 * np.exp( -.5 * (x-mu)**2. / sigma**2. )
x = np.random.normal(mu,sigma,n) #generate random list of points from normal distribution
y = normal(x,mu,sigma) #evaluate the probability density at each point
x,y = x[np.argsort(y)],np.sort(y) #sort according to the probability density
</code></pre>
| 1 |
2016-09-24T11:54:04Z
|
[
"python",
"numpy",
"normal-distribution"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.