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 create a dictionary with multiple values inside another dictionary in python
39,923,198
<p>I want to simulate a graph using dictionaries in Python.</p> <pre><code>G = {'a':{'b':3, 'c':4}, 'b':{'a':3, 'c':5}, 'c':{'a':4,'b':5}, } </code></pre> <p>G is a dictionary where each value is a dictionary which represents adjacent nodes with its weight.</p> <p>I have the following code:</p> <pre><...
2
2016-10-07T17:51:28Z
39,923,251
<p>You overwrite the "inner" dictionary in each iteration of the loop with an empty dictionary. You should do so only if it's missing:</p> <pre><code>if not graph[list_nodes[i]]: # Here! graph[list_nodes[i]] = {} graph[list_nodes[i]][list_adjacent_nodes[i][j]] = weight </code></pre>
2
2016-10-07T17:54:48Z
[ "python", "dictionary" ]
Variable scope in case of an exception in python
39,923,315
<pre><code>while True: try: 2/0 except Exception as e: break print e </code></pre> <p>Gives: integer division or modulo by zero</p> <p>I thought scope of <code>e</code> is within the <code>while</code> block and it will not be accessible in the outside <code>print</code> statement. What did I miss ...
2
2016-10-07T17:59:46Z
39,923,802
<p>Simple: <code>while</code> does not create a scope in Python. Python has only the following scopes:</p> <ul> <li>function scope (may include closure variables)</li> <li>class scope (only while the class is being defined)</li> <li>global (module) scope</li> <li>comprehension/generator expression scope</li> </ul> <p...
5
2016-10-07T18:33:49Z
[ "python", "python-2.7", "exception" ]
'str' object is not callable Django Rest Framework
39,923,384
<p>I'm trying to create an API view but I'm getting an error. Can anyone help?</p> <p>urls.py:</p> <pre><code>app_name = 'ads' urlpatterns = [ # ex: /ads/ url(r'^$', views.ListBrand.as_view(), name='brand_list'), ] </code></pre> <p>views.py:</p> <pre><code>from rest_framework.views import APIView from rest_...
0
2016-10-07T18:04:41Z
39,924,164
<p>My problem was in my settings.py file:</p> <p>It should've been:</p> <pre><code>REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticatedOrReadOnly', ),...
1
2016-10-07T19:00:14Z
[ "python", "django", "python-3.x", "django-rest-framework" ]
Compare length of values of a column
39,923,519
<p>I have a data frame with 20 columns, two of the columns being Company1 and Company2. I want a resultant data frame with only those rows in which length of Company1 and Company2 don't differ by more than 5 characters. How do I accomplish this task using pandas? </p>
1
2016-10-07T18:15:03Z
39,923,711
<p>You can use <code>.str.len()</code> to get access to the number of characters in the <code>Company</code> columns, then calculate the difference with vectorized subtraction of pandas series and create a logic vector with the condition for subsetting:</p> <pre><code>df[abs(df.Company1.str.len() - df.Company2.str.len...
2
2016-10-07T18:27:26Z
[ "python", "pandas" ]
Python Load csv file to Oracle table
39,923,540
<p>I'm a python beginner. I'm trying to insert records into a Oracle table from a csv file. csv file format : Artist_name, Artist_type, Country . I'm getting below error:</p> <pre><code>Error: File "artist_dim.py", line 42, in &lt;module&gt; cur.execute(sqlquery) cx_Oracle.DatabaseError: ORA-00917: missing comma ...
0
2016-10-07T18:16:29Z
39,923,627
<p>Put quotes around the values:</p> <pre><code>sqlquery="INSERT INTO ARTIST_DIM VALUES (%d,'%s','%s','%s')" %(x,row['Artist_name'],row['Artist_type'],row['Country']) </code></pre> <p>Without the quotes it translates to:</p> <pre><code>sqlquery="INSERT INTO ARTIST_DIM VALUES (1, Bob, Bob, Bob)" </code></pre>
1
2016-10-07T18:22:36Z
[ "python", "oracle", "python-3.x" ]
Python read CSV file, and write to another skipping columns
39,923,595
<p>I have CSV input file with 18 columns I need to create new CSV file with all columns from input except column 4 and 5</p> <p>My function now looks like</p> <pre><code>def modify_csv_report(input_csv, output_csv): begin = 0 end = 3 with open(input_csv, "r") as file_in: with open(output_csv, "w"...
0
2016-10-07T18:20:35Z
39,923,631
<p>You can add the other part of the row using <em>slicing</em>, like you did with the first part:</p> <pre><code>writer.writerow(row[:4] + row[6:]) </code></pre> <p>Note that to include column 3, the stop index of the first slice should be 4. Specifying start index 0 is also usually not necessary.</p> <p>A more gen...
2
2016-10-07T18:22:49Z
[ "python", "csv" ]
Python read CSV file, and write to another skipping columns
39,923,595
<p>I have CSV input file with 18 columns I need to create new CSV file with all columns from input except column 4 and 5</p> <p>My function now looks like</p> <pre><code>def modify_csv_report(input_csv, output_csv): begin = 0 end = 3 with open(input_csv, "r") as file_in: with open(output_csv, "w"...
0
2016-10-07T18:20:35Z
39,923,807
<p>This is what you want:</p> <pre><code>import csv def remove_csv_columns(input_csv, output_csv, exclude_column_indices): with open(input_csv) as file_in, open(output_csv, 'w') as file_out: reader = csv.reader(file_in) writer = csv.writer(file_out) writer.writerows( [col for ...
0
2016-10-07T18:34:11Z
[ "python", "csv" ]
Python read CSV file, and write to another skipping columns
39,923,595
<p>I have CSV input file with 18 columns I need to create new CSV file with all columns from input except column 4 and 5</p> <p>My function now looks like</p> <pre><code>def modify_csv_report(input_csv, output_csv): begin = 0 end = 3 with open(input_csv, "r") as file_in: with open(output_csv, "w"...
0
2016-10-07T18:20:35Z
39,923,823
<p>If your CSV has meaningful headers an alternative solution to slicing your rows by indices, is to use the <code>DictReader</code> and <code>DictWriter</code> classes.</p> <pre><code>#!/usr/bin/env python from csv import DictReader, DictWriter data = '''A,B,C 1,2,3 4,5,6 6,7,8''' reader = DictReader(data.split('\n...
0
2016-10-07T18:35:36Z
[ "python", "csv" ]
Models referring to each other - how can I most efficiently fix this issue?
39,923,649
<p>I have a Django application that contains two models - <code>Company</code> and <code>User</code>. These are each in separate files. Each <code>User</code> has a <code>Company</code> by a <code>model.ForeignKey</code> field:</p> <p>company.py:</p> <pre><code>class Company(models.Model): name = models.CharField...
0
2016-10-07T18:23:50Z
39,923,761
<pre><code>def list_admins(self): return User.object.filter(company__is_admin=True); </code></pre>
-1
2016-10-07T18:30:48Z
[ "python", "django", "django-models" ]
Models referring to each other - how can I most efficiently fix this issue?
39,923,649
<p>I have a Django application that contains two models - <code>Company</code> and <code>User</code>. These are each in separate files. Each <code>User</code> has a <code>Company</code> by a <code>model.ForeignKey</code> field:</p> <p>company.py:</p> <pre><code>class Company(models.Model): name = models.CharField...
0
2016-10-07T18:23:50Z
39,923,892
<p>You can use the reverse <code>ForeignKey</code> relation on each <code>Company</code> to access their respective <code>Users</code>:</p> <pre><code>def list_admins(self): return self.user_set.filter(is_admin=True) </code></pre> <hr> <p>Doc. reference: <a href="https://docs.djangoproject.com/en/1.10/topics/db/...
2
2016-10-07T18:40:05Z
[ "python", "django", "django-models" ]
Measure how much activity is occurring within certain frequency values in Python
39,923,741
<p>I'm trying to find a way to obtain frequency values (in Hz) of an audio file, and measure how often these frequency values occur in proportion to the rest of the frequency values in that file. </p> <p>For example, in an audio file, I'd like to see what proportion of the audio activity occurs within the 300 - 500 Hz...
0
2016-10-07T18:29:12Z
39,923,974
<p>You may be looking for a <a href="https://en.wikipedia.org/wiki/Fourier_transform" rel="nofollow">Fourier Transform</a> or <a href="https://en.wikipedia.org/wiki/Fast_Fourier_transform" rel="nofollow">Fast Fourier Transform</a>.</p> <p>From Wikipedia:</p> <p><a href="http://i.stack.imgur.com/QWXIG.png" rel="nofoll...
1
2016-10-07T18:46:19Z
[ "python", "audio", "frequency" ]
json array with in array returning error ?bad string
39,923,774
<p>i am parsing my json string file to python and always returning error . i used online json formatter and validators that also returning error so i want help to make my json correct and tell me error</p> <pre><code> [{ "sentence_id": "TR.00001", "sentence": { "text": "Bill was born 1986.", ...
0
2016-10-07T18:32:01Z
39,923,952
<p>JSON doesn't understand tuples, try changing to lists:</p> <pre><code>"annotation": [ [1, "Bill", "bill", "NNP", "B-PERSON"], [2, "was", "be", "VBD", "O"], [3, "born", "bear", "VBN", "O"], [4, "1986", "BIL", "CD", "B-DATE"], [5, ".", ".", ".", "O"] ] </code></pre> <p>You can do <code>tuple(list...
2
2016-10-07T18:45:12Z
[ "javascript", "php", "python", "arrays", "json" ]
json array with in array returning error ?bad string
39,923,774
<p>i am parsing my json string file to python and always returning error . i used online json formatter and validators that also returning error so i want help to make my json correct and tell me error</p> <pre><code> [{ "sentence_id": "TR.00001", "sentence": { "text": "Bill was born 1986.", ...
0
2016-10-07T18:32:01Z
39,924,089
<p>Your json string file is not proper it have some error ...</p> <ol> <li>you missed the key in annotation.</li> <li>your value must be in capital bracket because it is an array.</li> <li><p>you add extra comma at the end.</p> <pre><code> [ { "sentence_id" : "TR.00001", "sentence" : { "text" :...
1
2016-10-07T18:54:21Z
[ "javascript", "php", "python", "arrays", "json" ]
OpenCV Stereo confidence
39,923,798
<p>Is there a way to get out the confidence from OpenCV's Stereo matching algorithms in Python?</p> <p>I wish to eliminate points from the generated point cloud based on these confidence values.</p>
1
2016-10-07T18:33:28Z
39,927,027
<p>Unfortunately, OpenCV does not seem to provide correlation scores with the stereo matcher functions. If no correspondance is found, pixel appears black on disparity map but you have to trust the algorithms implementation.</p> <p>You can still compute your own error estimate with respect to your camera parameters, b...
0
2016-10-07T23:19:31Z
[ "python", "opencv", "computer-vision" ]
Retrieving form data after setting initial value
39,923,814
<p>I wanted to populate my form fields with initial data, so I've set my view just like recommended by @ars in <a href="http://stackoverflow.com/questions/3833403/initial-populating-on-django-forms">this question</a>:</p> <pre><code>def update_member(request): if request.method == 'POST': urn = 'urn:public...
0
2016-10-07T18:35:01Z
39,924,765
<p>If you check the POST data for values submitted, you can update member_attributes with those values before calling UpdateMemberForm()</p>
1
2016-10-07T19:45:17Z
[ "python", "django" ]
Merging two dictionaries together and adding None to the desired location
39,923,922
<p>I've scraped some <a href="http://www.richmond.com/data-center/salaries-local-government-employees-2014/?Agency=&amp;Last_Name=&amp;First_Name=&amp;Job_Title=PRINCIPAL&amp;appSession=82100926574322760625479516407609655632811717398403303845564132296054295099051816928601026788234447191565075848437884339109744304&amp;R...
2
2016-10-07T18:42:39Z
39,924,100
<p>I would restructure the data such that you have one dictionary for all relevant fields for each person. You can than easily use the dictwriter class of csv to export that data. </p>
0
2016-10-07T18:55:22Z
[ "python", "python-2.7", "csv", "dictionary" ]
Merging two dictionaries together and adding None to the desired location
39,923,922
<p>I've scraped some <a href="http://www.richmond.com/data-center/salaries-local-government-employees-2014/?Agency=&amp;Last_Name=&amp;First_Name=&amp;Job_Title=PRINCIPAL&amp;appSession=82100926574322760625479516407609655632811717398403303845564132296054295099051816928601026788234447191565075848437884339109744304&amp;R...
2
2016-10-07T18:42:39Z
39,924,128
<p>It'd be much better to change the way you store scraped data.</p> <p>Pseudocode:</p> <pre><code>data = [] for row in table: person = get_data_from_row(row) person.update(get_data_from_person_page(row)) data.append(person) </code></pre> <p>Then you can use <a href="https://docs.python.org/3/library/csv...
1
2016-10-07T18:57:18Z
[ "python", "python-2.7", "csv", "dictionary" ]
Pandas sklearn one-hot encoding dataframe or numpy?
39,923,927
<p>How can I transform a pandas data frame to sklearn one-hot-encoded (dataframe / numpy array) where some columns do not require encoding?</p> <pre><code>mydf = pd.DataFrame({'Target':[0,1,0,0,1, 1,1], 'GroupFoo':[1,1,2,2,3,1,2], 'GroupBar':[2,1,1,0,3,1,2], '...
0
2016-10-07T18:42:54Z
39,930,275
<p>This library provides several categorical encoders which make sklearn / numpy play nicely with pandas <a href="https://github.com/wdm0006/categorical_encoding" rel="nofollow">https://github.com/wdm0006/categorical_encoding</a></p> <p>However, they do not yet support "handle unknown category"</p> <p>for now I will ...
0
2016-10-08T08:21:05Z
[ "python", "pandas", "numpy", "scikit-learn", "dummy-variable" ]
Trying to create new variables by strings from a list
39,923,999
<p><p> I've been scouring the ends of the internet for this, and I am well aware of how discouraged what I am trying to do is. I just can't figure out another way to achieve what I want. Now, for my actual issue, I have been given a csv containing information of police shootings. The file contains the state of the case...
-1
2016-10-07T18:47:56Z
39,924,159
<p>Use <code>csv.reader</code> and <code>collections.defaultdict</code>:</p> <pre><code>import csv import collections with open('states.csv') as f: result = collections.defaultdict(list) reader = csv.reader(f) for state,city in reader: result[state].append(city) </code></pre> <p>The file:</p> <pr...
1
2016-10-07T18:59:41Z
[ "python", "list", "csv", "variables" ]
Trying to create new variables by strings from a list
39,923,999
<p><p> I've been scouring the ends of the internet for this, and I am well aware of how discouraged what I am trying to do is. I just can't figure out another way to achieve what I want. Now, for my actual issue, I have been given a csv containing information of police shootings. The file contains the state of the case...
-1
2016-10-07T18:47:56Z
39,924,318
<p>It is possible by using <code>eval()</code>, but you should <strong>REALLY</strong> not do that... a much more structured and safe way to accomplish your task would be to take the state name and make that a key in a dictionary:</p> <pre class="lang-python prettyprint-override"> txt = '''state1, city1 state2, city2 ...
0
2016-10-07T19:11:57Z
[ "python", "list", "csv", "variables" ]
Trying to create new variables by strings from a list
39,923,999
<p><p> I've been scouring the ends of the internet for this, and I am well aware of how discouraged what I am trying to do is. I just can't figure out another way to achieve what I want. Now, for my actual issue, I have been given a csv containing information of police shootings. The file contains the state of the case...
-1
2016-10-07T18:47:56Z
39,925,002
<p>Time to bring this to a close. My friend helped me out by introducing me to dictionaries. The formatting is right for my data, and I have parented all the states to their respective cities. Thank you all for the help! While furas' answer was correct for what I needed, it wasn't very explanatory, so I think the most ...
0
2016-10-07T20:06:26Z
[ "python", "list", "csv", "variables" ]
IBM Bluemix user defined variables
39,924,006
<p>How can we access <code>USER-DEFINED</code> variables in IBM Bluemix in Python? I have made a token in IBM Bluemix, but I am unable to access it from my Python script. </p> <p>In the bluemix UI,</p> <p><code>token = &lt;actual value of token&gt;</code></p>
0
2016-10-07T18:48:20Z
39,925,339
<p>Solved it.</p> <p><code>os.getenv('name of the key')</code></p> <p>where <code>name of the key</code> is key defined in Bluemix UI. </p>
0
2016-10-07T20:30:15Z
[ "python", "ibm-bluemix", "ibm" ]
fPython : Making a new list from a random list of letters
39,924,096
<pre><code>letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']#alphabet bag_o_letters = []#letters to chose from letter_count = [9, 2, 2, 4, 12, 2, 3, 2, 9, 1, 1, 4, 2, 6, 8, 2, 1, 6, 4, 6, 4, 2, 2, 1, 2, 1]#random indexes to chose...
0
2016-10-07T18:55:02Z
39,924,208
<p>You're selecting the <em>index</em> to <code>pop</code> for <code>bag_of_letters</code> from the length of <code>letters</code> which is obviously larger.</p> <p>You should instead do:</p> <pre><code>rack.append(bag_of_letters.pop(random.randint(0, len(bag_of_letters)-1))) # ...
1
2016-10-07T19:04:18Z
[ "python", "list", "random" ]
fPython : Making a new list from a random list of letters
39,924,096
<pre><code>letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']#alphabet bag_o_letters = []#letters to chose from letter_count = [9, 2, 2, 4, 12, 2, 3, 2, 9, 1, 1, 4, 2, 6, 8, 2, 1, 6, 4, 6, 4, 2, 2, 1, 2, 1]#random indexes to chose...
0
2016-10-07T18:55:02Z
39,924,244
<p>The first time through the loop, you append one value to <code>bag_of_letters</code>, and then you try to pop an index of <code>random.randint(0,len(letters)-1)</code>. It doesn't have that many elements to pop from yet. Instead of this approach, you can make a list of the required length and sample from it:</p> <p...
2
2016-10-07T19:06:25Z
[ "python", "list", "random" ]
fPython : Making a new list from a random list of letters
39,924,096
<pre><code>letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']#alphabet bag_o_letters = []#letters to chose from letter_count = [9, 2, 2, 4, 12, 2, 3, 2, 9, 1, 1, 4, 2, 6, 8, 2, 1, 6, 4, 6, 4, 2, 2, 1, 2, 1]#random indexes to chose...
0
2016-10-07T18:55:02Z
39,924,246
<p>So I assume this is for something like scrabble? Your issue is that you're choosing a random index from your list of <code>letters</code>, not <code>bag_o_letters</code>. Maybe try this:</p> <pre><code>rack = [] for i in range(7): index = random.randint(0, len(bag_o_letter) - 1) rack.append(bag_o_letters.po...
0
2016-10-07T19:06:31Z
[ "python", "list", "random" ]
fPython : Making a new list from a random list of letters
39,924,096
<pre><code>letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']#alphabet bag_o_letters = []#letters to chose from letter_count = [9, 2, 2, 4, 12, 2, 3, 2, 9, 1, 1, 4, 2, 6, 8, 2, 1, 6, 4, 6, 4, 2, 2, 1, 2, 1]#random indexes to chose...
0
2016-10-07T18:55:02Z
39,924,260
<p>Why not do something like this:</p> <pre><code>letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] letter_count = [9, 2, 2, 4, 12, 2, 3, 2, 9, 1, 1, 4, 2, 6, 8, 2, 1, 6, 4, 6, 4, 2, 2, 1, 2, 1]#random indexes to chose from fro...
0
2016-10-07T19:07:32Z
[ "python", "list", "random" ]
fPython : Making a new list from a random list of letters
39,924,096
<pre><code>letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']#alphabet bag_o_letters = []#letters to chose from letter_count = [9, 2, 2, 4, 12, 2, 3, 2, 9, 1, 1, 4, 2, 6, 8, 2, 1, 6, 4, 6, 4, 2, 2, 1, 2, 1]#random indexes to chose...
0
2016-10-07T18:55:02Z
39,924,266
<p>The IndexError is expected:</p> <blockquote> <p>pop(...) L.pop([index]) -> item -- remove and return item at index (default last). Raises IndexError if list is empty or <strong>index is out of range</strong>.</p> </blockquote> <p>You need to subtract 1 from the bounds of the call to <code>random()</c...
0
2016-10-07T19:07:42Z
[ "python", "list", "random" ]
I am writing a code which builds a decision tree and spits out the tree in the form of a code of if-else loops
39,924,168
<p>I am able to generate the correct if else loops. But i am not able to adjust the indentation. Is there any way of correctly indenting it?</p>
-4
2016-10-07T19:00:34Z
39,924,201
<p>If you have an indentation level that matches the decision tree depth, you should be able to just prepend four spaces for each level of indentation.</p>
0
2016-10-07T19:03:42Z
[ "python", "decision-tree" ]
How to make huge loops in python faster on mac?
39,924,176
<p>I am a computer science student and some of the things I do require me to run huge loops on Macbook with dual core i5. Some the loops take 5-6 hours to complete but they only use 25% of my CPU. Is there a way to make this process faster? I cant change my loops but is there a way to make them run faster?</p> <p>Than...
0
2016-10-07T19:01:22Z
39,924,228
<p>Sure thing: Python 2.7 has to generate huge lists and waste a lot of memory <em>each time</em> you use <code>range(&lt;a huge number&gt;)</code>. </p> <p>Try to use the <code>xrange</code> function instead. It doesn't create that gigantic list at once, it produces the members of a sequence <em>lazily</em>. </p> <h...
4
2016-10-07T19:05:32Z
[ "python", "performance", "python-2.7", "loops", "cpu-usage" ]
How to make huge loops in python faster on mac?
39,924,176
<p>I am a computer science student and some of the things I do require me to run huge loops on Macbook with dual core i5. Some the loops take 5-6 hours to complete but they only use 25% of my CPU. Is there a way to make this process faster? I cant change my loops but is there a way to make them run faster?</p> <p>Than...
0
2016-10-07T19:01:22Z
39,924,339
<p>You could split it up into 4 loops:</p> <pre><code>import multiprocessing def test_false_pos(i, pieces, q): sumA = [0] * 1000 for test in range((1000/pieces) * i, 250 + (1000/pieces)*i): counter = 0 bf = BloomFilter(4095,10) for i in range(600): bf.rand_inserts() ...
3
2016-10-07T19:13:39Z
[ "python", "performance", "python-2.7", "loops", "cpu-usage" ]
How to make huge loops in python faster on mac?
39,924,176
<p>I am a computer science student and some of the things I do require me to run huge loops on Macbook with dual core i5. Some the loops take 5-6 hours to complete but they only use 25% of my CPU. Is there a way to make this process faster? I cant change my loops but is there a way to make them run faster?</p> <p>Than...
0
2016-10-07T19:01:22Z
39,924,499
<p>Consider looking into Numba and Jit (just in time compiler). It works for functions that are Numpy based. It can handle some python routines, but is mainly for speeding up numerical calculations, especially ones with loops (like doing cholesky rank-1 up/downdates). I don't think it would work with a BloomFilter, ...
1
2016-10-07T19:26:01Z
[ "python", "performance", "python-2.7", "loops", "cpu-usage" ]
Python parser ply matches wrong regex
39,924,181
<p>I'm trying to create a parser using Ply but I am confronted to a strange error. Here is a MCVE where the matching error occurs :</p> <p>Lexer</p> <pre><code>import ply.lex as lex tokens = ( 'IDENTIFIER', 'NAME', 'EQUALS' ) def t_IDENTIFIER(t): r'\* *[a-zA-Z_]+' print("identifier") return ...
1
2016-10-07T19:01:46Z
39,925,412
<p>I think I found problem and solution. </p> <p>Problem is <code>'*'</code> in <code>' *'</code> because it treats <code>'\* '</code> as one string - so <code>'\* *'</code> means <code>'\* '</code> many times or <strong>none</strong> (like <code>'abc*'</code> means <code>'abc'</code> many times or none).</p> <p>You ...
1
2016-10-07T20:35:55Z
[ "python", "regex", "parsing", "lexer", "ply" ]
Python parser ply matches wrong regex
39,924,181
<p>I'm trying to create a parser using Ply but I am confronted to a strange error. Here is a MCVE where the matching error occurs :</p> <p>Lexer</p> <pre><code>import ply.lex as lex tokens = ( 'IDENTIFIER', 'NAME', 'EQUALS' ) def t_IDENTIFIER(t): r'\* *[a-zA-Z_]+' print("identifier") return ...
1
2016-10-07T19:01:46Z
39,928,427
<p>According to the <a href="http://www.dabeaz.com/ply/ply.html#ply_nn6" rel="nofollow">PLY manual</a>: (emphasis added)</p> <blockquote> <p>Internally, <code>lex.py</code> uses the <code>re</code> module to do its pattern matching. <em>Patterns are compiled using the <code>re.VERBOSE</code> flag</em> which can be u...
1
2016-10-08T03:39:06Z
[ "python", "regex", "parsing", "lexer", "ply" ]
tkinter widgets on one frame affecting another frame alignment
39,924,213
<p>this program works functionality wise so far anyway so that's not my issue. My issue is something to do with how the alignment works for widgets with multiple frames. If I make the widgets on one frame longer width wise, than the other frames, it will center all the frames based on the widest frame rather than each ...
-1
2016-10-07T19:04:45Z
39,925,476
<p>There are usually many ways to solve layout problems. It all depends on what you actually want to do, what actual widgets you're using, and how you expect widgets react when their containing windows or frames change. </p> <p>When you use <code>grid</code>, by default it gives widgets only as much space as they need...
1
2016-10-07T20:40:28Z
[ "python", "tkinter", "alignment" ]
How to use Python requests to post form as curl PUT -F
39,924,303
<p>I'm trying to replicate the use of <code>curl PUT -F "file=@someFile"</code> using Python's requests. The Content-Type i'm required to use is: <code>multipart/form-data</code> I tried different variations like:</p> <p><code>r = requests.put(url, headers=headers, files={'file': (full_filename, open(full_filename, 'r...
0
2016-10-07T19:10:25Z
39,931,294
<p>Thanks to <a href="http://stackoverflow.com/a/17438575/1659322">http://stackoverflow.com/a/17438575/1659322</a> i managed to work it out. I'm quoting his answer here because i find it extremely important:</p> <blockquote> <p>You should NEVER set that header yourself. We set the header properly with the boundary. ...
0
2016-10-08T10:29:36Z
[ "python", "curl", "python-requests", "multipartform-data", "put" ]
Redis management on Heroku
39,924,325
<p>I have provisioned Redis To Go addon in Heroku for use with <a href="http://python-rq.org/" rel="nofollow">Redis Queue python library</a>. My app is having some issue with the redis DB for the queue (namely max-memory problem). The memory use stays really high even when all the work has been finished. So I have b...
0
2016-10-07T19:12:35Z
39,924,543
<p>To give your Redis more RAM (i.e. increase max-memory) you just need to upgrade your plan - use <code>heroku addons:upgrade ...</code> to do that.</p>
0
2016-10-07T19:29:26Z
[ "python", "memory", "heroku", "redis" ]
Redis management on Heroku
39,924,325
<p>I have provisioned Redis To Go addon in Heroku for use with <a href="http://python-rq.org/" rel="nofollow">Redis Queue python library</a>. My app is having some issue with the redis DB for the queue (namely max-memory problem). The memory use stays really high even when all the work has been finished. So I have b...
0
2016-10-07T19:12:35Z
39,929,800
<p>Just for anyone using <a href="https://elements.heroku.com/addons/redistogo" rel="nofollow">Redis To Go</a>, I switched my Redis server to the free version of <a href="https://elements.heroku.com/addons/heroku-redis" rel="nofollow">Heroku Redis</a> and all the problems went away. </p> <p>Redis To Go was telling me...
0
2016-10-08T07:18:23Z
[ "python", "memory", "heroku", "redis" ]
Python generating a lookup table of lambda expressions
39,924,360
<p>I'm building a game and in order to make it work, I need to generate a list of "pre-built" or "ready to call" expressions. I'm trying to do this with lambda expressions, but am running into an issue generating the lookup table. The code I have is similar to the following:</p> <pre><code>import inspect def test(*...
0
2016-10-07T19:14:47Z
39,924,419
<p>As others have mentioned, Python's closures are <em>late binding</em>, which means that variables from an outside scope referenced in a closure (in other words, the variables <em>closed over</em>) are looked up at the moment the closure is called and <em>not</em> at the time of definition.</p> <p>In your example, t...
2
2016-10-07T19:19:46Z
[ "python", "function", "lambda", "functional-programming", "anonymous-function" ]
Crypto.Util import error in firebase_helper.py when deploying to Google App Flexible Engine
39,924,382
<p>I have been working to deploy the <a href="https://cloud.google.com/appengine/docs/python/authenticating-users-firebase-appengine" rel="nofollow">Authenticating Users on App Engine Using Firebase</a> tutorial, and can successfully deploy this to my local machine. </p> <p>As I wish to test some python modules that d...
1
2016-10-07T19:17:25Z
39,925,886
<p>According to the <a href="https://cloud.google.com/appengine/docs/flexible/python/migrating-an-existing-app" rel="nofollow">Google App engine documentation</a>, the libraries section of app.yaml is no longer supported in flexible VM. You will need to declare dependencies in requirements.txt.</p> <p>So, you need to ...
2
2016-10-07T21:13:17Z
[ "python", "google-app-engine", "firebase" ]
How do I post this HTML form using Python?
39,924,501
<p>This is the form that I want to post in Python:</p> <pre><code> &lt;FORM METHOD="POST" ACTION="http://www.speech.cs.cmu.edu/cgi-bin/tools/lmtool/run" ENCTYPE="multipart/form-data"&gt; &lt;INPUT NAME="formtype" TYPE="HIDDEN" value="simple"&gt; &lt;p&gt;&lt;b&gt;Upload a sentence corpus file&lt;/b&g...
0
2016-10-07T19:26:02Z
39,924,729
<p>There might be other errors, but the error message you get is clear enough:</p> <p>What the form expects:</p> <pre><code>&lt;INPUT NAME="formtype" ...&gt; </code></pre> <p>what you send:</p> <pre><code>'NAME': 'fromtype', ... </code></pre> <p>You see the difference between <strong>formtype</strong> and <strong>...
0
2016-10-07T19:42:53Z
[ "python", "html", "post", "python-requests" ]
Limiting integer width in python
39,924,510
<p>I'm practicing python, I came across a situation where I wanted to limit the character width of a field but it wasn't working.(I hope I'm saying that right) I want to truncate the sum of 2 integers to 5 spaces. eg: the sum of 88888 + 22222 has 6 characters. Is it possible to limit it to 5?</p>
0
2016-10-07T19:26:46Z
39,924,549
<p>You can easily truncate the value of these integers. Simply convert the result into a string and then use the Python index to select the first five characters:</p> <pre><code>&gt;&gt;&gt; str(88888 + 22222)[:5] '11111' </code></pre> <p>You can also convert this value back to an integer using <code>int()</code> if ...
1
2016-10-07T19:30:08Z
[ "python", "python-2.7", "python-3.x" ]
Limiting integer width in python
39,924,510
<p>I'm practicing python, I came across a situation where I wanted to limit the character width of a field but it wasn't working.(I hope I'm saying that right) I want to truncate the sum of 2 integers to 5 spaces. eg: the sum of 88888 + 22222 has 6 characters. Is it possible to limit it to 5?</p>
0
2016-10-07T19:26:46Z
39,924,566
<p>To limit the number of decimal characters by throwing away the upper digits, you can use a remainder:</p> <pre><code>(88888 + 22222) % 100000 </code></pre> <p>To do the same for a binary number, which is more commonly required, you can use a bit-wise and. Here's an example limited to 16 bits.</p> <pre><code>(8888...
1
2016-10-07T19:31:03Z
[ "python", "python-2.7", "python-3.x" ]
How to read a compressed (gz) CSV file inro a dask Dataframe?
39,924,518
<p>Is there a way to read a .csv file that is compressed via gz into a dask dataframe?</p> <p>I've tried it directly with</p> <pre><code>import dask.dataframe as dd df = dd.read_csv("Data.gz" ) </code></pre> <p>but get an unicode error (probably because it is interpreting the compressed bytes) There is a <code>"comp...
1
2016-10-07T19:27:03Z
39,924,970
<p>Without the file it's difficult to say. what if you set the encoding <code>like # -*- coding: latin-1 -*-</code>? or since <code>read_csv</code> is based off of Pandas, you may even <code>dd.read_csv('Data.gz', encoding='utf-8')</code>. Here's the list of Python encodings: <a href="https://docs.python.org/3/library/...
1
2016-10-07T20:04:42Z
[ "python", "csv", "pandas", "dask" ]
Python add quotes to all elements in list?
39,924,531
<p>I have a several list with in a dictionary. How do I add quotes around every element in each list?</p> <pre><code>native_american={ "A2" : ["Native, Eskimo Volodko, Apache, Mexico, Central America, Guarani, Rio das Cobras, Katuana, Poturujara, Surui, Waiwai, Yanomama, Zoro, Arsario, Cayapa, Kogui, Inupiat, Lauricoc...
1
2016-10-07T19:28:07Z
39,924,570
<p>Do you mean something like <code>"Native", "Eskimo Volodko", "Apache"</code>?</p> <p>If so: <code>[item.strip() for item in list.split(',')]</code></p>
0
2016-10-07T19:31:11Z
[ "python" ]
Python add quotes to all elements in list?
39,924,531
<p>I have a several list with in a dictionary. How do I add quotes around every element in each list?</p> <pre><code>native_american={ "A2" : ["Native, Eskimo Volodko, Apache, Mexico, Central America, Guarani, Rio das Cobras, Katuana, Poturujara, Surui, Waiwai, Yanomama, Zoro, Arsario, Cayapa, Kogui, Inupiat, Lauricoc...
1
2016-10-07T19:28:07Z
39,924,576
<pre><code>native_american = {key: value[0].split(',') for key, value in native_american.items()} </code></pre> <p>What you have at the moment is a list of one long string. This splits it into a list of many smaller strings</p>
3
2016-10-07T19:31:34Z
[ "python" ]
Sum from 1 to n in one line Python
39,924,547
<p>Given number <code>n</code>, I need to find the sum of numbers from <code>1</code> to <code>n</code>. Sample input and output:</p> <pre><code>100 5050 </code></pre> <p>So I came up with <code>print(sum(range(int(input())+1)))</code> which solves the problem in one line but takes a long time since it's <code>O(n)</...
1
2016-10-07T19:30:00Z
39,924,672
<p>Act as if it's Javascript; create a function that takes a parameter <code>n</code>, then immediately call it with the result of <code>input()</code>:</p> <pre><code>(lambda n: n * (n + 1) / 2)(int(input())) </code></pre>
10
2016-10-07T19:38:46Z
[ "python" ]
Sum from 1 to n in one line Python
39,924,547
<p>Given number <code>n</code>, I need to find the sum of numbers from <code>1</code> to <code>n</code>. Sample input and output:</p> <pre><code>100 5050 </code></pre> <p>So I came up with <code>print(sum(range(int(input())+1)))</code> which solves the problem in one line but takes a long time since it's <code>O(n)</...
1
2016-10-07T19:30:00Z
39,925,314
<p>Python 3, one line, and shorter than the currently accepted answer:</p> <pre><code>n=int(input());print(n*(n+1)/2) </code></pre>
0
2016-10-07T20:28:35Z
[ "python" ]
Python Raw Socket to Ethernet Interface (Windows)
39,924,563
<p>I'm trying to create a DHCP Server and the first step is for me to send packets through my ethernet port. I'm trying to send packets to my Ethernet interface and having an error popping up.</p> <p>The code is below.</p> <pre><code>import socket def sendeth(src, dst, eth_type, payload, interface = "eth0"): """Se...
0
2016-10-07T19:30:51Z
39,924,831
<p>Looks like you don't get access to ethernet with this socket:</p> <pre><code>s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW) </code></pre> <p><code>socket.IPPROTO_RAW</code> gives you access to Level 3 protocol (IP), whereas ethernet is on Level 1 and 2. At level 3 an ethernet frame is alrea...
0
2016-10-07T19:50:27Z
[ "python", "windows", "python-2.7", "sockets", "dhcp" ]
Python Raw Socket to Ethernet Interface (Windows)
39,924,563
<p>I'm trying to create a DHCP Server and the first step is for me to send packets through my ethernet port. I'm trying to send packets to my Ethernet interface and having an error popping up.</p> <p>The code is below.</p> <pre><code>import socket def sendeth(src, dst, eth_type, payload, interface = "eth0"): """Se...
0
2016-10-07T19:30:51Z
39,924,857
<p>This example from the docs seems instructive. <a href="https://docs.python.org/2/library/socket.html" rel="nofollow">https://docs.python.org/2/library/socket.html</a></p> <pre><code>import socket # the public network interface HOST = socket.gethostbyname(socket.gethostname()) # create a raw socket and bind it to ...
0
2016-10-07T19:52:52Z
[ "python", "windows", "python-2.7", "sockets", "dhcp" ]
Python Raw Socket to Ethernet Interface (Windows)
39,924,563
<p>I'm trying to create a DHCP Server and the first step is for me to send packets through my ethernet port. I'm trying to send packets to my Ethernet interface and having an error popping up.</p> <p>The code is below.</p> <pre><code>import socket def sendeth(src, dst, eth_type, payload, interface = "eth0"): """Se...
0
2016-10-07T19:30:51Z
39,926,417
<p>DHCP is a UDP protocol. You shouldn't need a raw socket to implement a DHCP server.</p> <p>Use an AF_INET/SOCK_DGRAM socket, and bind to address 255.255.255.255 in order to implement your server.</p>
0
2016-10-07T22:02:47Z
[ "python", "windows", "python-2.7", "sockets", "dhcp" ]
Python Raw Socket to Ethernet Interface (Windows)
39,924,563
<p>I'm trying to create a DHCP Server and the first step is for me to send packets through my ethernet port. I'm trying to send packets to my Ethernet interface and having an error popping up.</p> <p>The code is below.</p> <pre><code>import socket def sendeth(src, dst, eth_type, payload, interface = "eth0"): """Se...
0
2016-10-07T19:30:51Z
39,926,458
<p>Approaching your question from another direction: why do you need to work with ethernet at all? DHCP is usually implemented via UDP.</p> <ol> <li>DHCP server always has some IP address (and a pool of addresses it can lease).</li> <li>If a client wants and IP (DHCP actually can do much more than just assign IPs but ...
0
2016-10-07T22:08:07Z
[ "python", "windows", "python-2.7", "sockets", "dhcp" ]
Python - wxPython Sequence of Command Execution
39,924,586
<p>I have a properly working code, I understand I am not pasting enough code - but I will explain each command with proper comments. My question here is why is the code behaving rather than what I expected it to behave. </p> <p>My code: </p> <pre><code> def OnReset(self, event): # A function event which works after ...
2
2016-10-07T19:32:26Z
39,924,782
<p>The problem is that you're calling <code>time.sleep(5)</code> and <code>self.OnCorrectComPort()</code> in the callback, <em>before</em> returning to the mainloop where the events will be processed.</p> <p>The widgets will not reflect the effects of your <code>Clear</code> calls until you exit of the callback into t...
1
2016-10-07T19:46:19Z
[ "python", "multithreading", "wxpython" ]
Multilanguage site with Python Django
39,924,596
<p>We are making a site for multiple users, using Python Django.</p> <p>We need to set language of system messages (such as indications of user's errors, labels of control elements, etc.) different for different registered users.</p> <p>What is the best way to do this?</p>
-2
2016-10-07T19:33:29Z
39,924,680
<p>There is <code>activate</code> function in <code>django.utils.translation</code>, to set the language for current session.</p>
-1
2016-10-07T19:39:25Z
[ "python", "django" ]
Multilanguage site with Python Django
39,924,596
<p>We are making a site for multiple users, using Python Django.</p> <p>We need to set language of system messages (such as indications of user's errors, labels of control elements, etc.) different for different registered users.</p> <p>What is the best way to do this?</p>
-2
2016-10-07T19:33:29Z
39,924,726
<p>Django has a very mature and standard internationalization framework. The <a href="https://docs.djangoproject.com/en/1.10/topics/i18n/" rel="nofollow">documentation</a> is extensive and well organized.</p> <p>Unless you want to avoid using Django's own facilities for translation, which could be the case for applica...
0
2016-10-07T19:42:50Z
[ "python", "django" ]
Adding variable number of controls to DropDown - weakly-referenced object no longer exists
39,924,598
<p>I have a dropdown with a list of the months in it. When the Month is selected, I'm trying to dynamically populate buttons in a second dropdown with the correct number of days. When I do so, I get:</p> <pre><code>ReferenceError: weakly-referenced object no longer exists </code></pre> <p>Here are my files for refere...
1
2016-10-07T19:33:32Z
40,050,644
<p>Alright, I finally figured this one out.</p> <p>My ReferenceError was not a result of my methods, but rather a fundamental misunderstanding on my part of the implementation of DropDown objects. The fix was simply </p> <pre><code>&lt;DayDropDown&gt;: drop: drop.__self__ ... </code></pre> <p>This took me on...
0
2016-10-14T19:25:53Z
[ "python", "kivy" ]
Python logging: Best way to organize logs in different files?
39,924,599
<p>I have different loggers (log1, log2, log3, ..., logN) which are being logged to "registry.log" for a big N. I would like to divide "registry.log" into N different files as "registry.log" can become really large.</p> <p>Is there a way to accomplish this automatically, for instance, with a rotating handler?</p>
0
2016-10-07T19:33:35Z
39,930,135
<p>Create a <code>logging.Handler</code> subclass which determines which file to write to based on the details of the event being logged, and write the formatted event to that file.</p>
0
2016-10-08T08:01:01Z
[ "python", "logging", "rotation", "handler", "hierarchy" ]
Mezzanine overextends() template tag examples?
39,924,647
<p>I've been searching but there no examples of Mezzanine overextends()template tag, which allows you to extend a template with the same name. Does anybody know?</p>
0
2016-10-07T19:37:10Z
39,924,841
<p>While we still support django-1.8, note that <code>overextends</code> is deprecated because starting in django-1.9, <code>extends</code> supports recursive template extension.</p> <p>There are several examples you can check out in my project <a href="https://github.com/ryneeverett/cartridge-downloads" rel="nofollow...
1
2016-10-07T19:51:10Z
[ "python", "django", "django-templates", "mezzanine" ]
regex match space forward slash and space ' / '
39,924,654
<p>Here is my string 'something / something else' I would like to match with regex everything up to <code>/</code> i.e space forward slash space again. Here is what I tried =<code>/.+?(?=\s//\s)/</code>, but it does not work. It says: 'pattern contains no capture groups'. I am using it with pandas extract function.</p>...
2
2016-10-07T19:37:48Z
39,924,709
<p>Not sure if I understand your requirements exactly, but this should do the trick:</p> <pre><code>(.*?)(?= \/ ) </code></pre> <p><a href="https://regex101.com/r/JJYyg0/1" rel="nofollow">Try it here</a></p> <p>You can replace the <code>*</code> with a <code>+</code> if there must be at least one character before <c...
3
2016-10-07T19:41:52Z
[ "python", "regex", "pandas" ]
regex match space forward slash and space ' / '
39,924,654
<p>Here is my string 'something / something else' I would like to match with regex everything up to <code>/</code> i.e space forward slash space again. Here is what I tried =<code>/.+?(?=\s//\s)/</code>, but it does not work. It says: 'pattern contains no capture groups'. I am using it with pandas extract function.</p>...
2
2016-10-07T19:37:48Z
39,924,755
<p>Do:</p> <pre><code>r'^([^/]+) / ' </code></pre> <ul> <li><code>^([^/]+)</code> matches everything upto the <code>/</code>, then <code>/</code> matches a space, then <code>/</code>, and then a space again. SO the captured group 1 will only have the portion upto the space before <code>/</code></li> </ul> <p><strong...
2
2016-10-07T19:44:26Z
[ "python", "regex", "pandas" ]
Initializing a list and appending in one line
39,924,711
<p>How can I initialize a list, if it is not already initialized and append to it in one line. For example,</p> <pre><code>function example(a=None): a = a or [] a.append(1) return another_function(a) </code></pre> <p>How can I combine those two statements in the function into one?</p> <p>I am looking for so...
0
2016-10-07T19:41:54Z
39,924,739
<pre><code>def example(a): return a + [1] if a else [1] &gt;&gt;&gt; example([1,2,3]) [1, 2, 3, 1] &gt;&gt;&gt; example([]) [1] </code></pre>
3
2016-10-07T19:43:16Z
[ "python" ]
PYSPARK : casting string to float when reading a csv file
39,924,742
<p>I'm reading a csv file to dataframe</p> <pre><code>datafram = spark.read.csv(fileName, header=True) </code></pre> <p>but the data type in datafram is String, I want to change data type to float. Is there any way to do this efficiently?</p>
0
2016-10-07T19:43:33Z
39,925,215
<p>The most straightforward way to achieve this is by casting.</p> <pre><code>dataframe = dataframe.withColumn("float", col("column").cast("double")) </code></pre>
1
2016-10-07T20:21:00Z
[ "python", "apache-spark", "pyspark" ]
Is there a way to send (python) code to a server to compile and run but display the results on the computer that sent them?
39,924,750
<p>I just bought a server and was wondering if there was a way to run the code remotely but store/display the results locally. For example, I write some code to display a graph, the positions on the graph are computed by the (remote) server, but the graph is displayed on the (local) tablet. </p> <p>I would like to do ...
0
2016-10-07T19:44:07Z
39,924,860
<p>This is a complete "<a href="http://therussiansusedapencil.com/post/175863624/the-pencil" rel="nofollow">The Russians used a pencil</a>" solution, but have you considered running a VNC server on the machine that is doing the computations? </p> <p>You could install a VNC client onto your tablet/phone/PC and view it ...
0
2016-10-07T19:53:20Z
[ "python", "remote-access" ]
Is there a way to send (python) code to a server to compile and run but display the results on the computer that sent them?
39,924,750
<p>I just bought a server and was wondering if there was a way to run the code remotely but store/display the results locally. For example, I write some code to display a graph, the positions on the graph are computed by the (remote) server, but the graph is displayed on the (local) tablet. </p> <p>I would like to do ...
0
2016-10-07T19:44:07Z
39,924,876
<p>With ssh, you can do this with a python script or a shell script:</p> <p><code>ssh machine_name "python" &lt; ~/script/path/script.py</code></p> <p>REF: <a href="http://unix.stackexchange.com/questions/87405/how-can-i-execute-local-script-on-remote-machine-and-include-arguments">http://unix.stackexchange.com/quest...
0
2016-10-07T19:55:05Z
[ "python", "remote-access" ]
Code is correct, teacher approved, but it's not working. How do I make it run? (Python random module)
39,924,763
<p>This code is absolutely, 100% correct. It works on the teacher's computer and runs perfectly, but on mine it does not. I have no clue why that would be. The issue is the same on Mac and Windows (someone else had the same problem). I have Windows 8.1, if that's relevant, and I save all of my python files in Documents...
0
2016-10-07T19:45:12Z
39,924,986
<p>The reason of this weird behavior is the use of recursion and a while loop to call the same function.</p> <p>There are many ways to solve this; however, I recommend to get rid of the while loop entirely as it is confusing:</p> <pre><code>def addlist(): maxLengthList = int(input("How many students?")) turtl...
1
2016-10-07T20:05:46Z
[ "python", "random", "module", "python-module" ]
Code is correct, teacher approved, but it's not working. How do I make it run? (Python random module)
39,924,763
<p>This code is absolutely, 100% correct. It works on the teacher's computer and runs perfectly, but on mine it does not. I have no clue why that would be. The issue is the same on Mac and Windows (someone else had the same problem). I have Windows 8.1, if that's relevant, and I save all of my python files in Documents...
0
2016-10-07T19:45:12Z
39,925,088
<p>Maybe use the <code>random.randint(0,x)</code> to define what student you want, e.g. </p> <pre><code>print(students[random.randint(0,3)] </code></pre> <p>Not sure if this helps, another suggestion may be trying a simpler <code>print(random.randint(1,4)</code> in another project just to see if it is working?</p> <...
-1
2016-10-07T20:12:30Z
[ "python", "random", "module", "python-module" ]
Pygame: Creating a border
39,924,776
<p>I've been working on my school project which is a 2D game with a moveable player. I wish to create a border around the edge of the screen. I have read through several other articles but can't seem to wrap my mind around it. It would be great if someone could help me. Here is my program</p> <pre><code>import pygame ...
0
2016-10-07T19:45:36Z
39,924,952
<p>What you can do is that you can add 20 pixels to each width and height and draw a series of squares all around.</p> <pre><code>screen = pygame.display.set_mode((800 + 20, 600 + 20)) for x in range(0, 810, 10) pygame.draw.rect(surface, BLACK, [x, 0, 10, 10]) pygame.draw.rect(surface, BLACK, [x, 610, 10, 10...
1
2016-10-07T20:03:00Z
[ "python", "python-2.7", "pygame" ]
Pygame: Creating a border
39,924,776
<p>I've been working on my school project which is a 2D game with a moveable player. I wish to create a border around the edge of the screen. I have read through several other articles but can't seem to wrap my mind around it. It would be great if someone could help me. Here is my program</p> <pre><code>import pygame ...
0
2016-10-07T19:45:36Z
39,926,876
<p>Try adding this to your main part before <code>player.draw(screen)</code>:</p> <pre><code>pygame.init() line_width = 10 width = 800 height = 600 #creates the screen screen = pygame.display.set_mode((width+line_width, height+line_width),0,32) screen.fill(white) # fill the screen with white # top line pygame.dr...
0
2016-10-07T23:01:16Z
[ "python", "python-2.7", "pygame" ]
python multiprocessing returning error 'module' object has no attribute 'myfunc'
39,924,862
<p>First off, I am very new to multiprocessing, and I can't seem to make a very simple and straightforward example work. This is the example I working with:</p> <pre><code>import multiprocessing def worker(): """worker function""" print 'Worker' return if __name__ == '__main__': jobs = [] for i i...
0
2016-10-07T19:53:51Z
39,925,567
<p>Anaconda doesn't like multiprocessing as explained <a href="http://stackoverflow.com/questions/32489352/multiprocessing-program-has-attributeerror-in-anaconda-notebook">in this</a> answer.</p> <p>From the answer:</p> <blockquote> <p>This is because of the fact that multiprocessing does not work well in the inte...
0
2016-10-07T20:47:50Z
[ "python", "multiprocessing", "python-2.x" ]
Finding if member function exists in a Boost python::object
39,924,912
<p>I'm using Boost Python to make C++ and Python operate together and I have a code that looks like this, creating an instance of a python object and calling one of its member functions.</p> <pre><code>bp::object myInstance; // ... myInstance is initialized bp::object fun = myInstance.attr("myfunction"); fun(); </code...
2
2016-10-07T19:59:08Z
39,925,047
<blockquote> <p>the call to <code>myInstance.attr("myfunction")</code> is successful even if the function does not exist</p> </blockquote> <p>Pretty sure it throws an <code>AttributeError</code>. </p> <blockquote> <p>Is there any way to check if the function exists without involving exception or calling the funct...
2
2016-10-07T20:09:33Z
[ "python", "c++", "boost", "boost-python" ]
Importing default sublime text commands into a custom command
39,924,917
<p>I'm writing a command that needs to copy the current file's path. Sublime Text already has a <a href="https://github.com/cj/sublime/blob/master/Default/copy_path.py" rel="nofollow">copy_path command</a> that achieves this. Is it possible to import that command into my command's file? I have tried <code>import copy_p...
0
2016-10-07T19:59:20Z
39,925,204
<p>To import the command you can write <code>from Default.copy_path import CopyPathCommand</code>. <em>However</em> it sounds as if you run the command for which you don't need to import it. Just write <code>self.view.run_command("copy_path")</code> inside your <code>TextCommand</code> and it will be executed.</p>
0
2016-10-07T20:20:19Z
[ "python", "sublimetext3", "sublimetext", "sublime-text-plugin" ]
How would I do a detailed walk-through of a factorial?
39,924,924
<pre><code>def factorial(x): if x == 0: return 1 else: return x * factorial(x - 1) print(factorial(3)) </code></pre> <p>How would I do a detailed walk-through with information on the stack at every call and show the data at every return?</p> <p>I know I have to draw 3 boxes to show what happ...
0
2016-10-07T20:00:14Z
39,925,010
<p>You can try to add some <code>print</code> lines to know what's happening inside a function call. Such as the following:</p> <pre><code>def factorial(x): print("factorial({}) is called".format(x)) if x == 0: print("Reached base branch") return 1 else: print("Reached recursive bra...
0
2016-10-07T20:07:09Z
[ "python", "recursion", "stack", "factorial" ]
Programming error column does not exist
39,924,967
<p>models.py </p> <pre><code>class PlansToLodge(models.Model): sm_sequence = models.IntegerField() sm_year = models.IntegerField() location = models.TextField(blank=True, null=True) car_number = models.CharField(max_length=100, blank=True, null=True) client_or_owner = models.TextField(blank=True, null=True) date_r...
0
2016-10-07T20:04:20Z
39,926,597
<p>Actually this error occure because your database is not migrated</p> <p>So run following command to migrate database</p> <pre><code>python manage.py migrate </code></pre> <p>If this is not run then run following command</p> <pre><code>python manage.py makemigrations python manage.py migrate </code></pre>
1
2016-10-07T22:23:55Z
[ "python", "django", "postgresql", "object", "models" ]
How to run Threads synchronously with Python?
39,924,981
<p>I need to use 3 threads to print array items sequentially using Python.</p> <p>Each Thread will print one array item.</p> <p>I need the threads to sleep for a random number of seconds and then print the item.</p> <p>This function will be executed N times. This N value is given by the user.</p> <p>The items must ...
-1
2016-10-07T20:05:29Z
39,925,055
<p>There are many, many approaches to this. A simple one is to use a shared <a href="https://docs.python.org/2/library/queue.html" rel="nofollow">Queue</a> of numbers.</p> <p>Each thread can sleep for however long it wants to, take a number from the queue when it wakes up, and print it. They will come out in the order...
1
2016-10-07T20:09:51Z
[ "python", "multithreading" ]
How to run Threads synchronously with Python?
39,924,981
<p>I need to use 3 threads to print array items sequentially using Python.</p> <p>Each Thread will print one array item.</p> <p>I need the threads to sleep for a random number of seconds and then print the item.</p> <p>This function will be executed N times. This N value is given by the user.</p> <p>The items must ...
-1
2016-10-07T20:05:29Z
39,925,289
<p>If you didn't care about order you could just use a lock to synchronize access. In this case, though, how about a list of events. Each thread gets its own event slot and hands it to the next event in the list when done. This scheme could be fancied up by returning a context manager so that you don't need to release ...
0
2016-10-07T20:26:45Z
[ "python", "multithreading" ]
Having problems parsing numerical command-line arguments
39,925,069
<p>I am making a super simple program that strips even or odd numbers from a string given on the command line. For example:</p> <pre><code>$ test.py 1 1234 13 $ test.py 2 1234 24 </code></pre> <p>The problem is I can't get it to work. It prints the usage instead of the expected numbers.</p> <pre><code>$ test.py 1 12...
-2
2016-10-07T20:11:13Z
39,925,134
<p><code>sys.argv[1] == 1</code> is not possible. You mean: <code>sys.argv[1] == "1"</code>. Those are strings, not numbers.</p> <p>Your argument parsing would require some cleaning. No need for all those checks and exceptions to do such a simple task.</p> <p>Allow me to "code review" &amp; fix your code (I focused o...
4
2016-10-07T20:15:41Z
[ "python" ]
Having problems parsing numerical command-line arguments
39,925,069
<p>I am making a super simple program that strips even or odd numbers from a string given on the command line. For example:</p> <pre><code>$ test.py 1 1234 13 $ test.py 2 1234 24 </code></pre> <p>The problem is I can't get it to work. It prints the usage instead of the expected numbers.</p> <pre><code>$ test.py 1 12...
-2
2016-10-07T20:11:13Z
39,925,357
<p>Unlike the OP and one other answer so far, I don't see why you would compute both the odd and even lists knowing you'll only need one of them -- it's short distance from "simple" to "simply inefficient". How about we delay the "hard work" of thinning the lists until we've finished the "easy work" of decoding the ar...
1
2016-10-07T20:31:08Z
[ "python" ]
Why SQLAlchemy send extra SELECTs when accessing a persisted model property
39,925,074
<p>Given a simple declarative based class;</p> <pre><code>class Entity(db.Model): __tablename__ = 'brand' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255), nullable=False) </code></pre> <p>And the next script</p> <pre><code>entity = Entity() entity.name = 'random name' db.se...
0
2016-10-07T20:11:45Z
39,926,948
<p>By default, SQLAlchemy expires objects in the session when you commit. This is controlled via the <a href="http://docs.sqlalchemy.org/en/latest/orm/session_api.html#sqlalchemy.orm.session.Session.params.expire_on_commit" rel="nofollow"><code>expire_on_commit</code></a> parameter.</p> <p>The reasoning behind this is...
0
2016-10-07T23:09:58Z
[ "python", "sqlalchemy", "flask-sqlalchemy" ]
Flask web development. No module named 'MySQLdb'
39,925,076
<p>I'm working with Flask following Miguel Grinberg's book at the moment. i've reached the part where i need to interact with MySQL. i've checked everything and yet when i try to create the actual database with the command:</p> <p>db.create_all()</p> <p>i get an error saying "No module named 'MySQLdb'". i've tried in...
-1
2016-10-07T20:11:55Z
39,926,237
<p>solved it. needed to install mysqlclient via pip in the virtual environment. mySQL-python apparently doesn't work with python3</p>
0
2016-10-07T21:45:54Z
[ "python", "mysql", "flask" ]
Problems while applying a function to each element's content of a directory in python?
39,925,118
<p>I am trying to obtain the content of several .pdf files from a directory in order to transform them to text with tika library, however I believe that I am not reading the .pdf file objects correctly. This is what I tried so far:</p> <p>Input:</p> <pre><code>for filename in sorted(glob.glob(os.path.join(input_direc...
1
2016-10-07T20:14:24Z
39,925,250
<p>The tika parser receives a path and opens the file itself:</p> <pre><code>for filename in sorted(glob.glob(os.path.join(input_directory, '*.pdf'))): parsed = parser.from_file(filename) text = parsed['content'] </code></pre>
1
2016-10-07T20:23:19Z
[ "python", "python-3.x", "pdf", "io", "ipython-parallel" ]
Running a python program with cron, Docker and Supervisor
39,925,138
<p>When I run build the container with the CMD as <code>CMD /usr/bin/python3 /app/test.py</code> everything runs fine and I see an output, but when I run the CMD as <code>CMD ["/usr/bin/supervisord", "-n"]</code> which runs supervisor and cron, I see not output. It seems like the python file is not running, or i'm no...
-1
2016-10-07T20:16:13Z
40,108,168
<p>You're missing the <code>PATH</code> environment variable declaration, which is causing your Python app to not run. Editing your Dockerfile to the following should fix the issue for you:</p> <pre><code>FROM ubuntu:16.04 ENV PATH /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin # This is the line that m...
0
2016-10-18T12:23:10Z
[ "python", "docker", "cron", "supervisord" ]
obtaining pre-signed request from heroku
39,925,157
<p>I'm looking at the heroku documentation (<a href="https://devcenter.heroku.com/articles/s3-upload-python" rel="nofollow">https://devcenter.heroku.com/articles/s3-upload-python</a>) about making a direct upload to S3 using a pre-signed request from heroku. </p> <p>For the code below, are you expected to send the ac...
0
2016-10-07T20:17:16Z
39,934,319
<p>The code you posted uses only the file name and type to generate an S3 pre-signed URL, so it's not using the file.</p> <p>Once the server generates this S3 URL, it will send it to the client so it can use this URL to upload the file.</p> <p>So the answer is no, your file is not sent to Heroku, just the file info. ...
0
2016-10-08T15:47:16Z
[ "python", "heroku", "amazon-s3" ]
Try Statement Error
39,925,214
<p>I am new to Python and I am importing Excel data into postgreSQL. I have blank whitespaces in my Excel for the columns for Traffic and Week_Ending. The Try statement seems to function fine for the Week_Ending but for the Traffic it throws out an error. I checked the Excel and the error is showing up due to the singl...
0
2016-10-07T20:20:59Z
39,925,440
<p>You should be checking for a blank or empty string in that column:</p> <pre><code>traffic = sheet.cell(r, 1).value </code></pre> <p>I don't see in your code how you're actually executing the query but you should wrap traffic in int to parse an integer from a string: <a href="http://stackoverflow.com/questions/6421...
0
2016-10-07T20:37:48Z
[ "python", "excel" ]
AttributeError: module 'pkg_resources' has no attribute 'safe_name' oauthlib install
39,925,227
<p>I'm trying to install tweepy (and by extension oauthlib), and I'm getting the following error when attempting to install:</p> <pre><code>Collecting requests-oauthlib&gt;=0.4.1 (from tweepy) Using cached requests_oauthlib-0.7.0-py2.py3-none-any.whl Collecting oauthlib&gt;=0.6.2 (from requests-oauthlib&gt;=0.4.1-&gt;...
1
2016-10-07T20:22:05Z
39,930,983
<p>Found the solution. I had to upgrade setuptools, so: </p> <pre><code>$ sudo pip install --upgrade setuptools </code></pre>
0
2016-10-08T09:50:24Z
[ "python" ]
Extracting multiple lines of strings
39,925,258
<h2>Update:</h2> <p>I spoke to a colleague about this and we came up with the following solution...</p> <pre><code>#!/usr/bin/python python in_file = open("small-output.txt", "rt") with open("output-new.txt", "wt") as txtfile: sentence = "" hit = False for each in in_file: if each.strip() == "De...
1
2016-10-07T20:23:52Z
39,926,295
<pre><code>sed -n '/^Title$/,/^Description$/{//d;p}' file </code></pre> <p>outputs</p> <pre><code>This is the title of the thing. </code></pre>
0
2016-10-07T21:51:55Z
[ "python", "csv", "awk", "sed" ]
Python Loop that gets html tags returning empty list instead of tags
39,925,262
<p>So I'm trying to make a function that will go through a list of html tags in a list as characters and return the tags. An example would be it would go through a list like below</p> <p>['&lt;', 'h', 't', 'm', 'l', '>', '&lt;', 'h', 'e', 'a', 'd', '>', '&lt;', 'm', 'e', 't', 'a', '>']</p> <p>and return a list like t...
0
2016-10-07T20:24:12Z
39,925,312
<p>I'm going to assume this is just an exercise for the sake of learning. Python has much better tools for parsing HTML (<a href="https://www.crummy.com/software/BeautifulSoup/" rel="nofollow">https://www.crummy.com/software/BeautifulSoup/</a>) or strings (<a href="https://docs.python.org/2/library/re.html" rel="nofoll...
0
2016-10-07T20:28:29Z
[ "python", "html", "list", "if-statement", "for-loop" ]
Python Loop that gets html tags returning empty list instead of tags
39,925,262
<p>So I'm trying to make a function that will go through a list of html tags in a list as characters and return the tags. An example would be it would go through a list like below</p> <p>['&lt;', 'h', 't', 'm', 'l', '>', '&lt;', 'h', 'e', 'a', 'd', '>', '&lt;', 'm', 'e', 't', 'a', '>']</p> <p>and return a list like t...
0
2016-10-07T20:24:12Z
39,925,315
<p>That looks too complicated. Instead, join the list into a string, remove the opening angle brackets, and split on the closing angle brackets, remembering to discard the empty strings:</p> <pre><code>def get_tag(l): return [item for item in ''.join(l).replace('&lt;','').split('&gt;') if item] </code></pre> <p>R...
1
2016-10-07T20:28:43Z
[ "python", "html", "list", "if-statement", "for-loop" ]
Python Loop that gets html tags returning empty list instead of tags
39,925,262
<p>So I'm trying to make a function that will go through a list of html tags in a list as characters and return the tags. An example would be it would go through a list like below</p> <p>['&lt;', 'h', 't', 'm', 'l', '>', '&lt;', 'h', 'e', 'a', 'd', '>', '&lt;', 'm', 'e', 't', 'a', '>']</p> <p>and return a list like t...
0
2016-10-07T20:24:12Z
39,925,436
<p>I think <code>re</code> would be a good choice.</p> <pre><code>def get_tag(l): return re.findall(r'&lt;([a-z]+)&gt;', ''.join(l)) get_tag(l) ['html', 'head', 'meta'] </code></pre>
0
2016-10-07T20:37:41Z
[ "python", "html", "list", "if-statement", "for-loop" ]
Python Loop that gets html tags returning empty list instead of tags
39,925,262
<p>So I'm trying to make a function that will go through a list of html tags in a list as characters and return the tags. An example would be it would go through a list like below</p> <p>['&lt;', 'h', 't', 'm', 'l', '>', '&lt;', 'h', 'e', 'a', 'd', '>', '&lt;', 'm', 'e', 't', 'a', '>']</p> <p>and return a list like t...
0
2016-10-07T20:24:12Z
39,925,449
<p>Your code is <strong>nearly correct</strong>, you only need to replace all appearance of <code>character</code> in the inner loop with <code>word</code>; <code>word</code> was never used in that inner loop:</p> <pre><code> ... for index, word in enumerate(htmlList): if index &gt; iterate:...
0
2016-10-07T20:38:37Z
[ "python", "html", "list", "if-statement", "for-loop" ]
Flask test doesn't populate request.authorization when username and password are URL encoded
39,925,335
<p>I'm trying to use the following test: </p> <pre><code>def post_webhook(self, payload, **kwargs): webhook_username = 'test' webhook_password = 'test' webhook_url = 'http://{}:{}@localhost:8000/webhook_receive' webhook_receive = self.app.post( webhook_url.format(webhook_username, webhook_pass...
0
2016-10-07T20:29:54Z
39,925,521
<p>Using the <a href="http://flask.pocoo.org/snippets/8/" rel="nofollow">snippet</a> code and the <a href="http://flask.pocoo.org/docs/0.11/testing/#testing" rel="nofollow">Flask Test Client</a>, the next pytest code works for me. The way I send the HTTP Basic Auth is the same way curl and HTTPie send it; in the <stron...
1
2016-10-07T20:43:40Z
[ "python", "testing", "flask" ]
Django: Dynamic inline forms with filter upon user selection
39,925,382
<p>I have created these models:</p> <pre><code>class Service(models.Model): name = models.CharField(blank=False, max_length=200)code here class Monitor(models.Model): name = models.CharField(blank=False, max_length=100) services = models.ManyToManyField(Service, related_name='monitors') class Student(mod...
1
2016-10-07T20:34:01Z
39,925,507
<p>This likely can not be managed within the Django forms framework which is very limited in functionality. It allows you to use a filtered queryset for selections in a ModelChoiceDropDown (I think that's the name) but filtering after a selection isn't possible this way. Django's forms are generated and sent as HTML wh...
0
2016-10-07T20:43:02Z
[ "python", "django", "forms", "inline-formset" ]
Bizzare matplotlib behaviour in displaying images cast as floats
39,925,420
<p>When a regular RGB image in range (0,255) is cast as float, then displayed by matplotlib, the image is displayed as negative. If it is cast as uint8, it displays correctly (of course). It caused me some trouble to figure out what was going on, because I accidentally cast one of images as float. </p> <p>I am well aw...
2
2016-10-07T20:36:31Z
39,925,945
<p>I think you are on a wrong path here as you are claiming, that <code>np.random.randint()</code> should return an float-based array. <strong>It does not!</strong> (<a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.randint.html" rel="nofollow">docs</a>)</p> <p><strong>This means</strong>:</p> ...
1
2016-10-07T21:18:38Z
[ "python", "matplotlib" ]
Bizzare matplotlib behaviour in displaying images cast as floats
39,925,420
<p>When a regular RGB image in range (0,255) is cast as float, then displayed by matplotlib, the image is displayed as negative. If it is cast as uint8, it displays correctly (of course). It caused me some trouble to figure out what was going on, because I accidentally cast one of images as float. </p> <p>I am well aw...
2
2016-10-07T20:36:31Z
39,936,311
<p>In the sources, in <code>image.py</code>, in the <code>AxesImage</code> class (what <code>imshow</code> returns) a method <code>_get_unsampled_image</code> is called at some point in the drawing process. The relevant code starts on line 226 for me (matplotlib-1.5.3):</p> <pre><code>if A.dtype == np.uint8 and A.ndim...
1
2016-10-08T19:09:28Z
[ "python", "matplotlib" ]
join/search/sum in Pandas Python
39,925,423
<p>i'm new to Panda and trying to learn it, I have a DataFrame in Panda with 3 different columns:</p> <pre><code> a b c ----------------------------- ' Alice 5/5/2014 2 ' ' Bob 7/18/2014 1 ' ' Alice 5/5/2014 3 ' ' Bob 8/10/2014 5 ' -----------------------...
2
2016-10-07T20:36:47Z
39,925,456
<p>add a column specifying the month</p> <pre><code>df['month'] = df['b'].month # assuming it's a datetime object </code></pre> <p>then groupby and sum</p> <pre><code>df.groupby(['a','month']).sum() </code></pre>
0
2016-10-07T20:39:07Z
[ "python", "pandas" ]
join/search/sum in Pandas Python
39,925,423
<p>i'm new to Panda and trying to learn it, I have a DataFrame in Panda with 3 different columns:</p> <pre><code> a b c ----------------------------- ' Alice 5/5/2014 2 ' ' Bob 7/18/2014 1 ' ' Alice 5/5/2014 3 ' ' Bob 8/10/2014 5 ' -----------------------...
2
2016-10-07T20:36:47Z
39,925,482
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow">groupby</a> function like:</p> <pre><code>df.groupby(['a', 'b']).sum() </code></pre> <blockquote> <p>Group series using mapper (dict or key function, apply given function to group, return resu...
0
2016-10-07T20:40:55Z
[ "python", "pandas" ]
join/search/sum in Pandas Python
39,925,423
<p>i'm new to Panda and trying to learn it, I have a DataFrame in Panda with 3 different columns:</p> <pre><code> a b c ----------------------------- ' Alice 5/5/2014 2 ' ' Bob 7/18/2014 1 ' ' Alice 5/5/2014 3 ' ' Bob 8/10/2014 5 ' -----------------------...
2
2016-10-07T20:36:47Z
39,925,716
<p>The most efficient way is to first make sure your date column is of a <code>datetime</code> type:</p> <pre><code>&gt;&gt;&gt; df2 a b c 0 Alice 5/5/2014 2 1 Bob 7/18/2014 1 2 Alice 5/9/2014 3 3 Bob 8/10/2014 5 &gt;&gt;&gt; df2['b'] = pd.to_datetime(df2.b) </code></pre> <p>Then, i...
3
2016-10-07T20:59:08Z
[ "python", "pandas" ]
Keras custom metric gives incorrect tensor shape
39,925,462
<p>I want to monitor the dimension of <code>y_pred</code> by defining my own custom metric (using the Theano backend)</p> <pre><code>def shape_test(y_true, y_pred): return K.shape(y_pred)[0] </code></pre> <p>I was assuming that the dimension of <code>y_pred</code> in the custom metric function is equal to the min...
1
2016-10-07T20:39:25Z
39,930,509
<p>Using <code>neuron_num=2000</code> and <code>verbose=True</code>, here is what I was able to produce with your example:</p> <pre><code>Epoch 1/1 2048/5000 [========&gt;............] - ETA: 9s - loss: 1.4507 - shape_test: 2048.000 4096/5000 [=================&gt;...] - ETA: 3s - loss: 1.3577 - shape_test: 2048.000 5...
1
2016-10-08T08:54:26Z
[ "python", "python-2.7", "theano", "keras" ]
Indexing a ndarray - 1 item is stored differently to >1
39,925,512
<p>I'm using <code>genfromtxt</code> to import data from a txt file.</p> <p>This data is imported into an ndarray, as per <code>genfromtxt</code></p> <p>Normally, this text file has many lines of data to inport, meaning that the ndarray is like this:</p> <pre><code>array([ ('2016-04-17T00:08:42.273000Z', '2016-04-17...
0
2016-10-07T20:43:07Z
39,925,958
<p>Numpy actually is loading in the file as an array, but it is a "0-dimensional" array. That is, <code>results.ndim</code> will return <code>0</code>. You can convert it to a 1-dimensional array with 1 element by doing <code>results.reshape((1,))</code>.</p> <p>If you are reading in a file and you don't know whether ...
1
2016-10-07T21:19:53Z
[ "python", "multidimensional-array", "indexing", "genfromtxt" ]
How to use regex to replace a particular field in a formatted file
39,925,562
<p>I have a file with following formatted file I need to parse</p> <pre><code>field_1 { field_2 { .... } field_i_want_to_replace { .... } .... } .... </code></pre> <p>I need a pre-processor in python to parse those files and delete the content of some particular fields. In the abov...
0
2016-10-07T20:47:31Z
39,925,787
<p>Your <code>.</code> character is not matching any newlines, so it will not continue after the left curly bracket.</p> <p>To change this behavior, just add the <a href="https://docs.python.org/2/library/re.html#re.DOTALL" rel="nofollow"><code>re.DOTALL</code> flag</a> (or <code>re.S</code>) as a keyword arg to your ...
2
2016-10-07T21:05:11Z
[ "python", "regex" ]
Server/Client application TimeoutError on LAN
39,925,658
<p>I have two programs: server.py and client.py. I need to be able to use server.py in my main PC, and client.py from my laptop. When I run them, I get the following error from client.py:</p> <pre><code>TimeoutError: [WinError 10060] </code></pre> <p>I have disabled firewalls in both my PC (that runs Windows 7) and m...
1
2016-10-07T20:54:36Z
39,925,933
<p>You just need to change the <code>localhost</code> or <code>socket.gethostname()</code> in the <code>server.py/client.py</code> scripts to the actual <strong>internal ip</strong> address of the server. Then it will work! </p> <p>If you want to learn more why this happens I recommend reading <a href="http://superuse...
1
2016-10-07T21:17:18Z
[ "python", "sockets", "networking", "lan" ]
Subprocess call bash script
39,925,659
<p>Im trying to call a python class which contains a subprocess call for a bashscript.</p> <pre><code>def downloadURL(self,address): call(['bash youtube2mp3_2.sh', str(address)],shell=True) </code></pre> <p>This is the bash script:</p> <pre><code>#!/bin/bash # Script for grabbing the audio of youtube video...
0
2016-10-07T20:54:38Z
39,925,706
<p>either you pass the arguments as a string</p> <pre><code>def downloadURL(self,address): call('bash youtube2mp3_2.sh '+address) </code></pre> <p>or as a list</p> <pre><code>def downloadURL(self,address): call(['bash','youtube2mp3_2.sh',address]) </code></pre> <p>both work, but the latter is better...
2
2016-10-07T20:58:07Z
[ "python", "bash", "youtube-dl" ]