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>yie...
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...
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 <...
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 th...
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 an...
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 &lt; foo4 for l, r in pairs: ...
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 an...
1
2016-09-24T02:47:42Z
39,673,448
<p>You can find the rows with <code>df[df['foo3'] &lt; df['foo4']]</code>, yes, but if you use the Boolean series instead, you can easily accomplish your goal:</p> <pre><code>s = df['foo3'] &lt; df['foo4'] df.loc[s, ['foo1','foo2']] = df.loc[s, ['foo2','foo1']].values df.loc[s, ['foo3','foo4']] = df.loc[s, ['foo4','fo...
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. <...
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://develope...
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 do...
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 do...
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 ...
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 a...
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...
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 a...
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 t...
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....
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>&gt;&gt;&gt; limit(1/x, x, 0, '+') oo &gt;&gt;&gt; limit(1/x, x, 0, '-') -oo &gt;&gt;&gt; limit(1/x, x, 0) oo </code></pre> <p>The default is from the right. Bidirectional limits are not directly implemented yet...
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"}])))...
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"...
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"}])))...
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 +=[...
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 "attribut...
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 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...
0
2016-09-24T04:09:47Z
39,674,079
<p>The <code>rotate</code> attribute of a <code>&lt;text&gt;</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....
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...
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 <co...
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_f...
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...
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 = s...
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...
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...
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</stron...
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...
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...
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>&lt;script&gt; $(function() { // Hide all elements with a class starting with catlistforum $('[class^="catl...
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...
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...
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() i...
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...
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 ...
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...
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...
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/" &lt;-- With the double quotes') myurl = input("@&gt; ") for i in re.findall('''href=["...
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_in...
-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)...
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...
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('Ent...
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&gt;0: for function in range(integer): num=num*decimal if integer&lt;0: num=1.0 # force floating point division for function in range(-integer): n...
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('Ent...
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 &gt; 0 else num/decimal return num power_function(2, 2) # 4 power_function(2, -2) # 0.25 </c...
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 th...
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...
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, ...
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"...
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, ...
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 d...
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 e...
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> ...
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 e...
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...
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 e...
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></...
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 e...
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 broke...
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 e...
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 t...
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 e...
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?</...
-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?</...
-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 eac...
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? M...
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? M...
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 option...
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 ...
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 mem...
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 M...
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><co...
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> ...
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 c...
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 on...
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></p...
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 on...
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.upp...
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 on...
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 fr...
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']: ...
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"...
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 combi...
0
2016-09-24T06:38:06Z
39,673,553
<p>This is wrong:</p> <pre><code>while count&lt;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&lt;numbers</code> is always true, so you are stuck in an infinite loop. Try it:</p> <pre><code>&gt;&gt;&gt; 1000000 &lt; [1, 2] True </c...
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 combi...
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&lt;len(numbers): #error thats a list you have to convert that ...
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 image...
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...
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 nu...
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></...
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 nu...
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>...
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 nu...
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/...
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...
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...
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
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) # &lt;-- Add return here else: return ...
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:/...
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 f...
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 ...
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 ha...
-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 ha...
-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 ha...
-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>&gt;&gt;&gt; l = [] &gt;&gt;&gt; l.append(1) &gt;&gt;&...
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 ha...
-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 = []...
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 ha...
-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 ha...
-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>...
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 ha...
-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>&gt;&gt;&gt; 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>&lt;strong t-field="company.partner_id" styl...
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, compty...
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>Expect...
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) ...
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 -DskipTes...
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>&lt;plugin&gt; &lt;groupId&gt;org.vafer&lt;/groupId&gt; &lt;artifactId&gt;jdeb&lt;/artifactId&gt; &lt;version&gt;1.0.1&lt;/version&gt; &lt;executions&gt; &lt;execution&g...
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, ...
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\ ...
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=A91571BB81F620690376AF422A09EEF8A7C4F6C09978F36851B8DEDFA56C19C96A67EBD8BBD29C385C410CBC63D38135EFAE61...
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': ''...
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 ...
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 i...
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 ...
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 lis...
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 he...
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://stackover...
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(enumHa...
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+0...
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><...
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("&gt; ") if "0" in choice or "1" in choice: how_much = int(choice) else: dead("Man, learn to type a number.") if how_much &lt; 50: print "Nice, you'...
-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 f...
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 &lt;module&gt...
-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>&gt;&gt;&gt; sys.stdout.encoding 'cp852' &gt;&gt;&gt; u'\u0150'.encode(sys.stdout.encoding) '\x8a' &gt;&gt;&gt; print u'\u0150'...
-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): ...
-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() @class...
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 loo...
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': 'Центральный администратÐ...
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 di...
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 tr...
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 ar...
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 th...
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 f...
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 th...
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/ti...
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)] chmo...
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)] chmo...
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 for...
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 s...
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 m...
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
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...
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&amp;t=6m22s" rel="nofollow">Python Web Scraping Tutorial 5 (Network Requests)</a>. I tried running the code also via online Python interpreter.</p> <pre><...
-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&amp;t=6m22s" rel="nofollow">Python Web Scraping Tutorial 5 (Network Requests)</a>. I tried running the code also via online Python interpreter.</p> <pre><...
-3
2016-09-24T09:42:59Z
39,676,185
<p>If you follow the tutorial until the end :) :</p> <pre><code>% python2 &gt;&gt;&gt; import urllib &gt;&gt;&gt; data = urllib.urlopen('https://www.google.com/finance/getprices?q=AAPL&amp;x=NASD&amp;i=10&amp;p=25m&amp...
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....
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>...
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', '...
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 suc...
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', '...
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 gen...
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>&gt;&gt;&gt; mu, sigma = 0, 0.1 # mean and standard deviation &gt;&gt;&gt; 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, val...
-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...
1
2016-09-24T11:54:04Z
[ "python", "numpy", "normal-distribution" ]