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
How to print '%d' & '%s' in a class in python
37,546,433
<p>I'm writing a script which counts some specific words and gives me specific count of the words. </p> <p>I'm currently stuck in printing data, from the class. </p> <p>My next task would be put these values in a excel file using a data driven framework. </p> <p>Here's what i have done until now:</p> <pre><code>a =...
1
2016-05-31T12:57:31Z
37,546,612
<p>There is a problem in the order of operations. What's actually being executed is: <code>print '%s' + ' ' + ('%d' %(tittle,blockcode_passed))</code>.</p> <p>Python is trying to use <code>tittle</code> in place of the <code>%d</code> argument. You can change it with either:</p> <pre><code>print ('%s' + ' ' + '%d') %...
1
2016-05-31T13:05:43Z
[ "python", "python-2.7", "class", "oop", "beautifulsoup" ]
Python / closing is not defined
37,546,437
<p>I try to follow the <a href="https://pypi.python.org/pypi/scpclient" rel="nofollow">instructions of the scpclient</a>.</p> <p>I wrote the following code:</p> <pre><code>import paramiko client = paramiko.SSHClient() client.load_system_host_keys() client.set_missing_host_key_policy(paramiko.WarningPolicy()) client.c...
-1
2016-05-31T12:57:45Z
37,546,521
<p>You need to import it: <a href="https://docs.python.org/2/library/contextlib.html#contextlib.closing" rel="nofollow"><code>from contextlib import closing</code></a></p>
1
2016-05-31T13:01:47Z
[ "python" ]
python map/reduce: emit multiple keys values from single map lambda
37,546,459
<p>Is there a canonical way to emit multiple keys from a single item in the input sequence so that they form a continuous sequence and I don't need to use a <code>reduce(...)</code> just to flatten the sequence?</p> <p>e.g. if I wanted to expand each digit in a series of numbers into individual numbers in a sequence</...
2
2016-05-31T12:58:49Z
37,546,492
<p><code>map(func, *iterables)</code> will always call <code>func</code> as many times as the length of the shortest iterable (assuming no Exception is raised). Functions always return a single object. So <code>list(map(func, *iterables))</code> will always have the same length as the shortest iterable. </p> <p>Thus ...
3
2016-05-31T13:00:19Z
[ "python", "python-2.7" ]
python map/reduce: emit multiple keys values from single map lambda
37,546,459
<p>Is there a canonical way to emit multiple keys from a single item in the input sequence so that they form a continuous sequence and I don't need to use a <code>reduce(...)</code> just to flatten the sequence?</p> <p>e.g. if I wanted to expand each digit in a series of numbers into individual numbers in a sequence</...
2
2016-05-31T12:58:49Z
37,546,819
<p>Got two ideas, one with list comprehentions:</p> <pre><code>print [int(j) for i in somedata for j in list(str(i)) ] </code></pre> <p>Something new (from comments), string is already iterable, so it would be:</p> <pre><code>print [int(j) for i in somedata for j in str(i) ] </code></pre> <p>second with opertations...
2
2016-05-31T13:15:13Z
[ "python", "python-2.7" ]
How to bundle script into dmg file
37,546,533
<p>I am creating a dmg for qt standalone application using macdeployqt. I am calling a python script from qt application. I am not clear how can i bundle python script with dmg file.</p> <p>thanks </p>
0
2016-05-31T13:02:16Z
37,565,661
<p>I managed to get that done using QMAKE_BUNDLE_DATA</p> <p><a href="https://forum.qt.io/topic/67661/bundle-python-into-qt-application-dmg-and-exe/7" rel="nofollow">https://forum.qt.io/topic/67661/bundle-python-into-qt-application-dmg-and-exe/7</a></p>
0
2016-06-01T10:09:46Z
[ "python", "c++", "qt" ]
Make a variable from what's in a text file
37,546,552
<p>So I want to make a variable from the contents of a text file.</p> <p>E.g The text file contains the sentence "Ask not what your country can do for you ask what you can do for your country"</p> <p>Now I want the variable to be like Sentence = ("Ask not what your country can do for you ask what you can do for your...
-2
2016-05-31T13:02:48Z
37,546,621
<p>The file contains. </p> <pre><code>rahul@HP-EliteBook ~/Projects/Stackoverflow $ cat abc.txt hai am here </code></pre> <p>Here is the python code.It's very simple logic.</p> <pre><code>fo = open("abc.txt", "r+") a = fo.read() </code></pre>
2
2016-05-31T13:06:17Z
[ "python", "variables" ]
Using Selenium to select a frame
37,546,675
<p>So I'm trying to select a frame using selenium. I found many examples and similar questions on stackoverflow regarding this.</p> <p>All of them pointed out that to select elements that are in a frame you first have to "move" to that frame and then get the element you want. But I can't seem to get the frame that I w...
0
2016-05-31T13:08:55Z
37,547,887
<p>Without the website in question it's hard to pinpoint what the problem is but I will take a few assumptions:</p> <ul> <li><p>Your frameset is doing some javascript on the function <code>load()</code> which may make the elements unavailable when you try to find them.</p></li> <li><p><strike>The frame element you're ...
2
2016-05-31T14:01:23Z
[ "python", "selenium" ]
Using Selenium to select a frame
37,546,675
<p>So I'm trying to select a frame using selenium. I found many examples and similar questions on stackoverflow regarding this.</p> <p>All of them pointed out that to select elements that are in a frame you first have to "move" to that frame and then get the element you want. But I can't seem to get the frame that I w...
0
2016-05-31T13:08:55Z
37,561,278
<p>As @Rafael said, it is better to use a different locator, and you should check what the on load() javascript is doing. However I would suggest using the id of the frame as the locator and not an xpath for the frame name.</p> <pre><code>element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID,...
1
2016-06-01T06:44:41Z
[ "python", "selenium" ]
Get absolute path of caller file
37,546,685
<p>Say I have two files in different directories: <code>1.py</code> (say, in <code>C:/FIRST_FOLDER/1.py</code>) and <code>2.py</code> (say, in <code>C:/SECOND_FOLDER/2.py</code>).</p> <p>The file <code>1.py</code> imports <code>2.py</code> (using <code>sys.path.insert(0, #path_of_2.py)</code> followed, obviously, by <...
0
2016-05-31T13:09:25Z
37,546,839
<p>To return the absolute path of a python file, use python's <code>__file__</code> attribute:</p> <pre><code>import os path = os.path.abspath(__file__) </code></pre>
0
2016-05-31T13:15:59Z
[ "python" ]
Get absolute path of caller file
37,546,685
<p>Say I have two files in different directories: <code>1.py</code> (say, in <code>C:/FIRST_FOLDER/1.py</code>) and <code>2.py</code> (say, in <code>C:/SECOND_FOLDER/2.py</code>).</p> <p>The file <code>1.py</code> imports <code>2.py</code> (using <code>sys.path.insert(0, #path_of_2.py)</code> followed, obviously, by <...
0
2016-05-31T13:09:25Z
37,547,263
<pre><code>import inspect import os abs_path = os.path.abspath((inspect.stack()[0])[1]) directory_of_1py = os.path.dirname(abs_path) </code></pre> <p>for more information on the module <a href="https://docs.python.org/2/library/os.path.html" rel="nofollow">os.path</a></p>
0
2016-05-31T13:33:46Z
[ "python" ]
How to find what version of dawg I have?
37,546,726
<p>How can I find what version of dwag I have installed in python? Usually packagename.<strong>version</strong> does the trick, but dawg seems to lack the relevant methods.</p>
0
2016-05-31T13:11:32Z
37,547,401
<p>Normally you would go with:</p> <pre><code>print( pack.__version__ ) </code></pre> <p>or </p> <pre><code>help( pack ) </code></pre> <p>I am wondering if they just didn't include the version yet? The only way I could do it here was with larsks' comment, but that wouldn't work if not installed with pip. Not even t...
0
2016-05-31T13:39:14Z
[ "python", "import", "python-import", "dawg" ]
How to find what version of dawg I have?
37,546,726
<p>How can I find what version of dwag I have installed in python? Usually packagename.<strong>version</strong> does the trick, but dawg seems to lack the relevant methods.</p>
0
2016-05-31T13:11:32Z
37,661,187
<p>Since dawg was installed with pip, the best way to learn what version I have is with <code>pip list installed</code>. (Credit to larsks' comment.)</p>
0
2016-06-06T15:25:05Z
[ "python", "import", "python-import", "dawg" ]
Plot 2D array with imshow, setting axes values
37,546,769
<p>I have to plot the 2D array (called para_beta) with dimensions (2779, 1334). These dimensions refer to the (time, height) that the measurements were taken. </p> <p>When I plot using the code, the x axis and y axis ticks are just the count of the array dimensions, and don't reflect the time or height. I have lists ...
0
2016-05-31T13:13:25Z
37,551,139
<p><code>para_beta</code> is 2D (time x height), right? Then the read-in call needs to reflect those two dimensions: </p> <p><code>para_beta_raw = nc_file.variables['para_beta'][:,:]</code> (note the two colons, instead of one). </p>
1
2016-05-31T16:32:50Z
[ "python", "multidimensional-array", "imshow" ]
Plot 2D array with imshow, setting axes values
37,546,769
<p>I have to plot the 2D array (called para_beta) with dimensions (2779, 1334). These dimensions refer to the (time, height) that the measurements were taken. </p> <p>When I plot using the code, the x axis and y axis ticks are just the count of the array dimensions, and don't reflect the time or height. I have lists ...
0
2016-05-31T13:13:25Z
37,562,776
<p>I just found a <a href="http://stackoverflow.com/questions/11480568/correcting-the-axes-using-imshow">duplicate of my question</a> which has already been answered! I was using <code>extent</code> wrong as I took the min/max values from the para_beta array, when they should be taken from the time_bnds and altitude ar...
0
2016-06-01T08:00:16Z
[ "python", "multidimensional-array", "imshow" ]
Python, choose logging files' directory
37,546,770
<p>I am using the Python logging library and want to choose the folder where the log files will be written.</p> <p>For the moment, I made an instance of TimedRotatingFileHandler with the entry parameter filename="myLogFile.log" . This way myLogFile.log is created on the same folder than my python script. I want to cre...
0
2016-05-31T13:13:25Z
37,547,070
<p>Simple give a different filename like <code>filename=r"C:\User\Matias\Desktop\myLogFile.log</code></p>
1
2016-05-31T13:25:33Z
[ "python", "logging" ]
Python, choose logging files' directory
37,546,770
<p>I am using the Python logging library and want to choose the folder where the log files will be written.</p> <p>For the moment, I made an instance of TimedRotatingFileHandler with the entry parameter filename="myLogFile.log" . This way myLogFile.log is created on the same folder than my python script. I want to cre...
0
2016-05-31T13:13:25Z
37,547,193
<p>Specify an absolute path when creating instance TimedRotatingFileHandler:</p> <pre><code>from logging.handlers import TimedRotatingFileHandler </code></pre> <p>h = TimedRotatingFileHandler('/home/user/Desktop/myLogFile.log')</p> <p>or </p> <pre><code>from logging.handlers import TimedRotatingFileHandler </code><...
0
2016-05-31T13:30:06Z
[ "python", "logging" ]
Selectively loading backrefs in SQLAlchemy
37,546,807
<p>Following the examples here: <a href="http://docs.sqlalchemy.org/en/latest/orm/loading_relationships.html" rel="nofollow">http://docs.sqlalchemy.org/en/latest/orm/loading_relationships.html</a>, one can easily load <em>all</em> the addresses for the <code>User</code> with name Jack like so:</p> <pre><code>jack = se...
0
2016-05-31T13:14:54Z
37,552,765
<p>You have to do a join manually then specify <code>contains_eager</code>, like this:</p> <pre><code>session.query(User).join(User.addresses) \ .filter(User.name == "jack", Address.email.like("%@google.com")) \ .options(contains_eager(User.addresses)) <...
1
2016-05-31T18:08:11Z
[ "python", "sqlalchemy" ]
passing fields of an array of collections through functions in python
37,546,864
<p>is there a way of passing a field of an array of collections into a function so that it can still be used to access a element in the collection in python?. i am attempting to search through an array of collections to locate a particular item by comparing it with an identifier. this identifier and field being compare...
-1
2016-05-31T13:17:14Z
37,547,900
<p>In your code, <code>M_work</code> is a list. Lists are accessed using an index and this syntax: <code>myList[index]</code>. So that would translate to <code>M_work[place]</code> in your case. Then you say that <code>M_work</code> stores objects which have fields, and you want to access one of these fields by name. T...
0
2016-05-31T14:01:52Z
[ "python" ]
PyTest: test which function was called in the if statement
37,546,921
<p>I have a function, which considers three different cases and for each case calls a different function, like in the example below</p> <pre><code>def my_fun(input): if input == 1: fun1() if input == 2: fun2() if input == 3: fun3() </code></pre> <p>I would like to write a test for function <code>my_fun...
0
2016-05-31T13:19:28Z
37,547,072
<p>Why multiple if statements and not elif? They conditions are mutually exclusive so why waste another check ? But anyway, how about dummy prints, like so:</p> <pre><code>def my_fun(input): if input == 1: fun1() print("Function 1 executed ?") elif input == 2: fun2() print("Func...
-3
2016-05-31T13:25:35Z
[ "python", "python-2.7", "testing", "py.test" ]
PyTest: test which function was called in the if statement
37,546,921
<p>I have a function, which considers three different cases and for each case calls a different function, like in the example below</p> <pre><code>def my_fun(input): if input == 1: fun1() if input == 2: fun2() if input == 3: fun3() </code></pre> <p>I would like to write a test for function <code>my_fun...
0
2016-05-31T13:19:28Z
37,547,261
<p>As @fmarc commented, which function is called is less important than testing that <code>my_fun</code> does the right thing. But, you can mock each of the three functions, then test that the correct one was called independently of what each function actually does. (Note that <code>mock</code> is a 3rd-party module in...
2
2016-05-31T13:33:40Z
[ "python", "python-2.7", "testing", "py.test" ]
PyTest: test which function was called in the if statement
37,546,921
<p>I have a function, which considers three different cases and for each case calls a different function, like in the example below</p> <pre><code>def my_fun(input): if input == 1: fun1() if input == 2: fun2() if input == 3: fun3() </code></pre> <p>I would like to write a test for function <code>my_fun...
0
2016-05-31T13:19:28Z
37,583,992
<p>If all fun1(), fun2(), and fun3() return results I'd go with parametrization.</p> <pre><code># Here an example of functions to be tested def fun1(): return 1 def fun2(): return 2 def fun3(): return 3 def my_fun(input): if input == 1: return fun1() if input == 2: return fun2() ...
1
2016-06-02T06:13:46Z
[ "python", "python-2.7", "testing", "py.test" ]
How come my full circle isn't 360 degrees?
37,547,136
<p>I am stuck with a confusing problem. Here's a little background:</p> <p>I'm working on qgis/python with coordinate points in Lambert93: one central point (my dict key) and several other points gravitating around it. To simplify, the code I've put down just one example:</p> <pre><code>import numpy as np import math...
1
2016-05-31T13:27:58Z
37,591,823
<p>Thanks to Hellmar's indication, here's the working code. I did two things : gave all the central points (0,0) in my plane, substracted the distance between the central point and (0,0) from all the other related points. I was then able to use atan2 because all the angles I needed to calculate were at (0,0). Atan2 is ...
0
2016-06-02T12:25:55Z
[ "python", "coordinates", "angle", "qgis" ]
change multiple filenames - python script
37,547,153
<p>first i am newbie in python. i have a bulk of files (117 files), i think their names are UTF-8 .Here is one filename sample:</p> <pre><code>1|Ø¬Ø§ÙØ§ JAVA : ÙÙÙÙÙ Ø§ÙØ®ØµØ§Ø¦Øµ Attributes ÙÙ Ø§ÙØ¨Ø±Ùجة|R9Rku3z63uI.mp4 </code></pre> <p>i want to change these filenames so i m...
0
2016-05-31T12:20:56Z
37,547,993
<p>Your <em>names</em> variable is just a string and not a list, so <em>names[i]</em> is just the i-th character in it. Either you initialize it as a list or you split() it before use.</p> <p>When your code doesn't behave as you want/expect, it is usually because your variables do not contain what you think, so addin...
0
2016-05-31T14:05:27Z
[ "python", "unicode" ]
multiply 2 subset of a df based on 2 other columns python pandas
37,547,277
<p>I have a df such has:</p> <pre><code>df Out[177]: IV maturity strike date 2000-12-29 0.435 0.083 0.600 2000-12-29 0.390 0.083 0.700 2000-12-29 0.331 0.083 0.800 2000-12-29 0.283 0.083 0.900 2000-12-29 0.391 0.250 0.600 2000-12-29 0.349 ...
1
2016-05-31T13:34:17Z
37,547,977
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.pivot.html" rel="nofollow"><code>pivot</code></a>, then multiple first and second column selected by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.iloc.html" rel="nofollow"><code>iloc</code><...
1
2016-05-31T14:05:02Z
[ "python", "pandas" ]
Get single record on Django Rest Framework based on id
37,547,294
<p>I am getting the following response from my REST API at <a href="http://127.0.0.1:8000/api/category/" rel="nofollow">http://127.0.0.1:8000/api/category/</a>:</p> <pre><code>[ { "id": "17442811-3217-4b67-8c2c-c4ab762460d6", "title": "Hair and Beauty" }, { "id": "18a136b5-3dc4-4a98...
0
2016-05-31T13:34:49Z
37,547,538
<p>Your first regex, <code>r'^category/'</code>, matches both a URL with and without a UUID.</p> <p>You should anchor it at the end:</p> <pre><code>r'^category/$' </code></pre> <p>Additionally/alternatively, you can swap the order of those URL definitions, as Django will take the first one it matches.</p>
2
2016-05-31T13:45:20Z
[ "python", "django", "rest" ]
Why is this SPARQL query missing so many results?
37,547,300
<p>(First off, my apologies as this is a blatant cross-post. I thought opendata.SE would be the place for this, but it's gotten barely any views there and it appears to not be a very active site in general, so I figure I ought to try it here as it's programming-related.)</p> <p>I'm trying to get a list of major citie...
2
2016-05-31T13:35:00Z
37,547,751
<p>The population of seattle is simply not in this database.</p> <p>If you execute:</p> <pre><code>#Largest cities of the world #defaultView:BubbleChart SELECT * WHERE { wd:Q5083 wdt:P1082 ?population. SERVICE wikibase:label { bd:serviceParam wikibase:language "en". } } </code></pre> <p>You get zero results. Alto...
3
2016-05-31T13:55:22Z
[ "python", "geolocation", "sparql" ]
R equivalent to `python -i`
37,547,362
<p>Typing <code>python -i file.py</code> at the command line runs <code>file.py</code> and then drops into the python terminal preserving the run environment.</p> <p><a href="https://docs.python.org/3/using/cmdline.html" rel="nofollow">https://docs.python.org/3/using/cmdline.html</a></p> <p>Is there an equivalent in ...
1
2016-05-31T13:37:37Z
37,547,450
<p>I may be misinterpreting what <code>python -i file.py</code> does, but try:</p> <p>From inside R, at the terminal, you can do:</p> <pre><code>source('file.R') </code></pre> <p>and it will run <code>file.R</code>, with the global environment reflecting what was done in <code>file.R</code></p> <p>If you're trying ...
2
2016-05-31T13:41:12Z
[ "python", "command-line", "interactive" ]
Python Reading From File Putting Extra Mark and Pharanthesis
37,547,466
<p>my input file content is</p> <pre><code>12sljg1', 'kf [] ffdasfsdfdsf Process finished with exit code 0 </code></pre> <p>I am reading these lines into a list and print them with code:</p> <pre><code>lines = [line.splitlines() for line in open(r'C:\Users\BerkayS\Desktop\testfile.txt', 'r')] print(lin...
0
2016-05-31T13:42:10Z
37,547,585
<p>That's how the Python output represents strings</p>
0
2016-05-31T13:47:30Z
[ "python", "string", "list", "python-3.x", "io" ]
Python Reading From File Putting Extra Mark and Pharanthesis
37,547,466
<p>my input file content is</p> <pre><code>12sljg1', 'kf [] ffdasfsdfdsf Process finished with exit code 0 </code></pre> <p>I am reading these lines into a list and print them with code:</p> <pre><code>lines = [line.splitlines() for line in open(r'C:\Users\BerkayS\Desktop\testfile.txt', 'r')] print(lin...
0
2016-05-31T13:42:10Z
37,547,664
<p>Your print statement is using default formating for this type of structure. Your structure is List So python will indicate this by adding [] to representation Additionaly to show members of list and indicate its type again its add "" to show You its string </p> <p>You must use some formating to ommit this.</p>
1
2016-05-31T13:51:26Z
[ "python", "string", "list", "python-3.x", "io" ]
storing Unicode subclasses to MySQL with Django
37,547,513
<p>I got a problem with saving Unicode chars in MySQL.</p> <pre><code> Exception Type: UnicodeEncodeError Exception Value: 'ascii' codec can't encode character u'\xed' in position 39: ordinal not in range(128) Exception Location: /home/truhlik/.virtualenvs/reality/local/lib/python2.7/site-packages/MySQ...
0
2016-05-31T13:44:14Z
37,548,327
<p>It looks like you are sending a <code>unicode</code> object to the library code where it expects to receive a <code>str</code> object. There is not much context to go by from the code you posted (try posting the entire traceback) but handling the exception by modifying the MySQLdb library is not the proper way to do...
0
2016-05-31T14:21:26Z
[ "python", "mysql", "django", "unicode" ]
storing Unicode subclasses to MySQL with Django
37,547,513
<p>I got a problem with saving Unicode chars in MySQL.</p> <pre><code> Exception Type: UnicodeEncodeError Exception Value: 'ascii' codec can't encode character u'\xed' in position 39: ordinal not in range(128) Exception Location: /home/truhlik/.virtualenvs/reality/local/lib/python2.7/site-packages/MySQ...
0
2016-05-31T13:44:14Z
37,649,929
<p>Hex <code>ed</code> is not Unicode, nor is it utf8. Perhaps you were expecting <code>í</code>? That is what latin1 encodes as <code>ed</code>.</p> <p>Where did <code>ed</code> come from? Either change it to encode things in utf8 or declare that you are using latin1, not utf8.</p> <p>Python tips: <a href="http:...
0
2016-06-06T05:11:26Z
[ "python", "mysql", "django", "unicode" ]
How to execute powershell script from python with space in the path and parameters
37,547,587
<p>Path example: <code>C:\Users\user\Some Space\dev\sensor\</code></p> <pre><code>def readSensorList(): with open('sensor.json') as json_data: data = json.load(json_data) json_data.close() return data def executeSensor(): sensorList = list() sensorListRaw = readSensorList() for sensor in s...
0
2016-05-31T13:47:45Z
37,549,724
<p>The problem is not only with Python but also with Windows. Internally Unix-like system use an <code>execve</code> system call that takes as parameters the (path to) executable file and the arguments that will be passed to the command.</p> <p>In Windows the system API has the function <code>CreateProcess</code> that...
2
2016-05-31T15:23:56Z
[ "python", "powershell", "subprocess" ]
How to execute powershell script from python with space in the path and parameters
37,547,587
<p>Path example: <code>C:\Users\user\Some Space\dev\sensor\</code></p> <pre><code>def readSensorList(): with open('sensor.json') as json_data: data = json.load(json_data) json_data.close() return data def executeSensor(): sensorList = list() sensorListRaw = readSensorList() for sensor in s...
0
2016-05-31T13:47:45Z
37,559,500
<p>I finally found, you have to put ' between space like this:</p> <pre><code>powershell -command "C:\Users\me\Desktop\test\ps' 'test.ps1" </code></pre> <p>In python:</p> <pre><code>subprocess.Popen(['powershell','-ExecutionPolicy', 'Unrestricted', '-command', path] </code></pre> <p>with path as: </p> <pre><code>C...
0
2016-06-01T04:34:00Z
[ "python", "powershell", "subprocess" ]
Is there an fmod in theano?
37,547,682
<p>I am trying to work with images in the HSV colorspace. Since the hue channel is cyclic I wanted to have it normalized between 0 and 1. I plan on using a linear activation on the output layer. Is there a way to add another layer which clamps the output in a cyclic way. Such as 1.02 -> 0.02?</p>
0
2016-05-31T13:52:20Z
37,547,903
<p>You can just add an extra activation (not another layer) to your linear activation</p> <pre><code>linear_activation = ..... # your code to calculate linear activation cyclic_linear_activation = theano.tensor.switch(linear_activation &gt; 1.0, linear_activation % 1.0,...
1
2016-05-31T14:02:00Z
[ "python", "theano" ]
Pandas - Truncate dataframe on a time gap
37,547,703
<p>I want to keep the last few rows, but such that once there is a time gap above 100ms, cut off the rest of the dataframe. For example:</p> <p>Input:</p> <pre><code> Time X 0 12:30:00.00 A 1 12:30:00.100 B 2 12:30:00.202 C 3 12:30.00.300 D </code></pre> <p>Output</p> <pre><code> Time ...
1
2016-05-31T13:53:08Z
37,547,857
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.diff.html" rel="nofollow"><code>diff</code></a> comparing with <code>Timedelta</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_timedelta.html" rel="nofollow"><code>to_timedelta</code></a>, then...
2
2016-05-31T13:59:51Z
[ "python", "pandas", "dataframe" ]
Printing wrong if statement
37,547,712
<p>I have this data in a CSV</p> <pre><code>34512340,0 12395675,2 56756777,1 </code></pre> <p>My code below is checking what the stock level of each product is. The product is the eight digit number in the csv, and the number after the comma is the amount of available stock.</p> <p>If the stock level is above 0, all...
0
2016-05-31T13:53:21Z
37,547,749
<p>A value of <code>0</code> already matches your first condition <code>stocklevel &lt;= 5</code> so your later condition <code>&lt; 1</code> is never reached.</p> <p>Reorder your conditions. Start with the most strict condition, then relax them.</p> <pre><code> if stocklevel &lt; 1: print(...
3
2016-05-31T13:55:17Z
[ "python", "csv" ]
Way to mask functions on Python Object
37,547,800
<p>I have a class that inherit from OrderedDict, but I don't know if this is the right way to accomplish what I need. </p> <p>I would like the class to have the duel method of the javascript '.' notation like <code>obj.&lt;property&gt;</code> and I would also like the users to be able to access the class properties l...
0
2016-05-31T13:57:35Z
37,549,228
<p>If all you want is <code>x['a']</code> to work the same way as <code>x.a</code> without any other functionality of dictionaries, then don't inherit from <code>dict</code> or <code>OrderedDict</code>, instead just forward key/indice operations (<a href="https://docs.python.org/3/reference/datamodel.html#object.__geti...
3
2016-05-31T15:01:28Z
[ "python", "python-2.7", "python-3.x" ]
AttributeError: 'numpy.ndarray' object has no attribute 'lower' fitting logistic model data
37,547,914
<p>I am running this code:</p> <pre><code>from sklearn import cross_validation import numpy as np import sys import pandas as pd import matplotlib.pyplot as plt from sklearn import datasets, svm, metrics digits = datasets.load_digits() X_train, X_test, y_train, y_test = cross_validation.train_test_split( digits.data...
2
2016-05-31T14:02:24Z
37,548,078
<p>You shouldn't pass <code>X_train</code> and <code>y_train</code> to <code>LogisticRegression</code> constructor. You need just</p> <pre><code>... clf = linear_model.LogisticRegression() clf.fit(X_train, y_train) </code></pre>
1
2016-05-31T14:09:39Z
[ "python", "numpy", "scikit-learn" ]
Read only the updated part of a csv file in Python
37,547,917
<p>I have a csv file in which I append new results every 10 seconds. Every so (specified from a user) I read this csv and make a JSON file. I don't want to convert the whole csv into a JSON every time but only the last part that has been updated. So, I imagine that I will keep the last line every time, then I will star...
0
2016-05-31T14:02:27Z
37,548,174
<p>I would suggest to use another protocol to get your data shuffled from your producer to your consumer, for example a socket or a pipe. The approach pointed to by Lutz also works of course, but it relies on using a tool provided by the OS (tail).</p>
1
2016-05-31T14:14:06Z
[ "python", "json", "csv" ]
What is the best way to write two similiar ListView or render to similar lists in different templates in django?
37,547,923
<p>I want to show a user the whole list of cats on one page and the list of cats that belongs to that user on another page. These two lists are almost identical except for one of them is filtered by <code>self.request.user</code>. Firstly, I wrote two different ListView but their querysets are practically the same. I d...
0
2016-05-31T14:02:41Z
37,549,489
<p>I think you can do this in some ways, I will try to give some basic ways to implement this.</p> <p>I can see in your <code>get_context_data</code> method that you're filtering by user always and sending two list of cats to the template, I don't think that's a good idea.</p> <p>You could do this:</p> <p>Add a <cod...
3
2016-05-31T15:13:15Z
[ "python", "django" ]
How to import class from python module (boost.python)?
37,547,936
<p>I have a python function:</p> <pre><code>def log(text): print text </code></pre> <p>saved in <code>Callbacks.py</code> file. Now I want to import it to c++ function and execute. This works fine:</p> <pre><code>py_fun = import("Callbacks"); py_fun.attr("log")(text); </code></pre> <p>But I would like to make <...
0
2016-05-31T14:03:22Z
37,549,095
<p>Exactly the way you'd think:</p> <pre><code>py::object mod = py::import("Callbacks"); py::object logger = mod.attr("Logger")(); </code></pre>
1
2016-05-31T14:55:50Z
[ "python", "c++", "boost", "boost-python" ]
Python: pass to subprocess a temporary generated file not as the last argument
37,547,975
<p>how to use subprocess if my temp-file argument is in the middle of the command? For example a terminal command looks like this:</p> <pre><code>program subprogram -a -b tmpFILE otherFILE </code></pre> <p>I tried variations of this:</p> <pre><code>from subprocess import Popen, PIPE from tempfile import SpooledTempo...
0
2016-05-31T14:04:49Z
37,548,531
<p>Is there a reason to use <code>SpooledTemporaryFile</code> instead of other types of temp file? If not, I recommend using <code>NamedTemporaryFile</code> as you can retrieve the name from it. I have tried to retrieve the name from <code>SpooledTemporaryFile</code> and got <code>'&lt;fdopen&gt;'</code> which does not...
1
2016-05-31T14:31:02Z
[ "python", "subprocess", "command-line-arguments", "temporary-files" ]
CKAN - choroplethmap
37,547,982
<p>I have correctly installed CKAN 2.5 version with some plugins and it is running in a production server. Now I wanted to add <a href="https://github.com/ckan/ckanext-mapviews" rel="nofollow">ckanext-mapviews'</a> extension to configure regular choropleth maps to CKAN. </p> <p>I have followed the instructions as it i...
0
2016-05-31T14:05:05Z
37,596,642
<p>I am answering myself about the problem I had found explaning some kind of a workaround for the Choropleth Map:</p> <ul> <li>Column names in the spreadheet can not have "special chars" (accents or some other char).</li> <li>I only get working the map width a XLS (not CSV) file.</li> </ul> <p>I hope it should be us...
0
2016-06-02T15:52:04Z
[ "python", "ckan", "opendata" ]
Django command that opens a twisted socket client leaves idle database connections
37,548,136
<p>I'm using twisted to connect to a socket server and I am running twisted by using a django command:</p> <pre><code>#!/usr/bin/env python # -*- coding: utf-8 -*- import json from twisted.internet import reactor, task from twisted.internet.protocol import ReconnectingClientFactory from twisted.protocols.basic impor...
0
2016-05-31T14:12:28Z
37,548,731
<p>There seems to be no code that creates connection to postgres in the code you posted above. The problem lies elsewhere, maybe your server code which the code above connects to does not close the database connection when the client disconnects.</p> <p>EDIT: If you are using Django ORM calls from within a non-WSGI ap...
1
2016-05-31T14:40:28Z
[ "python", "django", "postgresql", "twisted" ]
How do I construct a Django form that has a ModelChoiceField?
37,548,503
<p>I'm trying to write a test for my form which uses a custom ModelChoiceField:</p> <pre><code>from django.forms import ModelChoiceField class CycleModelChoiceField(ModelChoiceField): def label_from_instance(self, cycle): return str(cycle.begin_date) </code></pre> <p>Whatever the user selects in this fiel...
3
2016-05-31T14:29:58Z
37,550,807
<p>As pointed out by DanielRoseman, the answer is to use the id of the instance.</p> <p>So the correct way to construct a form with a ModelChoiceField is as follows:</p> <pre><code>my_instance = MyModelName.objects.get(whatever instance you need) form_data = {'my_regular_choice_field': '0', 'my_model_choice_field': m...
0
2016-05-31T16:14:08Z
[ "python", "django", "forms" ]
How do I construct a Django form that has a ModelChoiceField?
37,548,503
<p>I'm trying to write a test for my form which uses a custom ModelChoiceField:</p> <pre><code>from django.forms import ModelChoiceField class CycleModelChoiceField(ModelChoiceField): def label_from_instance(self, cycle): return str(cycle.begin_date) </code></pre> <p>Whatever the user selects in this fiel...
3
2016-05-31T14:29:58Z
37,636,585
<pre><code>self.client.login(username='user', password='1234') response = self.client.get(reverse('my_form'), follow=True) cyc = list(CycleDate.objects.all())[0] form_data = {'type_of_input': '0', 'cycle': cyc,'usage_type': 'E',} form = EnergyUsageForm(data=form_data, user=response.context['user']) </code></pre> <p>es...
1
2016-06-05T01:27:48Z
[ "python", "django", "forms" ]
Using regex in python to return capitalized words between a specific word
37,548,652
<p>I am new to using regex.</p> <p>I have a string in the form </p> <pre><code> Waco, Texas Unit Dose 13 and SECTION 011100 SUMMARY OF WORK INDEX PAGE PART 1. - GENERAL 1 1.1. RELATED DOCUMENTS 1 1.2. PROJECT DESCRIPTION 1 1.3. ...
1
2016-05-31T14:37:08Z
37,548,833
<p>You don't even need to use regex, just use the <code>split</code> function for strings. If s is the name of your string, it would be:</p> <pre><code>s.split('PART') </code></pre> <p>This will include the text before the first PART, so don't use the first element of the list:</p> <pre><code>texts_between_parts = s...
4
2016-05-31T14:44:23Z
[ "python", "regex", "string" ]
Using regex in python to return capitalized words between a specific word
37,548,652
<p>I am new to using regex.</p> <p>I have a string in the form </p> <pre><code> Waco, Texas Unit Dose 13 and SECTION 011100 SUMMARY OF WORK INDEX PAGE PART 1. - GENERAL 1 1.1. RELATED DOCUMENTS 1 1.2. PROJECT DESCRIPTION 1 1.3. ...
1
2016-05-31T14:37:08Z
37,550,351
<p>I would forget grabbing everything between Part 1 and Part 2,etc. I would parse each line with the following regex and use Group 1 to determine the grouping of the headings.</p> <pre><code>^(\d)(\.|\d)+\s+([^a-z]+?)\s+\d$ </code></pre> <p>Group 1 is the Part Number/Section</p> <p>Group 2 is the Sub Section</p> ...
1
2016-05-31T15:52:24Z
[ "python", "regex", "string" ]
Using regex in python to return capitalized words between a specific word
37,548,652
<p>I am new to using regex.</p> <p>I have a string in the form </p> <pre><code> Waco, Texas Unit Dose 13 and SECTION 011100 SUMMARY OF WORK INDEX PAGE PART 1. - GENERAL 1 1.1. RELATED DOCUMENTS 1 1.2. PROJECT DESCRIPTION 1 1.3. ...
1
2016-05-31T14:37:08Z
37,551,229
<pre><code>import re p = re.compile('^(\d)(\.|\d)+\s+([^a-z]+?)\s+\d$') m = p.match( '1.4. ARCHITECT/ENGINEER 2' ) if m: print('Section: ', m.group(1)) print('Heading: ', m.group(3)) else: print('No match') # Output # Section: 1 # Heading: ARCHITECT/ENGINEER </code></pre>
0
2016-05-31T16:37:34Z
[ "python", "regex", "string" ]
numpy x**L operator gives NaN if x is a vector of negative floats
37,548,674
<p>I have encountered a strange behavior of python numpy; if I consider the following code:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt if __name__ == '__main__': x=np.linspace(-1.0, 0.0, 5) L=1.65 y=x**L plt.plot(x,y) plt.show() </code></pre> <p>The vector <code>y=[nan,nan,n...
2
2016-05-31T14:37:55Z
37,548,965
<p>You cannot raise negative real numbers to fractional powers</p> <p>In <code>python 2.7</code> try doing <code>(-1)**1.65</code> and see the python error</p> <p>As @Blckknght mention in the comments, given <code>(-1)**1.65</code>, <code>python 3</code> will automatically return a complex number, instead of raising ...
3
2016-05-31T14:50:05Z
[ "python", "numpy" ]
How to make matplotlib/pandas bar chart look like hist chart?
37,548,732
<h1>Plotting Differences between <code>bar</code> and <code>hist</code></h1> <p>Given some data in a <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.html#pandas-series" rel="nofollow"><code>pandas.Series</code></a> , <code>rv</code>, there is a difference between </p> <ol> <li><p>Calling ...
1
2016-05-31T14:40:32Z
37,548,733
<h1>Bar plotting differences</h1> <p>Obtaining a <code>bar</code> plot that looks like the <code>hist</code> plot requires some manipulating of default behavior for <code>bar</code>. </p> <ol> <li>Force <code>bar</code> to use actual x data for plotting range by passing both x (<code>hist.index</code>) and y (<code>...
3
2016-05-31T14:40:32Z
[ "python", "numpy", "pandas", "matplotlib", "plot" ]
Edit table in PyQt QAbstractTableModel without deletion of content
37,548,782
<p><strong>What I have done so far:</strong></p> <p>I'm implementing an custom <code>QAbstractTableModel</code> (used in a <code>QTableView</code>-Widget) that contains editable cells. The properties of these cells are specified in my <code>flags()</code> method that looks like this:</p> <pre><code>def flags(self, in...
1
2016-05-31T14:42:30Z
37,552,321
<p>You have a few options.</p> <p>No data is appearing in the cells during editing because you likely haven't set any data on the <a href="http://pyqt.sourceforge.net/Docs/PyQt4/qt.html#ItemDataRole-enum" rel="nofollow"><code>Qt.EditRole</code></a> for each item in your model. The <code>QTableWidget</code>'s do this ...
1
2016-05-31T17:40:54Z
[ "python", "pyqt4", "qabstracttablemodel" ]
Can't run python script from R in aws and Rstudio
37,548,933
<p>I am trying to call python script to call parallel api calls which is wrapped in function. However, I am not able to execute python script from Rstudio in local computer or R in aws.</p> <p>Following is my code for python.</p> <pre><code>import sys from numpy.random import randint if len(sys.argv)==5: ci = i...
0
2016-05-31T14:48:34Z
37,558,624
<p>My assumption is right, AWS EC2 was calling default python, not calling anaconda python. So I had to install module in default python. </p> <p>installing module in default is fist install apt-get install</p> <pre><code>sudo apt-get install pip </code></pre> <p>then install all modules using sudo pip install.</p>
0
2016-06-01T02:52:52Z
[ "python", "amazon-web-services" ]
Plotting pandas dataframe with string labels
37,548,944
<p>I have a pandas dataframe that has several fields. The ones of importance are:</p> <pre><code>In[191]: tasks[['start','end','appId','index']] Out[189]: start end appId index 2576 1464262540102.000 1464262541204.000 application_1464258584784_0012 1 2577 14...
0
2016-05-31T14:48:51Z
37,550,345
<p>The problem is that you are assigning the label each time you plot the graph in the for loop using the <code>label=</code> argument. Try removing it and giving <code>p2.lengend()</code> a list of strings as an argument that represent the labels you want to show.</p> <pre><code>p2.legend(['label1', 'label2']) </code...
1
2016-05-31T15:52:15Z
[ "python", "pandas", "matplotlib" ]
Use a c exe as Nativehost application instead python in chrom NativeHost messaging
37,548,962
<p>I took <a href="https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/docs/examples/api/nativeMessaging/" rel="nofollow">this</a> chrome app example for NativeMessaging, it allows a python program to run and talk back to app. i converted it to extension and am trying to replace the python ...
0
2016-05-31T14:49:55Z
37,549,414
<p>Chrome doesn't care (and cannot know) what's on the other side as long as the program answers in expected format (see <a href="https://developer.chrome.com/extensions/nativeMessaging#native-messaging-host-protocol" rel="nofollow">Native Messaging Protocol</a>). Which does not seem to be the case here from a brief gl...
2
2016-05-31T15:09:31Z
[ "python", "c", "google-chrome-extension", "file-handling" ]
Selecting lines of a file specified by a list of strings
37,549,143
<p>I have a python list of some strings. I also have a text file (say X) where each line has a word token and some floats after that each separated by a space. # of floats in every line is constant.</p> <p>My objective is to take only the lines corresponding to the strings in the list and save it as a text file. And i...
0
2016-05-31T14:57:44Z
37,561,681
<p>You could use grep if you want to find in one file.</p> <pre><code>### let's create a file find_strings.py import os list = ['the','in','red'] for l in list : os.system('grep ' + str(l) + ' fileX.txt') ### after saving the file, run the below command in the console . ### $ python find_strings.py &gt; list_fo...
0
2016-06-01T07:06:49Z
[ "python", "string", "list", "file" ]
How to create a list of many characters in python?
37,549,265
<p>I would like to create a list of size 100 in python that contains the character <code>x_i</code> for <code>i=1...100</code>. How to do this in Python?</p> <pre><code>['x_1', 'x_2', ..., 'x_100'] </code></pre> <p>If it was a list of 10 character I would write it by hand, but a hundred elements?</p>
-1
2016-05-31T15:03:13Z
37,549,388
<p>you can use list comprehension</p> <pre><code>["x_{}".format(i) for i in range(1, 101)] </code></pre>
3
2016-05-31T15:08:15Z
[ "python", "loops" ]
How to create a list of many characters in python?
37,549,265
<p>I would like to create a list of size 100 in python that contains the character <code>x_i</code> for <code>i=1...100</code>. How to do this in Python?</p> <pre><code>['x_1', 'x_2', ..., 'x_100'] </code></pre> <p>If it was a list of 10 character I would write it by hand, but a hundred elements?</p>
-1
2016-05-31T15:03:13Z
37,549,418
<p>It looks like you may be a beginner so here is a simple example:</p> <pre><code>mylist = [] for i in range(1, 101): mylist.append('x_'+str(i)) print(mylist) </code></pre>
1
2016-05-31T15:09:46Z
[ "python", "loops" ]
How to create a list of many characters in python?
37,549,265
<p>I would like to create a list of size 100 in python that contains the character <code>x_i</code> for <code>i=1...100</code>. How to do this in Python?</p> <pre><code>['x_1', 'x_2', ..., 'x_100'] </code></pre> <p>If it was a list of 10 character I would write it by hand, but a hundred elements?</p>
-1
2016-05-31T15:03:13Z
37,549,422
<pre><code>my_list = [] for i in xrange(1, 101): #use range if python 3+ my_list.append('x_{0}'.format(i)) print my_list </code></pre> <p>This is easier to understand if you're just getting started. Xrange starts at 1 and goes to 101 (exclusive). </p>
3
2016-05-31T15:09:50Z
[ "python", "loops" ]
How to create a list of many characters in python?
37,549,265
<p>I would like to create a list of size 100 in python that contains the character <code>x_i</code> for <code>i=1...100</code>. How to do this in Python?</p> <pre><code>['x_1', 'x_2', ..., 'x_100'] </code></pre> <p>If it was a list of 10 character I would write it by hand, but a hundred elements?</p>
-1
2016-05-31T15:03:13Z
37,549,551
<pre><code>["x_"+str(i) for i in range(1,101)] </code></pre> <p>Using list comprehension. </p>
0
2016-05-31T15:15:48Z
[ "python", "loops" ]
python combine each pair of lines: making script more efficient
37,549,302
<p>I'm sorry for how basic this question is. </p> <p>The aim: This is my output from a software program:</p> <pre><code>1 590 SC 1.000 LEU2_YEAST 100% 1 590 EC 1.000 LEU2_ECOLI 100% 2 467 SC 1.000 FADH_YEAST 100% 2 467 EC 1.000 ADH3_ECOLI 100% 3 463 SC 1.000 6PG1_YEAST 100% 3 463 SC 0...
1
2016-05-31T15:05:01Z
37,549,563
<p>A possible improvement is to change the <code>if line[0] not in Dict1.keys()</code> to <code>if line[0] not in Dict1</code>, since <code>not in Dict1.keys()</code> is a O(n) operation, whereas <code>not in Dict</code> is about O(1). </p> <p>I'm not sure about the real performance gain. You should use <a href="http...
1
2016-05-31T15:16:15Z
[ "python", "performance", "parsing" ]
python combine each pair of lines: making script more efficient
37,549,302
<p>I'm sorry for how basic this question is. </p> <p>The aim: This is my output from a software program:</p> <pre><code>1 590 SC 1.000 LEU2_YEAST 100% 1 590 EC 1.000 LEU2_ECOLI 100% 2 467 SC 1.000 FADH_YEAST 100% 2 467 EC 1.000 ADH3_ECOLI 100% 3 463 SC 1.000 6PG1_YEAST 100% 3 463 SC 0...
1
2016-05-31T15:05:01Z
37,550,170
<p>If your file is sorted by the numbers in the first line, you can use <a href="https://docs.python.org/3/library/itertools.html#itertools.groupby" rel="nofollow"><code>itertools.groupby</code></a>:</p> <pre><code>from itertools import groupby import operator with open(sys.argv[1]) as infile: # split lines and g...
1
2016-05-31T15:44:12Z
[ "python", "performance", "parsing" ]
How to check for words in a string even if the order is different - PYTHON
37,549,426
<p>I am trying to find make as many words with e.g. 'workbook' So the results should be like: work, workbook, book, bookwork, bow, row etc. </p> <p>This is one method I tried, but this won't find words that are spelled in different order. (e.g. it won't append 'bow' even though you could rearrange letters within 'work...
1
2016-05-31T15:09:59Z
37,549,629
<p>You additionally need to test that for each letter in the dictionary word, it does not appear more times in the dictionary word than it does in <code>"workbook"</code>. You could do this for example using the method <code>count()</code> of <code>str</code>.</p> <p>Of course there are other approaches that in the en...
1
2016-05-31T15:19:06Z
[ "python", "string", "dictionary", "set", "anagram" ]
How to check for words in a string even if the order is different - PYTHON
37,549,426
<p>I am trying to find make as many words with e.g. 'workbook' So the results should be like: work, workbook, book, bookwork, bow, row etc. </p> <p>This is one method I tried, but this won't find words that are spelled in different order. (e.g. it won't append 'bow' even though you could rearrange letters within 'work...
1
2016-05-31T15:09:59Z
37,549,785
<p>First generate all the potential anagrams by calculating all the word permutations and iterating over all the possible anagram lengths. Then filter <code>potential_anagrams</code> according to your <code>words</code> file <code>f</code>.</p> <pre><code>import itertools def compute_anagrams(word) n = len(word) ...
2
2016-05-31T15:27:16Z
[ "python", "string", "dictionary", "set", "anagram" ]
Writing to a text file error - Must be str, not list
37,549,498
<p>I have been having problems with some code I am writing. Basically, when I run the code I enter an 8 digit number and it should scan the CSV file to see if the number is inside the file. If it is, the row should be written to the text file. However, when I run it and I enter a number, I get this:</p> <pre><code>Typ...
1
2016-05-31T15:13:30Z
37,549,630
<p>The <code>write</code> method of a Python text file takes a string (<code>str</code>), not a list.</p> <p>If you want to duplicate matching rows from the input file to the output, as your description implies, I think you want to either replace your </p> <pre><code>receipt.write(cells) </code></pre> <p>with </p> ...
1
2016-05-31T15:19:12Z
[ "python", "csv", "text", "writing" ]
Writing to a text file error - Must be str, not list
37,549,498
<p>I have been having problems with some code I am writing. Basically, when I run the code I enter an 8 digit number and it should scan the CSV file to see if the number is inside the file. If it is, the row should be written to the text file. However, when I run it and I enter a number, I get this:</p> <pre><code>Typ...
1
2016-05-31T15:13:30Z
37,549,678
<p><code>write</code> call in <code>receipt.write(cells)</code> expects a string, whereas you give it a list.</p> <p>You can use <a href="https://docs.python.org/2/library/stdtypes.html#str.join" rel="nofollow">join</a> if you want everything to be concatenated (in this example, the values would be separated by dashes...
1
2016-05-31T15:21:22Z
[ "python", "csv", "text", "writing" ]
Create a POST service in app engine with python
37,549,515
<p>I am very new to app engine and python too so this might sound like a very basic question. I want to create a RESTful service which handles POST requests(using Python, app engine) </p> <p>For Example:</p> <pre><code>www.myproject.appspot.com - is my URL </code></pre> <p>and if I do a simple GET call to this(from ...
1
2016-05-31T15:14:23Z
37,549,681
<p>Write a method that will handle the POST method and set proper content type:</p> <p><a href="https://webapp-improved.appspot.com/guide/handlers.html#http-methods-translated-to-class-methods" rel="nofollow">https://webapp-improved.appspot.com/guide/handlers.html#http-methods-translated-to-class-methods</a></p> <p>I...
1
2016-05-31T15:21:37Z
[ "python", "google-app-engine" ]
Create a POST service in app engine with python
37,549,515
<p>I am very new to app engine and python too so this might sound like a very basic question. I want to create a RESTful service which handles POST requests(using Python, app engine) </p> <p>For Example:</p> <pre><code>www.myproject.appspot.com - is my URL </code></pre> <p>and if I do a simple GET call to this(from ...
1
2016-05-31T15:14:23Z
37,550,801
<p>Here's the way to get the <a href="http://webapp-improved.appspot.com/guide/request.html?highlight=url#post-data" rel="nofollow">POST data</a> from the request into the response:</p> <pre><code>class MainHandler(webapp2.RequestHandler): def post(self): name = self.request.POST['myName'] self.res...
0
2016-05-31T16:14:01Z
[ "python", "google-app-engine" ]
Extracting multiple fields from json output
37,549,581
<p>Hi folks im new to asking questions in stack but I want to know what is the process in order to remove the 'name' value from the json output below i know how to get the individual names through indexing<code>name = [groups['groups'][0]['name'] for groups in result]</code> but how do i get both names </p> <pre><code...
0
2016-05-31T15:16:53Z
37,550,930
<p>You should be able to do it with a <a href="https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions" rel="nofollow">list-comprehension</a>:</p> <pre><code>json_output = [ [ { "internal": "0", "flags": "0", "groupid": "110", "name": "- GSOC - Systems" }, { ...
1
2016-05-31T16:20:36Z
[ "python", "json", "list-comprehension" ]
Displaying all Many to Many relationships in one template
37,549,628
<p>I am writing a todo list application for myself as well as a way to better familiarize myself with Django and all it's painful intricacies. </p> <p>I am trying to use a many-to-many relationship between List models and Item models such that an item can be present in one or more lists at a time. </p> <p>Here is the...
1
2016-05-31T15:19:04Z
37,550,259
<p>Your <code>getLists</code> function returns a dict, mapping list names to lists. So when you iterate over <code>lists</code> in the template, you're iterating over that dict: and iterating over a list just gives the key, which here is the list name.</p> <p>If you want to test iterating over many-to-many items, you ...
0
2016-05-31T15:48:47Z
[ "python", "html", "django", "django-templates", "many-to-many" ]
Dictionary Containing list data, filter based on value in list
37,549,689
<p>I have test data which is gathered based on multiple inputs, and results in a single output. I'm currently storing this data in a dictionary whose keys are my parameter/ results labels, and whose values are the test conditions and results. I would like to be able to filter the data so I can generate plots based on...
0
2016-05-31T15:22:07Z
37,549,897
<p>Consider using the pandas module for this type of work.</p> <pre><code>import pandas as pd df = pd.DataFrame(data) df = df[df["b"] &gt;= 20] print(df) </code></pre> <p>It appears like this will give you what you want. You are using the dictionary key to represent the column name and the values are just rows in a ...
3
2016-05-31T15:32:09Z
[ "python", "list", "dictionary", "dictionary-comprehension" ]
Dictionary Containing list data, filter based on value in list
37,549,689
<p>I have test data which is gathered based on multiple inputs, and results in a single output. I'm currently storing this data in a dictionary whose keys are my parameter/ results labels, and whose values are the test conditions and results. I would like to be able to filter the data so I can generate plots based on...
0
2016-05-31T15:22:07Z
37,549,943
<p>Are all of the dictionary value lists in matching orders? If so, you could just look at whichever list you want to filter by, say <code>'b'</code> in this case, find the values you want, and then either use those indices or the same slice on the other values in the dictionary.</p> <p>For example:</p> <pre><code>m...
0
2016-05-31T15:34:03Z
[ "python", "list", "dictionary", "dictionary-comprehension" ]
Dictionary Containing list data, filter based on value in list
37,549,689
<p>I have test data which is gathered based on multiple inputs, and results in a single output. I'm currently storing this data in a dictionary whose keys are my parameter/ results labels, and whose values are the test conditions and results. I would like to be able to filter the data so I can generate plots based on...
0
2016-05-31T15:22:07Z
37,549,948
<p>you can change this into a method which would give it more flexibility. Your current logic means that dataset a and c are neglected because there are no values greater than or equal to 20:</p> <pre><code>data = {'a': [0, 1, 2, 0, 1, 2], 'b': [10, 10, 10, 20, 20, 20], 'c': [1.3, 1.9, 2.3, 2.3, 2.9, 3.4]} filter_vals...
0
2016-05-31T15:34:12Z
[ "python", "list", "dictionary", "dictionary-comprehension" ]
Dictionary Containing list data, filter based on value in list
37,549,689
<p>I have test data which is gathered based on multiple inputs, and results in a single output. I'm currently storing this data in a dictionary whose keys are my parameter/ results labels, and whose values are the test conditions and results. I would like to be able to filter the data so I can generate plots based on...
0
2016-05-31T15:22:07Z
37,550,093
<p>use this:</p> <pre><code>k:[v[i] for i,x in enumerate(v) if data['b'][i] &gt;= 20] for k,v in data.items()} </code></pre> <p><strong>Desired Result:</strong></p> <pre><code>{'a': [0, 1, 2], 'c': [2.3, 2.9, 3.4], 'b': [20, 20, 20]} </code></pre>
2
2016-05-31T15:40:30Z
[ "python", "list", "dictionary", "dictionary-comprehension" ]
Dictionary Containing list data, filter based on value in list
37,549,689
<p>I have test data which is gathered based on multiple inputs, and results in a single output. I'm currently storing this data in a dictionary whose keys are my parameter/ results labels, and whose values are the test conditions and results. I would like to be able to filter the data so I can generate plots based on...
0
2016-05-31T15:22:07Z
37,550,522
<p><strong>I agree with the pandas approach above.</strong> </p> <p>If for some reason you hate pandas or are an old school computer scientist, tuples are a good way to tore relational data. In your example, the a, b, and c lists are columns rather than rows. For tuples, you would want to store the rows as:</p> <p...
0
2016-05-31T16:01:16Z
[ "python", "list", "dictionary", "dictionary-comprehension" ]
Is it possible to bulk-add docstrings to all the functions in PyCharm?
37,549,741
<p>I have a python project that many of the functions and classes missing docstrings. I know that PyCharm can automatically add docstrings by the <em>Insert documentation string stub</em> command using intention action. However, for large number of methods and functions, it is tedious. Is there a method to bulk add doc...
2
2016-05-31T15:24:59Z
37,592,814
<p>Finally, I found an answer, or may be a workaround</p> <p>In pyCharm, </p> <ol> <li>goto File\Settings\Code Style\Inspections then put a tick in front of 'Missing or empty docstring' Then press OK button.</li> <li>goto Code\Inspect Code\ then select Custom scope>>Open Files</li> <li>You will find a panel below wit...
2
2016-06-02T13:08:54Z
[ "python", "pycharm", "docstring" ]
Python:How do I export the output of my code to it's own text file?
37,549,754
<p>How do I export the output of my code to it's own text file? When I run my code I get a large set of data from it. How do I export this so that I can read all lines of data in it's own text file.</p>
1
2016-05-31T15:26:01Z
37,549,947
<p>You may want to take a look at <a href="https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files" rel="nofollow">file objects</a>, which would allow you to write all the data you want to a file.</p> <p>For example :</p> <pre><code>file = open('output.txt', 'w') file.write('Here is some data') ...
-1
2016-05-31T15:34:08Z
[ "python", "python-2.7", "python-3.x", "ipython" ]
Python:How do I export the output of my code to it's own text file?
37,549,754
<p>How do I export the output of my code to it's own text file? When I run my code I get a large set of data from it. How do I export this so that I can read all lines of data in it's own text file.</p>
1
2016-05-31T15:26:01Z
37,549,961
<p>Assuming you will read the results in another application, you can use <a href="https://en.wikipedia.org/wiki/Redirection_(computing)" rel="nofollow">redirections</a>, usually something like this:</p> <pre><code>./myprogram &gt;results.txt </code></pre>
2
2016-05-31T15:34:47Z
[ "python", "python-2.7", "python-3.x", "ipython" ]
Python:How do I export the output of my code to it's own text file?
37,549,754
<p>How do I export the output of my code to it's own text file? When I run my code I get a large set of data from it. How do I export this so that I can read all lines of data in it's own text file.</p>
1
2016-05-31T15:26:01Z
37,550,042
<p>You can write file in python like</p> <pre><code>with open("out.txt", "w") as f: f.write("OUTPUT") </code></pre> <p>Or you can use io redirection to redirect output to a file</p> <pre><code>$ python code.py &gt; out.txt </code></pre> <hr> <ol> <li><a href="https://docs.python.org/3/tutorial/inputoutput.html...
5
2016-05-31T15:38:01Z
[ "python", "python-2.7", "python-3.x", "ipython" ]
Python:How do I export the output of my code to it's own text file?
37,549,754
<p>How do I export the output of my code to it's own text file? When I run my code I get a large set of data from it. How do I export this so that I can read all lines of data in it's own text file.</p>
1
2016-05-31T15:26:01Z
37,550,120
<p>One way to do it is this:</p> <pre><code>import csv with open("name_of_file_to_be_created") as f: writer = csv.writer(f) for i in range(n): writer.writerow('stuff to write') # writes a single line in each iteration, e.g. assuming you are computing something inside the loop </code></pre> <p>Another...
-1
2016-05-31T15:41:31Z
[ "python", "python-2.7", "python-3.x", "ipython" ]
How can I extract two columns from a .txt file with python?
37,549,771
<p>I have done some calculation. I want to extract two columns from the data and save them in another file with python.</p> <p>This is what I've done so far: I saved the file as .txt and then wrote this script:</p> <pre><code># -*- coding: utf-8 -*- import csv f = open('file.txt') csv_f=csv.reader(f) for row in ...
0
2016-05-31T15:26:31Z
37,549,901
<pre><code>import csv f = open('file.txt') csv_f=csv.reader(f) for row in csv_f: print row.split(" ").[1:3] # to get the second and third columns f.close() </code></pre>
0
2016-05-31T15:32:20Z
[ "python", "csv" ]
How can I extract two columns from a .txt file with python?
37,549,771
<p>I have done some calculation. I want to extract two columns from the data and save them in another file with python.</p> <p>This is what I've done so far: I saved the file as .txt and then wrote this script:</p> <pre><code># -*- coding: utf-8 -*- import csv f = open('file.txt') csv_f=csv.reader(f) for row in ...
0
2016-05-31T15:26:31Z
37,549,910
<p>You have to specify the correct delimiter (default is <code>','</code>):</p> <pre><code>csv_f = csv.reader(f, delimiter='\t') # if the file is tab delimited </code></pre>
3
2016-05-31T15:32:44Z
[ "python", "csv" ]
How can I extract two columns from a .txt file with python?
37,549,771
<p>I have done some calculation. I want to extract two columns from the data and save them in another file with python.</p> <p>This is what I've done so far: I saved the file as .txt and then wrote this script:</p> <pre><code># -*- coding: utf-8 -*- import csv f = open('file.txt') csv_f=csv.reader(f) for row in ...
0
2016-05-31T15:26:31Z
37,550,418
<p>Here is a solution that doesn't require the use of the csv module</p> <pre><code>with open('test.txt', 'r') as data: #using the with keyword ensures files are closed properly for line in data.readlines(): parts = line.split(',') #change this to whatever the deliminator is print parts[0], parts[1] # parts[...
0
2016-05-31T15:56:11Z
[ "python", "csv" ]
Syntax error when importing CSV file (Python)
37,549,789
<p>I'm fairly new to Python and am using it for parsing some data. For some reason when I run:</p> <p>import numpy as np</p> <pre><code>def main(): try: sequencename, modelaccession, modelname, bitscore, e-value, -, hmmstart, hmmend, hmmlength, strandofhit, alignmentstart, alignmentend, envelopestart, en...
-2
2016-05-31T15:27:25Z
37,550,218
<p>The syntax error is occurring because you are trying to assign a value to <code>-</code> (the minus operator). By changing <code>-</code> to <code>_</code> the syntax error will be removed as python reads <code>_</code> as a placeholder. It is likely that you intended to do this but forgot to hit the shift button. A...
2
2016-05-31T15:46:26Z
[ "python", "csv", "numpy" ]
How to use 'yield' inside async function?
37,549,846
<p>I want to use generator yield and async functions. I read <a href="http://stackoverflow.com/questions/231767/what-does-the-yield-keyword-do-in-python">this topic</a>, and wrote next code:</p> <pre><code>import asyncio async def createGenerator(): mylist = range(3) for i in mylist: await asyncio.sle...
7
2016-05-31T15:30:08Z
37,550,568
<p>You can't <code>yield</code> inside coroutines. Only way is to implement <a href="https://www.python.org/dev/peps/pep-0492/#asynchronous-iterators-and-async-for" rel="nofollow">Asynchronous Iterator</a> manually using <code>__aiter__</code>/<code>__anext__</code> magic methods. In your case:</p> <pre><code>import a...
6
2016-05-31T16:03:21Z
[ "python", "yield", "python-3.5", "python-asyncio" ]
How to use 'yield' inside async function?
37,549,846
<p>I want to use generator yield and async functions. I read <a href="http://stackoverflow.com/questions/231767/what-does-the-yield-keyword-do-in-python">this topic</a>, and wrote next code:</p> <pre><code>import asyncio async def createGenerator(): mylist = range(3) for i in mylist: await asyncio.sle...
7
2016-05-31T15:30:08Z
39,557,462
<p>New Python 3.6 comes with support for asynchronous generators.</p> <p><a href="https://www.python.org/dev/peps/pep-0525/" rel="nofollow">PEP 0525</a></p> <p><a href="https://docs.python.org/3.6/whatsnew/3.6.html" rel="nofollow">What's new in Python 3.6</a></p> <p>PS: On the moment of writing Python 3.6 is still b...
1
2016-09-18T12:05:08Z
[ "python", "yield", "python-3.5", "python-asyncio" ]
How to use 'yield' inside async function?
37,549,846
<p>I want to use generator yield and async functions. I read <a href="http://stackoverflow.com/questions/231767/what-does-the-yield-keyword-do-in-python">this topic</a>, and wrote next code:</p> <pre><code>import asyncio async def createGenerator(): mylist = range(3) for i in mylist: await asyncio.sle...
7
2016-05-31T15:30:08Z
39,564,492
<p>This should work with python 3.6 (tested with 3.6.0b1):</p> <pre><code>import asyncio async def createGenerator(): mylist = range(3) for i in mylist: await asyncio.sleep(1) yield i*i async def start(): async for i in createGenerator(): print(i) loop = asyncio.get_event_loop() ...
1
2016-09-19T02:18:10Z
[ "python", "yield", "python-3.5", "python-asyncio" ]
Transform dataframe and count values in pandas
37,549,870
<p>I have a dataframe df that looks like</p> <pre><code>Date Type 2010 A 1998 A 2003 B 2003 C 2007 D 2010 D 2015 B 2015 B 2006 C 2006 C 1998 D </code></pre> <p>I need to transform it and count the occurence of each Type for each year. So my expected output is:</p> <pre><code> 1998 2003 2006 2007 2010 2...
0
2016-05-31T15:31:00Z
37,550,112
<p>You can use pivot_table and pass <code>len</code> as the aggregate function:</p> <pre><code>df.pivot_table(index="Type", columns="Date", aggfunc=len).fillna(0).astype(int) Out[152]: Date 1998 2003 2006 2007 2010 2015 Type A 1 0 0 0 1 0 B ...
3
2016-05-31T15:41:17Z
[ "python", "pandas", "pivot" ]
Transform dataframe and count values in pandas
37,549,870
<p>I have a dataframe df that looks like</p> <pre><code>Date Type 2010 A 1998 A 2003 B 2003 C 2007 D 2010 D 2015 B 2015 B 2006 C 2006 C 1998 D </code></pre> <p>I need to transform it and count the occurence of each Type for each year. So my expected output is:</p> <pre><code> 1998 2003 2006 2007 2010 2...
0
2016-05-31T15:31:00Z
37,550,452
<p>If you don't want the empty values to show up, you can also use :</p> <pre><code>df.groupby(['Date', 'Type']).size().reset_index() </code></pre> <p>Which would give :</p> <pre><code> Date Type 0 0 1998 A 1 1 1998 D 1 2 2003 B 1 3 2003 C 1 4 2006 C 2 5 2007 D 1 6 2010 A 1 7 2...
2
2016-05-31T15:57:27Z
[ "python", "pandas", "pivot" ]
Selenium is misclicking
37,549,912
<p>I'm trying to make Selenium click a button, Selenium has to scroll in order to click that button. But what happens is that when Selenium scrolls down, the button gets behind the sticky bar and Selenium clicks on the sticky bar instead of the button.</p> <p>I'm using Firefox webdriver.</p> <p>I tried the following:...
1
2016-05-31T15:32:46Z
37,550,106
<p>You could try to use a javascript scroll to element then scroll a little more with an offset eg in c#.</p> <pre><code>IJavaScriptExecutor jse = (IJavaScriptExecutor)driver; jse.ExecuteScript("arguments[0].scrollIntoView(true)", element) jse.ExecuteScript("window.scrollBy(0,50)"); </code></pre>
-1
2016-05-31T15:40:56Z
[ "python", "python-2.7", "python-3.x", "selenium", "selenium-webdriver" ]
Selenium is misclicking
37,549,912
<p>I'm trying to make Selenium click a button, Selenium has to scroll in order to click that button. But what happens is that when Selenium scrolls down, the button gets behind the sticky bar and Selenium clicks on the sticky bar instead of the button.</p> <p>I'm using Firefox webdriver.</p> <p>I tried the following:...
1
2016-05-31T15:32:46Z
37,550,113
<p>You could implement something like this:</p> <pre><code>driver = webdriver.Firefox() driver.get("http://somewebpage.example") time.sleep(5) while True: try: # Edit this to how you're currently scrolling driver.execute_script("window.scrollBy(0, 150);") button = driver.find_element(By.XP...
0
2016-05-31T15:41:17Z
[ "python", "python-2.7", "python-3.x", "selenium", "selenium-webdriver" ]
Changing the dtype for specific columns in a pandas dataframe
37,549,938
<p>I have a pandas dataframe which I have created from data stored in an xml file:</p> <p>Initially the xlm file is opened and parsed</p> <pre><code>xmlData = etree.parse(filename) trendData = xmlData.findall("//TrendData") </code></pre> <p>I created a directory which lists all the data names (which are used as colu...
2
2016-05-31T15:34:00Z
37,550,925
<p>You can explicitly replace columns in a DataFrame with the same column just with another <code>dtype</code>. Try this:</p> <pre><code>import pandas as pd data = pd.DataFrame({'date':[2000, 2001, 2002, 2003], 'type':['A', 'B', 'A', 'C']}) data['date'] = data['date'].astype('int64') </code></pre> <p>when now calling...
2
2016-05-31T16:20:22Z
[ "python", "pandas" ]
Changing the dtype for specific columns in a pandas dataframe
37,549,938
<p>I have a pandas dataframe which I have created from data stored in an xml file:</p> <p>Initially the xlm file is opened and parsed</p> <pre><code>xmlData = etree.parse(filename) trendData = xmlData.findall("//TrendData") </code></pre> <p>I created a directory which lists all the data names (which are used as colu...
2
2016-05-31T15:34:00Z
37,553,412
<p>for multiple columns you can do it this way:</p> <pre><code>cols = df.filter(like='AnalyzeParameters').columns.tolist() df[cols] = df[cols].astype(np.int64) </code></pre>
1
2016-05-31T18:47:39Z
[ "python", "pandas" ]
Python, install Pytables: ValueError: [u'path']
37,549,981
<p>I use command 'pip install tables' in powershell (Windows) to install Pytables. Yet I receive the <code>ValueError: [u'path']</code>. In red is written <code>'Command "python setup.py egg_info" failed with error code 1'</code>. I have miniconda installed.</p> <p>EDIT: the full red error message is the following:</...
0
2016-05-31T15:35:33Z
37,550,786
<p>This is a problem with not being able to correctly setup certain environment variables required for the setup using <code>vcvarsall.bat</code>. You can download a binary of <code>pytables</code> <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/#pytables" rel="nofollow">here</a> instead and do <code>pip install tab...
1
2016-05-31T16:13:20Z
[ "python", "pytables" ]
Plotting co-ordinates on python - what data type to use?
37,550,073
<p>I'm working on a task that involves isolating information from a CSV document (to be specific, the timestamp in nanoseconds and the latitude and longitude). I have managed to print these values successfully, but now I would like to plot it using matplotlib. This is my code so far:</p> <pre><code>import csv from mat...
0
2016-05-31T15:39:17Z
37,550,296
<p>When you write <code>plt.plot('lat','lon')</code>, it is trying to plot the string <code>lat</code> with a format string <code>lon</code>. This does not work and gives you the error you see. What <code>plt.plot()</code> wants as arguments are lists of latitudes and longitudes. For example,</p> <pre><code>lat = [13,...
0
2016-05-31T15:50:13Z
[ "python", "matplotlib", "coordinates" ]
Plotting co-ordinates on python - what data type to use?
37,550,073
<p>I'm working on a task that involves isolating information from a CSV document (to be specific, the timestamp in nanoseconds and the latitude and longitude). I have managed to print these values successfully, but now I would like to plot it using matplotlib. This is my code so far:</p> <pre><code>import csv from mat...
0
2016-05-31T15:39:17Z
37,550,315
<p><a href="http://matplotlib.org/api/pyplot_api.html" rel="nofollow"><code>plt.plot()</code></a> takes a list or array of x and y pairs, not strings as you are passing with <code>plt.plot('lat', 'lon')</code>. The ValueError you are getting is due to this. Instead, put your values for latitude and longitude into a lis...
0
2016-05-31T15:50:54Z
[ "python", "matplotlib", "coordinates" ]
Adding a new column to the table in a database using sqlalchemy, pyodbc
37,550,248
<pre><code>cnx=sqlalchemy.create_engine("mssql+pyodbc://Omnius:MainBrain1@172.31.163.135:1433/Basis?driver=/opt/microsoft/sqlncli/lib64/libsqlncli-11.0.so.1790.0") cnx1 = pyodbc.connect('driver=/opt/microsoft/sqlncli/lib64/libsqlncli-11.0.so.1790.0;server=SRVWUDEN0835;database=Basis;uid=Omnius; pwd=MainBrain1') sqlquer...
2
2016-05-31T15:47:52Z
37,553,173
<p>you have incorrectly built your <code>alter table ... add column ...</code> SQL.</p> <p>It should look like as follows (for single column):</p> <pre><code>ALTER TABLE table_name ADD COLUMN column_name data_type(precision); </code></pre> <p>or for multiple columns:</p> <pre><code>ALTER TABLE table_name ADD COLUMN...
2
2016-05-31T18:33:30Z
[ "python", "pandas", "sqlalchemy", "pyodbc" ]
Using Django numeric variable in css
37,550,276
<p>I'm trying to get a bootstrap progress bar to work, but I'm running into a problem. I want to get the progress bar width from a Django variable, I use the templates language for this. The problem is, HTML changes the float variable (i.e 32.54) to a string (i.e 32,54). I'm not sure why this happens (my guess is encod...
0
2016-05-31T15:49:32Z
37,550,447
<p>Django formats numbers according to your localization settings. You can turn localization off by using:</p> <pre><code>{% load l10n %} {% localize off %} {{ foo.rendimiento }} {% endlocalize %} </code></pre> <p>You can also unlocalize one single value:</p> <pre><code>{% load l10n %} {{foo.rendimiento|unlo...
1
2016-05-31T15:57:22Z
[ "python", "html", "css", "django", "twitter-bootstrap" ]
How to change the default selected option in a Django ChoiceField?
37,550,332
<p>I am trying to get a form with a choice field in Django. My form code looks like this:</p> <pre><code>UNIVERSITIES = ( ('North South University', 'North South University'), ('BRAC University', 'BRAC University'), ) class SearchForm(forms.Form): """ Form used to search for a professor. """ p...
0
2016-05-31T15:51:38Z
37,550,700
<p>Try this:</p> <pre><code>university = forms.TypedChoiceField( label="Select your university", choices=UNIVERSITIES, empty_value="--- youre empty value here ---", ) </code></pre>
2
2016-05-31T16:08:47Z
[ "python", "django", "django-forms" ]
How to change the default selected option in a Django ChoiceField?
37,550,332
<p>I am trying to get a form with a choice field in Django. My form code looks like this:</p> <pre><code>UNIVERSITIES = ( ('North South University', 'North South University'), ('BRAC University', 'BRAC University'), ) class SearchForm(forms.Form): """ Form used to search for a professor. """ p...
0
2016-05-31T15:51:38Z
37,550,718
<p>You can do something like this:</p> <pre><code>UNIVERSITIES = ( ( None, ''), ('North South University', 'North South University'), ('BRAC University', 'BRAC University'), ) </code></pre> <p>Since the value will be <code>None</code> by default the user will be required to select one of the options. If y...
2
2016-05-31T16:09:35Z
[ "python", "django", "django-forms" ]