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 do I create a "dummy" module object?
38,687,075
<p>Suppose I have a function that takes a module object as an argument and does something to it -- maybe monkeypatches it. For testing purposes, how do I create a dummy module object to pass to it?</p>
2
2016-07-31T18:20:47Z
38,687,085
<p>Like this (<a href="https://docs.python.org/3/library/types.html#types.ModuleType" rel="nofollow">docs</a>)</p> <pre><code>&gt;&gt;&gt; import types &gt;&gt;&gt; types.ModuleType('my_module') &lt;module 'my_module'&gt; </code></pre>
1
2016-07-31T18:21:59Z
[ "python", "python-3.x" ]
Program to read multiple URLs and generate a word (Should only contains alphanumeric) frequency table
38,687,095
<p>I am writing a Python program to read multiple URLs and generate a word (a word only contains letters A-Za-z0-9) frequency table. Output can be stored in files with names url1.txt, url2.txt</p> <p>This is what i have so far:</p> <pre><code>import urllib2 import obo url = 'sample url' response = urllib2.urlopen(u...
-1
2016-07-31T18:22:37Z
38,687,169
<p>You can use boilerpipe to easily extract the text: <a href="https://github.com/misja/python-boilerpipe" rel="nofollow">https://github.com/misja/python-boilerpipe</a>.</p> <p>The code might look like this: </p> <pre><code>from boilerpipe.extract import Extractor from collections import Counter urls = ['url1', 'url...
0
2016-07-31T18:31:54Z
[ "python" ]
how does Python handle "from __future__ import division"?
38,687,131
<p>I've looked at the <a href="https://hg.python.org/cpython/file/2.7/Lib/__future__.py" rel="nofollow">source code for __future__.py</a> and it makes no sense to me -- how does this actually work, to change the behavior of division?</p>
1
2016-07-31T18:26:13Z
38,687,330
<p>That module only serves a documentary / introspection purpose; none of the code in it actually <em>does</em> anything.</p> <p>Rather, when Python is compiling a module, it calls <a href="https://hg.python.org/cpython/file/2.7/Python/compile.c#l272" rel="nofollow">PyFuture_FromAST</a> on the module, which checks for...
3
2016-07-31T18:48:12Z
[ "python" ]
Why python is "shy" to use memory in docker?
38,687,134
<p>I'm running a memory intensive python script (pandas, numpy, machine learning) in docker and performance is terrible.</p> <p>In my host machine the script uses more than 10GB of RAM. The dockerized python script uses only 3Gb (com.docker.hyperkit process). I have already changer my docker memory preferences to 10gb...
-1
2016-07-31T18:26:59Z
38,687,403
<p>Computer programs use other resources besides memmory. There's CPU, I/O devices and information. I would guess that this behavior you're seeing is the result of other resource been exausted. For instance, your I/O device could be causing a bottleneck before memmory is filled up. This is just a guess, because I have ...
1
2016-07-31T18:57:50Z
[ "python", "docker" ]
How to process python dictionary items in the order of value item?
38,687,261
<p>I get the following JSON from a web service. How to get an ordered collection from the following JSON in Python. I want to process key value pairs in the ascending order of "order" number.</p> <pre><code>{ "key1": { "order": 10, "name": "somenameZ" }, "key2": { "order": 3, "name": "somenameY" ...
0
2016-07-31T18:39:27Z
38,687,286
<p>Sort the <code>dict.items()</code> result with a custom key:</p> <pre><code>ordered = sorted(outerdict.items(), key=lambda kv: kv[1]['order']) for key, item in ordered: # ... </code></pre> <p>If you only need the nested dictionaries, and not the outer keys, you could do the same for <code>dict.values()</code>:...
3
2016-07-31T18:42:06Z
[ "python", "json", "sorting", "dictionary" ]
Counting how many times a row occurs in a matrix (numpy)
38,687,292
<p>Is there a better way to count how many times a given row appears in a numpy 2D array than</p> <pre><code>def get_count(array_2d, row): count = 0 # iterate over rows, compare for r in array_2d[:,]: if np.equal(r, row).all(): count += 1 return count # let's make sure it works...
4
2016-07-31T18:42:54Z
38,687,313
<p>One simple way would be with <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow"><code>broadcasting</code></a> -</p> <pre><code>(array_2d == row).all(-1).sum() </code></pre> <hr> <p>Considering memory efficiency, here's one approach considering each row from <code>array_2d</code...
3
2016-07-31T18:46:07Z
[ "python", "numpy" ]
Text file does not get opened in output window.Python (Pycharm IDE)
38,687,319
<p>So I just began learning Python and after making a file named myfile.txt I tried running this bit of code</p> <pre><code>def Main(): f=open("myfile.txt","r") for line in f: print(line) f.close() if __name__ =="__main__": Main() </code></pre> <p>The file doesn't open , I'm just ...
1
2016-07-31T18:47:05Z
38,687,337
<p>deindent the <code>if</code></p> <pre><code>def Main(): f=open("myfile.txt","r") for line in f: print(line) f.close() if __name__ =="__main__": Main() </code></pre> <p>The <code>if</code> was part of your <code>Main</code> function, so you had a recursive function when the the conditio...
1
2016-07-31T18:49:18Z
[ "python", "file-io", "pycharm" ]
Text file does not get opened in output window.Python (Pycharm IDE)
38,687,319
<p>So I just began learning Python and after making a file named myfile.txt I tried running this bit of code</p> <pre><code>def Main(): f=open("myfile.txt","r") for line in f: print(line) f.close() if __name__ =="__main__": Main() </code></pre> <p>The file doesn't open , I'm just ...
1
2016-07-31T18:47:05Z
38,687,385
<p>First you need to make sure you indentions are correct. You should not close the file when inside the loop, so it's to much indented. And to run the program your <code>if __name__ =="__main__":</code> must be defined outside the function. Try this: </p> <pre><code>def main(): f = open("myfile.txt","r") for...
3
2016-07-31T18:55:49Z
[ "python", "file-io", "pycharm" ]
How to run custom seq2seq learning (using pre-calculated word embeddings) encoder-decoder in Tensorflow?
38,687,369
<p>I need to run a encoder-decoder model in Tensorflow. I see that using the available APIs <code>basic_rnn_seq2seq(encoder_input_data, decoder_input_data, lstm_cell)</code> etc, a encoder-decoder system can be created.</p> <ol> <li>How can we enter the embeddings such as word2vec in such model? I am aware that we can...
0
2016-07-31T18:53:56Z
38,700,227
<p>First question: Probably not the best way, but what I did was, after building the model, before training starts:</p> <pre><code>for v in tf.trainable_variables(): if v.name == 'embedding_rnn_seq2seq/RNN/EmbeddingWrapper/embedding:0': assign_op = v.assign(my_word2vec_matrix) session.run(assign_op) # or `a...
2
2016-08-01T13:31:13Z
[ "python", "tensorflow", "deep-learning", "lstm", "language-model" ]
Tkinter Loop Never Exits Cleanly
38,687,396
<p>Python 2.7</p> <p>I have written a <code>run</code> method for my Tkinter GUI rather than using the standard <code>mainloop</code>, and it always exits on an error when I close the window, even after implementing a <code>WM_DELETE_WINDOW</code> protocol as advised elsewhere on SO. I tried invoking <code>exit</code...
0
2016-07-31T18:56:52Z
38,729,490
<p>Without the mainloop, tkinter cannot get the <code>WM_DELETE_WINDOW</code> message to call your exit function. (Or rather, it can only catch anything during the ~millisecond of the <code>update_idletasks</code> call, as it won't queue since tkinter doesn't have an event loop (and thus queue) going since you never st...
1
2016-08-02T20:03:29Z
[ "python", "python-2.7", "tkinter", "tkinter-canvas", "event-loop" ]
I try to create and SQL table that contains 10000 rows from random elements. It gives me an error
38,687,476
<p>I'm trying to create an SQL table, it runs by this (this is in and SQL file, what I call in the end of my code '1-fake-mentor-candidates.sql')</p> <pre><code>CREATE TABLE "mentor_candidates" ( first_name varchar(255) NOT NULL, last_name varchar(255) NOT NULL, phone_number varchar(100) NOT NULL, emai...
0
2016-07-31T19:05:50Z
38,687,590
<p>You tried to access instance attributes in a classmethod. You need to create instances:</p> <pre><code>class FakeMentors: first_name_to_pick = ['Attila', 'Prezmek', 'John', 'Tim', 'Matthew', 'Andy', 'Giancarlo'] last_name_to_pick = ['Monoczki', 'Szodoray', 'Ciacka', 'Carrey', 'Obama', 'Lebron', 'Hamilton', ...
1
2016-07-31T19:18:59Z
[ "python", "postgresql" ]
Add current element in array + next element in array while iterating through array in Python
38,687,480
<p>What's the best way to add the first element in an array to the next element in the same array, then add the result to the next element of the array, and so on? For example, I have an array:</p> <pre><code>s=[50, 1.2658, 1.2345, 1.2405, 1.2282, 1.2158, 100] </code></pre> <p>I would like the end array to look like ...
1
2016-07-31T19:06:09Z
38,687,502
<p>The beset way is using <code>numpy.cumsum()</code> for all of your items except the last one then append the last one to the result of <code>cumsum()</code>:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; s=[50, 1.2658, 1.2345, 1.2405, 1.2282, 1.2158, 100] &gt;&gt;&gt; &gt;&gt;&gt; np.append(np.cumsum...
1
2016-07-31T19:08:54Z
[ "python", "arrays" ]
Add current element in array + next element in array while iterating through array in Python
38,687,480
<p>What's the best way to add the first element in an array to the next element in the same array, then add the result to the next element of the array, and so on? For example, I have an array:</p> <pre><code>s=[50, 1.2658, 1.2345, 1.2405, 1.2282, 1.2158, 100] </code></pre> <p>I would like the end array to look like ...
1
2016-07-31T19:06:09Z
38,687,539
<p>You can use <code>numpy.cumsum()</code>:</p> <pre><code>import numpy as np np.append(np.cumsum(s[:-1]), s[-1]) # array([50., 51.2658, 52.5003, 53.7408, 54.969 , 56.1848, 100.]) </code></pre>
1
2016-07-31T19:12:14Z
[ "python", "arrays" ]
How to use Faker from Factory_boy
38,687,492
<p><code>Factory_boy</code> uses <code>fake-factory (Faker)</code> to generate random values, I would like to generate some random values in my Django tests using Faker directly.</p> <p>Factory_boy docs suggests using <code>factory.Faker</code> and its provider as :</p> <pre><code>class RandomUserFactory(factory.Fact...
0
2016-07-31T19:07:09Z
38,720,172
<p>You can use faker with factory_boy like this:</p> <pre><code>class RandomUserFactory(factory.Factory): class Meta: model = models.User first_name = factory.Faker('first_name') user = RandomUserFactory() print user.first_name # 'Emily </code></pre> <p>So you need to instantiate a user with factor...
0
2016-08-02T12:15:47Z
[ "python", "factory", "django-testing", "faker", "factory-boy" ]
ImportError: No module named rl.algorithms.deepq
38,687,495
<p>I cloned the repo from here: <a href="https://github.com/wingedsheep/rl" rel="nofollow">https://github.com/wingedsheep/rl</a></p> <p>I now tried to run the code, </p> <pre><code>cd rl python examples/runner_lunarlander.py </code></pre> <p>I get the error:</p> <pre><code>Traceback (most recent call last): File ...
0
2016-07-31T19:07:37Z
38,687,832
<p>Your are getting this error because the module (code) you're trying to run is not on your python's PYTHONPATH. PYTHONPATH environment variable is responsible to update and inform python where to look for imports. There are lot of ways for setting it. </p> <p>You could add this in your ~/.bashrc file for more perman...
0
2016-07-31T19:49:27Z
[ "python", "python-2.7", "import", "anaconda" ]
Django1.9: No model matches the given query
38,687,572
<p>I am following a tutorial to create a blog. The code is correct according to the tutorial. The only difference is that I use Django 1.9 instead of 1.8</p> <p>Calling the <code>Post</code> model in the view without </p> <pre><code>publish__year=year, publish__month=month, publish__day=day) </code></pre> <p>doesn't...
0
2016-07-31T19:17:35Z
38,688,330
<p>As I got it, you can either change <code>self.publish.strftime('%m')</code> and <code>self.publish.strftime('%d')</code> to <code>self.publish.month</code> and <code>self.publish.day</code>, either you can convert passed data into int <code>publish__year=int(year), pub...
0
2016-07-31T20:54:32Z
[ "python", "django", "view", "model" ]
UnicodeDecodeError for Reading files in Python
38,687,591
<pre><code>pythonNotes = open('E:\\Python Notes.docx','r') read_it_now = pythonNotes.read() print(read_it_now.encode('utf-16')) </code></pre> <p>When I try this code, I get:</p> <p><code>UnicodeDecodeError: 'charmap' can't decode byte 0x8f in position 591 character maps to &lt;undefined&gt;</code></p> <p>I am runnin...
-1
2016-07-31T19:19:00Z
38,687,769
<p>This error <a href="http://www.i18nqa.com/debug/bug-double-conversion.html" rel="nofollow">can occur</a> when text that is already in utf-8 format is read in as an 8-bit encoding, and python tries to "decode" it to Unicode: Bytes that have no meaning in the supposed encoding throw a <code>UnicodeDecodeError</code>. ...
0
2016-07-31T19:42:06Z
[ "python" ]
Download entire directory via FTP using Python
38,687,599
<p>Trying to put together my first useful Python program, with the aim of automating my website backups. I watched a tutorial on how to download a single file, but when it comes to a folder I'm less clear. I'd like to create a local backup of an entire folder from my website via FTP.</p> <p>So far I have come up with ...
0
2016-07-31T19:19:57Z
38,687,671
<p>You don't need to change your working directory just save your files in your intended path.</p> <p>And for downloading the files you first need to get the list of file names:</p> <pre><code>file_list = [] ftp.retrlines('LIST', lambda x: file_list.append(x.split())) </code></pre> <p>Then separate the files, from d...
1
2016-07-31T19:30:05Z
[ "python", "ftp" ]
Trying to position plots next to each other
38,687,737
<p>I am trying to position two plots next to each other, but dont know how do it right. Could someone pls help me. </p> <p>This is the first plot</p> <pre><code>x_new = np.linspace(dsa[0], dsa[-1], num=len(dsa)*10) coefs = poly.polyfit(dsa, Wechsel, 1) ffit = poly.polyval(x_new, coefs) plt.grid(True) plt.xlabel("...
0
2016-07-31T19:37:13Z
38,687,790
<p>You can use <code>plt.subplots</code>:</p> <pre><code>f, (ax1, ax2) = plt.subplots(1, 2) x_new = np.linspace(dsa[0], dsa[-1], num=len(dsa)*10) coefs = poly.polyfit(dsa, Wechsel, 1) ffit = poly.polyval(x_new, coefs) ax1.grid(True) ax1.set_xlabel("Druck p in mbar") ax1.set_ylabel("Minimawechse...
0
2016-07-31T19:44:01Z
[ "python", "matplotlib" ]
Issue sending mail with smtp python
38,687,747
<p>I'm working in an app that sends an icalendar file to a mail and I've an issue with it. The main fact is that the app works in a properly way in all the cases except one. I've been testing the app with the wifi of my university (only students have acces to this wifi) and It couldn't be sent (the app enter in a loop ...
0
2016-07-31T19:38:36Z
38,688,154
<p>Turn on SMTP session debugging. It should provide some clues.</p> <p><a href="https://docs.python.org/3/library/smtplib.html#smtplib.SMTP.set_debuglevel" rel="nofollow">https://docs.python.org/3/library/smtplib.html#smtplib.SMTP.set_debuglevel</a></p>
0
2016-07-31T20:31:18Z
[ "python", "email", "smtp", "port", "icalendar" ]
Time difference in python not working for some dates
38,687,780
<p>I have this function to count difference between two timestamps in seconds.</p> <pre><code>def diffdates(d1, d2): diff = (time.mktime(time.strptime(d2,"%Y-%m-%dT%H:%M:%S")) - time.mktime(time.strptime(d1, "%Y-%m-%dT%H:%M:%S"))) pprint(d2) pprint(d1) pprint(diff) return diff diffdates(diffdate...
0
2016-07-31T19:43:11Z
38,687,831
<p>Your math is wrong. The delta between 16:00 and 11:10 is 4 hours 50 minutes. Your computation of <code>4*3600-10*60</code> is suggesting 3 hours 50 minutes. You're off by an hour.</p> <p><code>16:00</code> is <code>60*16</code> minutes into the day: <code>960</code></p> <p><code>11:10</code> is <code>60*11+10</...
1
2016-07-31T19:49:20Z
[ "python", "datetime" ]
Delete first row in Dataframe each day for certain value only
38,687,786
<p>Is there a way to delete the first row in a Dataframe, each day, for certain value only. So for example:</p> <pre><code>2014-03-04 10:00:00 -1.0 2014-03-04 10:04:00 1.0 2014-03-04 10:42:00 -1.0 2014-03-05 09:57:00 1.0 2014-03-05 10:05:00 -1.0 2014-03-05 10:30:00 1.0 </code></pre> <p>For each day a...
1
2016-07-31T19:43:41Z
38,687,889
<p>You can first <code>groupby</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DatetimeIndex.year.html" rel="nofollow"><code>DatetimeIndex.year</code></a> and aggregate <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.head.html" rel="nofollow"><c...
2
2016-07-31T19:57:59Z
[ "python", "pandas" ]
Delete first row in Dataframe each day for certain value only
38,687,786
<p>Is there a way to delete the first row in a Dataframe, each day, for certain value only. So for example:</p> <pre><code>2014-03-04 10:00:00 -1.0 2014-03-04 10:04:00 1.0 2014-03-04 10:42:00 -1.0 2014-03-05 09:57:00 1.0 2014-03-05 10:05:00 -1.0 2014-03-05 10:30:00 1.0 </code></pre> <p>For each day a...
1
2016-07-31T19:43:41Z
38,688,534
<p>Here is another method of creating a mask variable using <code>apply</code> method to check each group and pick up the condition of the first element, and then use the <code>mask</code> for subsetting:</p> <pre><code>import pandas as pd import numpy as np df['date_time'] = pd.to_datetime(df.date_time) df # ...
0
2016-07-31T21:25:32Z
[ "python", "pandas" ]
Serialize a string without changes in Django Rest Framework?
38,687,810
<p>I'm using Python's json.dumps() to convert an array to a string and then store it in a Django Model. I'm trying to figure out how I can get Django's REST framework to ignore this field and send it 'as is' without serializing it a second time.</p> <p>For example, if the model looks like this(Both fields are CharFiel...
0
2016-07-31T19:46:38Z
38,696,435
<p>I ended up using a wasteful and sickening method of deserializing the array before serializing it again with the REST framework:</p> <p><strong>Serializers.py:</strong></p> <pre><code>import json class PathWithIds(serializers.CharField): def to_representation(self, value): x = json.loads(value) ...
1
2016-08-01T10:23:18Z
[ "python", "json", "django", "serialization", "django-rest-framework" ]
Python, create shortcut with two paths and argument
38,687,822
<p>I'm trying to create a shortcut through python that will launch a file in another program with an argument. E.g:</p> <pre><code>"C:\file.exe" "C:\folder\file.ext" argument </code></pre> <p>The code I've tried messing with:</p> <pre><code>from win32com.client import Dispatch import os shell = Dispatch("WScript.Sh...
3
2016-07-31T19:48:42Z
38,688,725
<pre><code>from comtypes.client import CreateObject from comtypes.gen import IWshRuntimeLibrary shell = CreateObject("WScript.Shell") shortcut = shell.CreateShortCut(path).QueryInterface(IWshRuntimeLibrary.IWshShortcut) shortcut.TargetPath = "C:\file.exe" args = ["C:\folder\file.ext", argument] shortcut.Arguments = "...
2
2016-07-31T21:57:46Z
[ "python", "shortcut", "wscript" ]
How to define zorder when using 2 y-axis?
38,687,887
<p>I plot using two y-axis, on the left and the right of a matplotlib figure and use <code>zorder</code> to control the position of the plots. I need to define the <code>zorder</code> <em>across</em> axes in the same figure.</p> <hr> <p><strong>Problem</strong></p> <pre><code>import numpy as np import matplotlib.pyp...
0
2016-07-31T19:57:52Z
38,688,010
<p>It looks like the two axes have separate z-stacks. The axes are z-ordered with the most recent axis on top, so you need to move the curve you want on top to the last axis you create:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt x = np.arange(-10,10,0.01) fig, ax1 = plt.subplots( 1, 1, figsize=...
0
2016-07-31T20:11:44Z
[ "python", "numpy", "matplotlib" ]
order list of tuples in revlex
38,687,935
<p>I am trying to generate the list of all k tuples on the numbers 0 through n-1, but I want this list to be ordered in revlex. For example, </p> <pre><code>import itertools list(itertools.combinations(range(0, 6), 3)) </code></pre> <p>outputs these tuples in lexicographic ordering:</p> <p>[(0, 1, 2), (0, 1, 3), (0,...
-1
2016-07-31T20:03:05Z
38,688,954
<p>Your reverse lexicographic order sorts by last item, then next-to-last, etc. One way to do that is to take the range, reverse that range, use itertools to make all combinations from that, reverse each item in that combinations list, then finally reverse the overall list. A list or tuple can be reversed by slicing wi...
1
2016-07-31T22:37:46Z
[ "python", "list", "sorting" ]
Remove everything besides a certain html tag and its content in Python
38,687,974
<p>I've search around the internet and I cannot find anything that will exclude everything besides a certain tag and its content inside it.</p> <p>How can I do this with Python (beautifulsoup 4)?</p> <p>I have this html:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="fal...
0
2016-07-31T20:06:49Z
38,688,029
<p>Why don't locate the <code>iframe</code> and get its <em>string representation</em>:</p> <pre><code>iframe = soup.find("iframe", class_="embed") print(str(iframe)) </code></pre>
0
2016-07-31T20:13:52Z
[ "python", "django", "python-3.x" ]
Converting a 1.2GB list of edges into a sparse matrix
38,688,062
<p>I have a 1.2GB list of edges from a graph in a text file. My ubuntu PC has 8GB of RAM. Each line in the input looks like</p> <pre><code>287111206 357850135 </code></pre> <p>I would like to convert it into a sparse adjacency matrix and output that to a file.</p> <p>Some statistics for my data: </p> <pre><code>Num...
5
2016-07-31T20:18:19Z
38,688,464
<h2>Updated version</h2> <p>As indicated in the comments, the approach did not fit your use-case. Let's make some changes:</p> <ul> <li>use pandas for reading in the data (instead of numpy: i'm quite surprised np.loadtxt is performing that bad!)</li> <li>use external library <a href="http://www.grantjenks.com/docs/so...
3
2016-07-31T21:16:01Z
[ "python", "pandas", "numpy", "optimization", "scipy" ]
Converting a 1.2GB list of edges into a sparse matrix
38,688,062
<p>I have a 1.2GB list of edges from a graph in a text file. My ubuntu PC has 8GB of RAM. Each line in the input looks like</p> <pre><code>287111206 357850135 </code></pre> <p>I would like to convert it into a sparse adjacency matrix and output that to a file.</p> <p>Some statistics for my data: </p> <pre><code>Num...
5
2016-07-31T20:18:19Z
38,692,211
<p>You might want to take a look at the <a href="http://igraph.org/python/" rel="nofollow">igraph</a> project, this is a GPL library of C code which is designed for this kind of thing, and has a nice Python API. I think in your case you the Python code would be something like </p> <pre><code>from igraph import Graph g...
0
2016-08-01T06:25:36Z
[ "python", "pandas", "numpy", "optimization", "scipy" ]
Converting a 1.2GB list of edges into a sparse matrix
38,688,062
<p>I have a 1.2GB list of edges from a graph in a text file. My ubuntu PC has 8GB of RAM. Each line in the input looks like</p> <pre><code>287111206 357850135 </code></pre> <p>I would like to convert it into a sparse adjacency matrix and output that to a file.</p> <p>Some statistics for my data: </p> <pre><code>Num...
5
2016-07-31T20:18:19Z
38,734,771
<p>Here's my solution:</p> <pre><code>import numpy as np import pandas as pd import scipy.sparse as ss def read_data_file_as_coo_matrix(filename='edges.txt'): "Read data file and return sparse matrix in coordinate format." data = pd.read_csv(filename, sep=' ', header=None, dtype=np.uint32) rows = data[0] ...
5
2016-08-03T05:04:02Z
[ "python", "pandas", "numpy", "optimization", "scipy" ]
Converting a 1.2GB list of edges into a sparse matrix
38,688,062
<p>I have a 1.2GB list of edges from a graph in a text file. My ubuntu PC has 8GB of RAM. Each line in the input looks like</p> <pre><code>287111206 357850135 </code></pre> <p>I would like to convert it into a sparse adjacency matrix and output that to a file.</p> <p>Some statistics for my data: </p> <pre><code>Num...
5
2016-07-31T20:18:19Z
38,770,170
<p>In my answer I consider the case where the ids of the nodes are given by 9 characters long strings each character from <code>[0-9A-Za-z]</code>. <code>n</code> of these node ids should be mapped on the values <code>[0,n-1]</code> (which might be not necessary for your application, but still of general interest).</p>...
2
2016-08-04T14:26:36Z
[ "python", "pandas", "numpy", "optimization", "scipy" ]
Converting a 1.2GB list of edges into a sparse matrix
38,688,062
<p>I have a 1.2GB list of edges from a graph in a text file. My ubuntu PC has 8GB of RAM. Each line in the input looks like</p> <pre><code>287111206 357850135 </code></pre> <p>I would like to convert it into a sparse adjacency matrix and output that to a file.</p> <p>Some statistics for my data: </p> <pre><code>Num...
5
2016-07-31T20:18:19Z
38,780,599
<p>I was trying the different methods available apart from the ones already used. I found the following doing good.</p> <p>Method 1 - Reading the file into a string, parsing the string into a 1-D array using numpy's fromstring.</p> <pre><code>import numpy as np import scipy.sparse as sparse def readEdges(): with...
3
2016-08-05T03:26:08Z
[ "python", "pandas", "numpy", "optimization", "scipy" ]
output a dataframe to a json array
38,688,072
<p>I was wondering if there was a more efficient way to do the following operation.</p> <pre><code># transforms datetime into timestamp in seconds t = df.index.values.astype(np.int64) // 10**6 return jsonify(np.c_[t, df.open, df.high, df.low, df.close, df.volume].tolist()) </code></pre> <p>where <code>df</code> is a...
2
2016-07-31T20:20:07Z
38,688,136
<p>you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_json.html" rel="nofollow">to_json()</a> method:</p> <pre><code>In [88]: import pandas_datareader.data as web In [89]: apl = web.get_data_yahoo('AAPL', '2016-07-05', '2016-07-07') In [90]: apl Out[90]: O...
5
2016-07-31T20:29:24Z
[ "python", "json", "pandas", "numpy", "dataframe" ]
Why is this invalid syntax? (Class function)
38,688,097
<p>The code I am trying to enter (python) looks like this:</p> <pre><code>class RainfallTable: def _init_ (self, njrainfall.txt): self.njrainfall.txt = open(njrainfall.txt, 'r') def close(self): if self.t: self.t.close() self.t = None </code></pre> <p>I am trying to get...
0
2016-07-31T20:24:41Z
38,688,121
<p>Function/constructor should have only variables as input</p> <p>You can pass text file name along with path to that init function</p> <p>Better you pass text file with absolute path</p> <pre><code>class RainfallTable: def _init_ (self, textfile): self.t = open(textfile, 'r') def close(self): ...
0
2016-07-31T20:27:44Z
[ "python", "class" ]
Why is this invalid syntax? (Class function)
38,688,097
<p>The code I am trying to enter (python) looks like this:</p> <pre><code>class RainfallTable: def _init_ (self, njrainfall.txt): self.njrainfall.txt = open(njrainfall.txt, 'r') def close(self): if self.t: self.t.close() self.t = None </code></pre> <p>I am trying to get...
0
2016-07-31T20:24:41Z
38,688,127
<p>You've got a <code>.</code> in your variable names, which is invalid syntax for python. Remove those in your <code>njrainfall.txt</code> variables. A good substitute would be <code>njrainfall_file</code> or something similar. Secondly, the init functions is written with two underscores, like so:</p> <pre><code>def ...
3
2016-07-31T20:28:32Z
[ "python", "class" ]
Why is this invalid syntax? (Class function)
38,688,097
<p>The code I am trying to enter (python) looks like this:</p> <pre><code>class RainfallTable: def _init_ (self, njrainfall.txt): self.njrainfall.txt = open(njrainfall.txt, 'r') def close(self): if self.t: self.t.close() self.t = None </code></pre> <p>I am trying to get...
0
2016-07-31T20:24:41Z
38,688,224
<p>It looks like you are confused with strings, parameter/variable names, and class objects.</p> <p>The dot you are using in what must be a variable name (<code>njrainfall.txt</code>) looks like either a string with an actual file name, or an object attribute.</p> <p>As other people have pointed out already, you shal...
0
2016-07-31T20:42:01Z
[ "python", "class" ]
Why is this invalid syntax? (Class function)
38,688,097
<p>The code I am trying to enter (python) looks like this:</p> <pre><code>class RainfallTable: def _init_ (self, njrainfall.txt): self.njrainfall.txt = open(njrainfall.txt, 'r') def close(self): if self.t: self.t.close() self.t = None </code></pre> <p>I am trying to get...
0
2016-07-31T20:24:41Z
38,690,150
<p>Remove the fullstop here <pre>self.njrainfall.txt</pre> to something else.</p> <p>Like</p> <pre>self.njrainfall</pre>
0
2016-08-01T02:17:21Z
[ "python", "class" ]
Python: Elements in a list not being changed?
38,688,116
<p>I'm having issues with editing elements in a list in Python, I've got the following code: </p> <pre><code>mylist = ["one", "day", "soon"] for x in mylist: x = "New word" print(x) print(mylist) </code></pre> <p>I would expect the output to be "New Word" three times (once for each iteration) and then a lis...
0
2016-07-31T20:26:34Z
38,688,123
<p>The problem is that when you iterate with <code>for x in mylist</code> and then assign a value to <code>x</code>, you are creating a new variable called <code>x</code> and that is what you are printing. You cannot change the list in that way, only by iterating like this:</p> <pre><code>for i in range(len(mylist)): ...
2
2016-07-31T20:28:00Z
[ "python", "list", "python-3.x" ]
How to parse text from a html table element
38,688,137
<p>I'm currently writing a small test webscraper using the python requests and lxml libraries. I'm trying to extract the text from the rows of a table from <a href="https://en.wikipedia.org/wiki/Game_of_Thrones" rel="nofollow">this site</a> using xpaths to uniquely identify the table. Since the table itself can only be...
2
2016-07-31T20:29:28Z
38,688,170
<p>The <code>wikitable</code> is too broad of a class to distinguish tables on a wiki page between one another.</p> <p>I would instead rely on the preceding <code>Adaptation schedule</code> label:</p> <pre><code>import requests from lxml.html import fromstring url = "https://en.wikipedia.org/wiki/Game_of_Thrones" re...
2
2016-07-31T20:33:55Z
[ "python", "html", "xpath", "python-requests", "lxml" ]
[RESOLVED]Get all files from my C drive - Python
38,688,228
<p>Here is what I try to do: I would like to get a list of all files that are heavier than 35 MB in my C drive.</p> <p>Here is my code:</p> <pre><code>def getAllFileFromDirectory(directory, temp): files = os.listdir(directory) for file in files: if (os.path.isdir(file)): getAllFileFromDir...
0
2016-07-31T20:42:16Z
38,688,311
<p>I fixed your code. Your problem was that <code>os.path.isdir</code> can only know if something is a directory if it receives the full path of it. So, I changed the code to the following and it works. Same thing for <code>os.path.getsize</code> and <code>os.path.isfile</code>.</p> <pre><code>import os def getAllFil...
1
2016-07-31T20:52:18Z
[ "python", "windows", "python-2.7", "python-3.x" ]
How to return tuples and count from list using list comprehension
38,688,254
<p>I have a function which, using list comprehension, returns the list elements in caps, and counts each element. </p> <pre><code>def wordlengths(mywords): upperword = [word.upper() for word in mywords] lenword = [len(i) for i in mywords] return upperword, lenword print(wordlengths(["The", "quick", "brown"...
0
2016-07-31T20:45:18Z
38,688,271
<p>You can use <a href="https://docs.python.org/3/library/functions.html#zip" rel="nofollow"><code>zip()</code></a>:</p> <pre><code>def wordlengths(mywords): upperword = [word.upper() for word in mywords] lenword = [len(i) for i in mywords] return list(zip(upperword, lenword)) </code></pre> <p>But, why do...
4
2016-07-31T20:46:46Z
[ "python", "list", "python-3.x", "list-comprehension" ]
Assert Error is thrown when mocking python3
38,688,258
<p>I am trying to write a test that mocks raising <code>PermissionError</code> on a call to <code>open()</code> when attempting to open a file for reading. However I cannot seem to get the test working. The <code>PermissionError</code> appears to be thrown but my test fails because of this even though I am trying to as...
0
2016-07-31T20:45:45Z
38,688,291
<p>The reason this will not work is because you are mocking <code>fileMethods.open</code> and so the <code>open</code> function (which raises the <code>PermissionError</code> you're looking for) is not even called.</p> <p>If the <code>open</code> function is mocked (and therefore, the called function will do nothing),...
0
2016-07-31T20:49:12Z
[ "python", "unit-testing", "mocking" ]
Python string not printing properly in PowerShell
38,688,328
<p>I'm having difficulty parsing data with a lot of scientific and international symbols using Python 2.7 so I wrote a toy program that illustrates what is not making sense to me: </p> <pre><code>#!/usr/bin/python # coding=utf-8 str ="35 μg/m3" str = str.decode('utf-8') str = str.encode('utf-8') #ready for printing?...
0
2016-07-31T20:54:28Z
38,688,754
<p>The line <code># coding=utf-8</code> only helps to write unicode literal and is no use for plain byte strings. Anyway assuming that your Python file is UTF-8 encoded, the line <code>str = str.decode('utf-8')</code> gives you a correct unicode string.</p> <p>But as said by Ansgar Wiechers, as you declare your encodi...
0
2016-07-31T22:02:58Z
[ "python", "powershell", "unicode", "encoding" ]
Python string not printing properly in PowerShell
38,688,328
<p>I'm having difficulty parsing data with a lot of scientific and international symbols using Python 2.7 so I wrote a toy program that illustrates what is not making sense to me: </p> <pre><code>#!/usr/bin/python # coding=utf-8 str ="35 μg/m3" str = str.decode('utf-8') str = str.encode('utf-8') #ready for printing?...
0
2016-07-31T20:54:28Z
38,688,846
<p>Python 2.7 doesn't use Unicode strings by default, so you basically have 2 options:</p> <ul> <li><p>Define the string as a Unicode string literal (<code>u"..."</code>):</p> <pre><code># coding=utf-8 str = u"35 µg/m3" print(str) </code></pre> <p>This way you can simply use the string as one would expect, so I'd p...
0
2016-07-31T22:20:14Z
[ "python", "powershell", "unicode", "encoding" ]
Python string not printing properly in PowerShell
38,688,328
<p>I'm having difficulty parsing data with a lot of scientific and international symbols using Python 2.7 so I wrote a toy program that illustrates what is not making sense to me: </p> <pre><code>#!/usr/bin/python # coding=utf-8 str ="35 μg/m3" str = str.decode('utf-8') str = str.encode('utf-8') #ready for printing?...
0
2016-07-31T20:54:28Z
38,702,903
<p>Your decoding/encoding has no effect:</p> <pre><code># coding=utf-8 s1 = "35 μg/m3" s2 = s1.decode('utf-8') s3 = s2.encode('utf-8') #ready for printing? print s1==s3 </code></pre> <p>If your source is UTF-8 as declared, then <code>s1</code> is a byte string that is UTF-8-encoded already. Decoding it to a Unicod...
0
2016-08-01T15:40:11Z
[ "python", "powershell", "unicode", "encoding" ]
Add a delay after 500 requests scrapy
38,688,347
<p>I have a list of start 2000 urls and I'm using:</p> <pre><code>DOWNLOAD_DELAY = 0.25 </code></pre> <p>For controlling the speed of the requests, But I also want to add a bigger delay after n requests. For example, I want a delay of 0.25 seconds for each request and a delay of 100 seconds each 500 requests.</p> ...
1
2016-07-31T20:57:30Z
38,688,378
<p>You can look into using an <a href="http://doc.scrapy.org/en/latest/topics/autothrottle.html" rel="nofollow">AutoThrottle extension</a> which does not give you a tight control of the delays but instead has its own algorithm of slowing down the spider adjusting it on the fly depending on the response time and number ...
1
2016-07-31T21:03:43Z
[ "python", "web-scraping", "scrapy" ]
How Can I check if my rectangle(coin) has collided with my chest?
38,688,409
<p>I am currently making a game in pygame.What I am trying to do is check if my rectangle(a yellow coin blitted on it) collides with my chest image.If it does what the program should do is reset the yellow coin back to its initial position of y axis( showed later in here). </p> <p>This is my function to create rectan...
0
2016-07-31T21:08:59Z
38,689,115
<p>What you probably want is <code>pygame.Rect.collide_rect()</code>. It returns <code>True</code> if two rects collided. You first want to put your coin and your treasure chest dimensions in a <code>pygame.Rect</code> object. I'll use your coin rect as a example: <code>coin_rect = pygame.Rect(thingx,thingy,thingw,thi...
0
2016-07-31T23:07:18Z
[ "python", "image", "python-2.7", "pygame", "rect" ]
AttributeError for function called in another function within same class - Python
38,688,414
<p>When I run the following code I get an AttributeError: 'set' object has no attribute findMean. What am I doing wrong?</p> <pre><code>class BasicStats: def findMean(self, num = {}): length = len(num) sum = 0 for x in num: sum = sum + x mean =sum/length r...
1
2016-07-31T21:09:49Z
38,688,436
<p>It's because <code>self</code> in that scope is a <code>set</code>. More specifically, it is <code>arr</code> (which is a set and you pass in as the first argument).</p> <p>The <code>self</code> keyword only works for functions called against an instance of a class (this special type of functions are called methods...
3
2016-07-31T21:11:44Z
[ "python" ]
django use models variable in template
38,688,432
<p>I would like to use the values in a choices field in my template. Suppose I had the class:</p> <pre><code>MY_CHOICES = ( ('A1', 'The best steak sauce'), ('B2', 'Very stealthy'), ('C3', 'Missing a P0')) class MyClass(models.Model): my_field = models.CharField(max_length = 2, choices = MY_CHOICES) </...
2
2016-07-31T21:11:23Z
38,688,646
<p><strong>EDIT:</strong> Added a new solution since the first was only about a line the author Woody1193 forgot to mention but implemented it already.</p> <p><strong>NEW:</strong></p> <p>I have actually had a similar problem and solved it by creating a custom POST function in javascript.</p> <p>Copied from <a href=...
-1
2016-07-31T21:44:27Z
[ "python", "django" ]
django use models variable in template
38,688,432
<p>I would like to use the values in a choices field in my template. Suppose I had the class:</p> <pre><code>MY_CHOICES = ( ('A1', 'The best steak sauce'), ('B2', 'Very stealthy'), ('C3', 'Missing a P0')) class MyClass(models.Model): my_field = models.CharField(max_length = 2, choices = MY_CHOICES) </...
2
2016-07-31T21:11:23Z
38,694,920
<p>the simplest solution of this problem is, You should create a file forms.py in a same directory where models.py is locaed and write this code into the file:</p> <p><strong>forms.py</strong></p> <pre><code>from models import MyClass from django import forms class MyForm(forms.ModelForm): class Meta: mod...
1
2016-08-01T09:09:15Z
[ "python", "django" ]
Adding a text input dialogue box in psychopy using python?
38,688,451
<p>I am using psychopy and python to program a simple psychology experiment. Basically, a foreign word appears on the screen for 8 seconds, followed by 5 seconds of a translation of that word. During the 8 second exposure to the foreign word, participants are instructed to type in a guess as to what the translation m...
0
2016-07-31T21:13:48Z
38,722,662
<p>I made something similar to what you are describing a while back. Perhaps this will help. You first have some TextStim, and some predefined keys:</p> <pre><code>instruction = psychopy.visual.TextStim(myWindow,color="white") quitKeys = ['escape', 'esc'] ansKeys = ['space', 'return'] keyboardKeys = ['a','b','c','d','...
1
2016-08-02T14:02:53Z
[ "python", "psychopy" ]
Dictionary Sorting based on lower dictionary value
38,688,455
<p>I am working with an API that returns values in this format:</p> <pre><code>raw = [{'Name': 'Erica','Value':12},{'Name':'Sam','Value':8},{'Name':'Joe','Value':60}] </code></pre> <p>I am trying to return the 'name' of the people with the top 2 'values':</p> <pre><code>result = ['Joe','Erica'] </code></pre> <p>Wha...
-6
2016-07-31T21:14:22Z
38,688,474
<pre><code>raw = [{'Name': 'Erica','Value':12},{'Name':'Sam','Value':8},{'Name':'Joe','Value':60}] raw.sort(key=lambda d: d['Value'], reverse=True) result = [] for i in range(2): result.append(raw[i]['Name']) print(result) # =&gt; ['Joe', 'Erica'] </code></pre> <p>print(result)</p> <p>Try this.</p>
-1
2016-07-31T21:17:08Z
[ "python", "dictionary" ]
Converting and writing list of strings as binary in Python 3
38,688,488
<p>I'm trying to convert a Python 2.x version of this code:</p> <pre><code>out_chunk = open('out.txt','w+b') chunks.append(out_chunk) # out_chunk is just a list of strings like ['a', 'b', ...] out_chunk.writelines(chunk) </code></pre> <p>into Python 3.x version. If I run the above code in Python 3.x directly, I get a...
0
2016-07-31T21:18:43Z
38,688,521
<p>Just don't open the file in binary mode:</p> <pre><code>out_chunk = open('out.txt','w+') </code></pre> <p>Hope it helps!</p>
1
2016-07-31T21:23:31Z
[ "python", "python-2.7", "python-3.x", "io" ]
Converting and writing list of strings as binary in Python 3
38,688,488
<p>I'm trying to convert a Python 2.x version of this code:</p> <pre><code>out_chunk = open('out.txt','w+b') chunks.append(out_chunk) # out_chunk is just a list of strings like ['a', 'b', ...] out_chunk.writelines(chunk) </code></pre> <p>into Python 3.x version. If I run the above code in Python 3.x directly, I get a...
0
2016-07-31T21:18:43Z
38,688,648
<p>You opened the file in <em>binary</em> mode, so you'd have to encode your bytes.</p> <p>If you drop the <code>'b'</code> part from the file mode (so open with <code>'w+'</code> rather than <code>'w+b'</code>), you get an implementation of the <a href="https://docs.python.org/3/library/io.html#io.TextIOBase" rel="no...
3
2016-07-31T21:44:32Z
[ "python", "python-2.7", "python-3.x", "io" ]
Dataframe manipulation and aggregation
38,688,502
<p>I have the following dataframe </p> <pre><code> City Status q1 q2 Record 0 Austin Standard N Y Active 1 Dallas Standard N y Active 2 Orlando Standard N N Active 3 Orlando Ex Y Y Inactive 4 Orlando Standard N N Active </code></pre> <p>I'm tryi...
-2
2016-07-31T21:20:13Z
38,688,579
<p>you can do it this way:</p> <pre><code>In [159]: df.q1 = 'Q1 = ' + df.q1.str.upper() In [160]: df.q2 = 'Q2 = ' + df.q2.str.upper() In [161]: df Out[161]: City Status q1 q2 Record 0 Austin Standard Q1 = N Q2 = Y Active 1 Dallas Standard Q1 = N Q2 = Y Active 2 Orlando Standar...
1
2016-07-31T21:31:31Z
[ "python", "pandas" ]
Notepad++ or python - Compare two lists and change the original changed
38,688,542
<p>I have this original list.</p> <pre><code>John:password123 Daved:Password123 Steve:Password123 Michael:Password123 </code></pre> <hr> <p>The second list is a random of original list and with changed passwords.</p> <pre><code>Michael:p241d111 John:fcvbfdg122 Steve:pdPo134! </code></pre> <p>What I want is to chan...
-1
2016-07-31T21:26:40Z
38,688,654
<p><strong>test.txt</strong></p> <pre><code>John:password123 Daved:Password123 Steve:Password123 Michael:Password123 </code></pre> <p><strong>test2.txt</strong></p> <pre><code>Michael:p241d111 John:fcvbfdg122 Steve:pdPo134! </code></pre> <p><strong>script.py</strong></p> <pre><code>lst = {} with open("test.txt") ...
0
2016-07-31T21:46:22Z
[ "python", "regex", "list", "compare", "notepad++" ]
What do the keywords in the eventful api map to?
38,688,666
<p>I have been trying to setup the eventful api using python. The following example is all the documentation I could find on the it:</p> <pre><code>import eventful api = eventful.API('your API key here') # If you need to log in: # api.login('username', 'password') events = api.call('/events/search', q='music', l='...
0
2016-07-31T21:47:39Z
38,688,691
<p>Just found out what the args stood for, this link has them:</p> <p><a href="http://api.eventful.com/tools/tutorials/search" rel="nofollow">http://api.eventful.com/tools/tutorials/search</a></p> <p><em>What: The 'what' argument, also called <strong>'q'</strong> or 'keywords', is used to search by any aspect of an e...
0
2016-07-31T21:51:17Z
[ "python" ]
Sublime Text3 creates Scripts inside Scripts folder inside virtualenv
38,688,707
<p>I'm trying to run Python scripts inside virtualenv from Sublime Text 3. When I activate the virtualenv in ST3 and choose the <code>.py</code>, ST3 creates a <code>Scripts</code> folder inside the preexisting <code>Scripts</code> folder (for a new `.py'). What is causing this problem and how I do stop this from happe...
0
2016-07-31T21:54:39Z
38,689,463
<p>Solved. In ST3, use <code>Virtualenv: Add Directory</code> instead of <code>Virtualenv: New</code>. The latter creates a new virtualenv (hence the new Scripts folder).</p>
0
2016-08-01T00:10:40Z
[ "python", "python-2.7", "sublimetext3", "virtualenv" ]
change specific parts of a string in python (update bootstrap values in phylogenetic trees)
38,688,721
<p>So basically I have a string:</p> <pre><code>string_1 = '(((A,B)123,C)456,(D,E)789)135' </code></pre> <p>Containing a phylogenetic tree with bootstrap values is parenthetical notation (not really important to the question, but in case anyone was wondering). This example tree contains four relationships with four b...
3
2016-07-31T21:57:14Z
38,725,131
<p>This is a solution using Biopython. First you need to load your trees. If you're using strings, you'll need to load then first as <code>StringIO</code>, as the Parser only accepts file handles:</p> <pre><code>from io import StringIO from Bio.Phylo.NewickIO import Parser string_1 = u'(((A,B)123,C)456,(D,E)789)135' ...
1
2016-08-02T15:48:55Z
[ "python", "biopython", "statistics-bootstrap", "phylogeny" ]
the efficient approach to generate submatrices
38,688,745
<p>The following is a function that can return sub-matries from two given matries. The position of generating these sub-matries are the same for both input matries. The input matries are of <code>Numpy array</code>. I just would like to know are there more elegant ways to fulfill the same type of task as this function ...
0
2016-07-31T22:01:22Z
38,688,803
<p>As an alternative approach, we could create the indexing ranges with <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ix_.html" rel="nofollow"><code>np.ix_</code></a> and index into the input arrays with those, like so -</p> <pre><code>idx = np.ix_(np.arange(size)+dim1,np.arange(size)+dim2) out = ...
0
2016-07-31T22:10:06Z
[ "python", "numpy", "scipy" ]
the efficient approach to generate submatrices
38,688,745
<p>The following is a function that can return sub-matries from two given matries. The position of generating these sub-matries are the same for both input matries. The input matries are of <code>Numpy array</code>. I just would like to know are there more elegant ways to fulfill the same type of task as this function ...
0
2016-07-31T22:01:22Z
38,695,437
<p>You likely want to do <code>rowN, colN = ma1.shape</code> instead of</p> <p>rowN = len(ma1)<br> colN = len(ma1[0]) </p> <p>Also, you might want to seed your random number generator.</p>
0
2016-08-01T09:32:56Z
[ "python", "numpy", "scipy" ]
Daylight savings time for GPX and PostgreSQL
38,688,752
<p>So here I'm working with gpx files. Take note of an excerpt of one:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;!-- GPSTrack 2.2.1 — http://bafford.com/gpstrack --&gt; &lt;gpx xmlns="http://www.topografix.com/GPX/1/1"&gt; &lt;trk&gt; &lt;name&gt;&lt;![CDATA[2016-03-31 10-17-54]]&gt;&lt;/name&g...
0
2016-07-31T22:02:56Z
38,690,354
<p>If you <em>know</em> the <strong><em>time zone name</em></strong> where this local time is supposed to be set in (assuming <em>'Europe/Vienna'</em> in the example), you can normalize the value to correct UTC time (or <em>any</em> other time zone) with this expression:</p> <pre><code>SELECT '2016-03-31T09:17:51Z'::t...
0
2016-08-01T02:50:24Z
[ "python", "xml", "postgresql", "time", "dst" ]
handling large integers in for loop optimized in python
38,688,780
<p>I'm reading a large csv file (500 000 rows) and adding every row in a dict. One example row is: </p> <p><code>6AH8,F,B,0,60541765,60541765,90.52,1</code></p> <p>index 4 - <code>60541765</code> and index 5 - <code>60541765</code>in this case is the same, but it is not always the case. These integers are timestamps ...
0
2016-07-31T22:06:49Z
38,688,928
<p>Your issue is likely that checking whether a number is in a List in python is an O(n) operation, which will need to be performed for every row in your large dataset, meaning a total of O(n^2) algorithm, which is enormous on 500,000 entries.</p> <p>My suggestion would be to add a bit of space complexity O(n) to save...
1
2016-07-31T22:34:02Z
[ "python", "for-loop", "optimization", "integer", "iteration" ]
Copy value from matching index in another dataframe after criteria matched
38,688,784
<p>With the test Pandas dataframe below I am trying to copy a value from matching index in another dataframe after certain criteria is matched.</p> <p>This is a snip from the dataframe called <code>data2</code>:</p> <pre><code> Signal Value2 2013-01-01 09:00:00 1.0 NaN 2013-01-01 10:00:00 1.0 NaN 2013...
0
2016-07-31T22:07:16Z
38,688,970
<p>Could be something like this?</p> <pre><code>data2.loc[data2.Signal == -1, 'Value2'] = data.loc[data2.Signal == -1, 'value'] </code></pre>
1
2016-07-31T22:40:50Z
[ "python", "pandas" ]
django deleteview NoReverseMatch at
38,688,793
<p>I am new to Django. I keep receiving NoReverseMatch when building an app. Was wondering if someone can point me in the right direction as to where I am going wrong. </p> <p>The app has scenarios, each scenario has associated emailss. When I click on a scenario the app displays the emails associated to the scenari...
0
2016-07-31T22:08:58Z
38,690,928
<p><code>email-delete</code> URL has two capture groups - one non-named <code>([0-9]+)</code> and one named <code>(?P&lt;pk&gt;[0-9]+)</code>, but in the <code>url</code> tag you pass only positional argument - <code>email.id</code>. You must either remove the first group from url pattern or pass two arguments to <code...
0
2016-08-01T04:14:11Z
[ "python", "django" ]
How to implement multithreading with tornado?
38,688,816
<p>I am working with python2.7 with futures module installed.</p> <p>I am trying to implement multithreading in tornado using ThreadPoolExecutor. </p> <p>Here is the code that I have implemented.</p> <pre><code>from __future__ import absolute_import from base_handler import BaseHandler from tornado import gen from p...
0
2016-07-31T22:13:45Z
38,701,789
<p>It appears that <code>m.operation()</code> is blocking, so you need to run it on a thread. The way you're doing it blocks the main thread while calling <code>m.operation()</code>, and spawns a thread <em>after</em>:</p> <pre><code>self.executor.submit(m.operation()) </code></pre> <p>You want, instead, to pass the ...
1
2016-08-01T14:44:58Z
[ "python", "multithreading", "asynchronous", "tornado" ]
regular expression for shortest match in Python 2.7
38,688,827
<p>I am using Python 2.7. The current code returns <code>hello }{(2) world</code>. If I only want the shortest match, in this case <code>hello</code>, what is the solution in Python 2.7?</p> <pre><code>import re content = '{(1) hello }{(2) world}' reg = '{\(1\)(.*)}' results = re.findall(reg, content) print results[0...
0
2016-07-31T22:16:10Z
38,688,836
<p>Make the wildcard match <a href="http://stackoverflow.com/questions/2301285/what-do-lazy-and-greedy-mean-in-the-context-of-regular-expressions"><em>non-greedy</em></a>:</p> <pre><code>&gt;&gt;&gt; reg = r'{\(1\)(.*?)}' # this ? is important^ &gt;&gt;&gt; results = re.findall(reg, content) &gt;&gt;&gt; print results...
3
2016-07-31T22:18:14Z
[ "python", "regex", "python-2.7" ]
regular expression for shortest match in Python 2.7
38,688,827
<p>I am using Python 2.7. The current code returns <code>hello }{(2) world</code>. If I only want the shortest match, in this case <code>hello</code>, what is the solution in Python 2.7?</p> <pre><code>import re content = '{(1) hello }{(2) world}' reg = '{\(1\)(.*)}' results = re.findall(reg, content) print results[0...
0
2016-07-31T22:16:10Z
38,690,961
<p>For this kind of situation negated character class will also help you.</p> <pre><code>reg = r'{\(1\)([^}]*)}' results = re.findall(reg, content) print results[0] </code></pre>
0
2016-08-01T04:18:54Z
[ "python", "regex", "python-2.7" ]
how to create new variable from loop index in python
38,688,865
<p>i have the following sort of code</p> <pre><code> ps=[1,2,3,4] for subj in ps: num=num+1 datapath='/home/subj%d' %(int(subj)) if num==1: d1= pd.read_csv(datapath, 'words.csv') if num==2: d2= pd.read_csv(datapath, 'words.csv') if num==3: d3= pd.read_csv(datapath, ...
0
2016-07-31T22:23:34Z
38,688,887
<p>Just do this:</p> <pre><code>paths = map('/home/subj{}'.format, ps) datas = map(pd.read_csv, paths) </code></pre> <p>Now you have a list of DataFrames, but if you want separate variables, you can:</p> <pre><code>d1, d2, d3, d4 = datas </code></pre>
0
2016-07-31T22:27:02Z
[ "python" ]
how to create new variable from loop index in python
38,688,865
<p>i have the following sort of code</p> <pre><code> ps=[1,2,3,4] for subj in ps: num=num+1 datapath='/home/subj%d' %(int(subj)) if num==1: d1= pd.read_csv(datapath, 'words.csv') if num==2: d2= pd.read_csv(datapath, 'words.csv') if num==3: d3= pd.read_csv(datapath, ...
0
2016-07-31T22:23:34Z
38,688,889
<p>Create a list and append the data.</p> <pre><code>ps=[1,2,3,4] d = [] for subj in ps: datapath = '/home/subj%d' % (subj) d.append(pd.read_csv(datapath, 'numbers.csv')) </code></pre> <p>You can access the data with <code>d[0]</code> to <code>d[3]</code>.</p> <p>Using a list comprehension will lead to the f...
4
2016-07-31T22:27:21Z
[ "python" ]
Seaborn OS X : seaborn.pairplot() ValueError: 'transform' must be an instance of 'matplotlib.transform.Transform'
38,688,881
<p>The following steps were taken inside of jupyter notebook in an attempt to make <code>seaborn.pairplot()</code> work. An error from <code>/usr/local/lib/python2.7/site-packages/matplotlib/matplotlib/transforms.pyc</code> stopped the function from working.</p> <p>Below are the python library versions:</p> <pre><cod...
3
2016-07-31T22:25:58Z
38,708,506
<p>So I am answering my own question now.</p> <p>I solved the problem by using a Macports virtual environment</p> <pre><code>sudo port selfupdate sudo port install python27 sudo port install py27-virtualenv /opt/local/bin/virtualenv-2.7 $HOME/local/python/27 </code></pre> <p>Add to .bash_profile:</p> <pre><code>a...
0
2016-08-01T21:35:49Z
[ "python", "matplotlib", "seaborn" ]
Python Minimalmodbus sending value
38,688,893
<p>I need to control the speed of a VSD via Modbus using Python. I have all working accept one part and that is to send the speed of the VSD.</p> <p>If I send this command the motor will start</p> <pre><code> vsd.write_register(8192 , 2 , 0) </code></pre> <p>And this command will let it stop </p> <pre><code> vsd.wr...
0
2016-07-31T22:28:09Z
38,704,134
<p>You have to set the functioncode = 6. Then it sends the correct bytes.</p>
0
2016-08-01T16:51:14Z
[ "python", "modbus" ]
python 2.7 Regex for a range of numbers
38,688,899
<p>What is the regular expression to return a number in the range 274-342 and the rest of the line until '\n'? Here is my attempt.</p> <pre><code>import re text = '333get\n361donuts\n400chickenmcsandwich\n290this\n195foo\n301string' match=re.findall(r'(27[4-9]|8[0-9]|9[0-9]|3[0-3]\d|4[0-2])(.*)', text) </code></pre> ...
-5
2016-07-31T22:29:32Z
38,792,879
<p>You can use <code>'(\d+)(.*)'</code> and then filter the list:</p> <pre><code>import re text = '333get\n361donuts\n400chickenmcsandwich\n290this\n195foo\n301string' matches = re.findall(r'(\d+)(.*)', text) matches = [ item for item in matches if int(item[0]) in range(274,342) ] print(matches) # should print : [('33...
1
2016-08-05T15:29:40Z
[ "python", "regex" ]
Python - get combination of data from array of arrays
38,688,982
<p>I have an array which holds other arrays which are holding possible values of data at given position. Example: </p> <pre><code>data = [['A'],['A','B'],['A','B'],['A','B','D'],['0','2']] </code></pre> <p>From this data possible values are (for example): </p> <pre><code>"AAAA0" # (00000) "AAAA2" # (00001) ...
0
2016-07-31T22:43:21Z
38,689,025
<p>Try this:</p> <pre><code>data = [['A'], ['A','B'], ['A','B'], ['A','B','D'], ['0','2']] size = 5 def rec(cur): if len(cur) == size: print(cur) return for x in data[len(cur)]: rec(cur + [x]) rec([]) </code></pre> <p>Output:</p> <pre><code>['A', 'A', 'A', 'A', '0'] ['A', 'A', 'A',...
0
2016-07-31T22:50:35Z
[ "python", "arrays", "combinations" ]
Python - get combination of data from array of arrays
38,688,982
<p>I have an array which holds other arrays which are holding possible values of data at given position. Example: </p> <pre><code>data = [['A'],['A','B'],['A','B'],['A','B','D'],['0','2']] </code></pre> <p>From this data possible values are (for example): </p> <pre><code>"AAAA0" # (00000) "AAAA2" # (00001) ...
0
2016-07-31T22:43:21Z
38,689,033
<p>I think you need the <code>itertools.product</code> here:</p> <pre><code>import itertools [''.join(p) for p in itertools.product(*data)] #['AAAA0', # 'AAAA2', # 'AAAB0', # 'AAAB2', # 'AAAD0', # 'AAAD2', # 'AABA0', # 'AABA2', # 'AABB0', # 'AABB2', # 'AABD0', # 'AABD2', # 'ABAA0', # 'ABAA2', # 'ABAB0', # 'ABAB2', # ...
1
2016-07-31T22:51:30Z
[ "python", "arrays", "combinations" ]
handling exit status popen python
38,689,014
<p>I am tring to handle status exit with popen but it gives a error, the code is:</p> <pre><code>import os try: res = os.popen("ping -c 4 www.google.com") except IOError: print "ISPerror: popen" try: #wait = [0,0] wait = os.wait() except IOError: print "ISPerror:os.wait" if wait[1] != 0: print...
0
2016-07-31T22:48:52Z
38,689,192
<h1>Error Explanation</h1> <p>It looks like this error is occurring because upon exiting, the program tries to destroy <code>res</code>, which involves calling the <code>res.close()</code> method. But somehow invoking <code>os.wait()</code> has already closed the object. So it's trying to close <code>res</code> twice...
0
2016-07-31T23:18:48Z
[ "python" ]
Keep track of items in array with delimiter python
38,689,028
<p>I take in a user supplied input string array that can look like the following:</p> <pre><code>x=[100.0,150.0,200.0:300.0:10.0,300.0,350.0:400.0:10.0,500.0,600.0:700.0:10.0,800.0,900.0] </code></pre> <p>As these are user supplied lists, the ordering of the interval slices [e.g., 200.0:300.0:10.0] can vary, as can t...
2
2016-07-31T22:51:03Z
38,689,231
<p>Are you trying to convert this input string/list in to a list/array of numbers, taking into account that some items look like slices?</p> <p>Here's my experiment with your string (minus the <code>[]</code>). I'll leave a lot of the trial and error in. It might be instructive.</p> <pre><code>In [957]: txt='100.0,...
1
2016-07-31T23:25:42Z
[ "python", "arrays", "numpy" ]
Keep track of items in array with delimiter python
38,689,028
<p>I take in a user supplied input string array that can look like the following:</p> <pre><code>x=[100.0,150.0,200.0:300.0:10.0,300.0,350.0:400.0:10.0,500.0,600.0:700.0:10.0,800.0,900.0] </code></pre> <p>As these are user supplied lists, the ordering of the interval slices [e.g., 200.0:300.0:10.0] can vary, as can t...
2
2016-07-31T22:51:03Z
38,689,385
<p>You said the input array is a string, so (using your example):</p> <pre><code>x = '[100.0,150.0,200.0:300.0:10.0,300.0,350.0:400.0:10.0,500.0,600.0:700.0:10.0,800.0,900.0]' </code></pre> <p>Then we split <code>x</code> by <code>,</code> and then the elements by <code>:</code>:</p> <pre><code>x = x[1:-1].split(','...
1
2016-07-31T23:55:48Z
[ "python", "arrays", "numpy" ]
Attribute error response object doesnot have an attribute 'text'
38,689,047
<p>I am trying to use python scrapy tool for extracting the information from the bitcointalk.org website about the users and the public keys that they post in the forum for donation.</p> <p>I found this piece of code online, made changes to it so that it runs on my desired website, but I am running into an error Attri...
0
2016-07-31T22:53:45Z
38,689,544
<p>Something is likely wrong with one of your requests, since it seems like the response from at least one url your crawling is not properly formatted. Either the request itself failed, or you're not making requests appropriately.</p> <p><a href="https://github.com/scrapy/scrapy/blob/master/scrapy/selector/unified.py#...
0
2016-08-01T00:26:25Z
[ "python", "scrapy", "attributeerror" ]
when creating script have :TypeError: '_io.TextIOWrapper' object is not subscriptable
38,689,106
<p>I am trying to make my code narrow down words in a listing an input then sorting them into a different list but it threw out this can anyone help me?</p> <pre><code>Traceback (most recent call last): File "C:/Users/dan/Desktop/python/threeword.py", line 4, in &lt;module&gt; word = words[x],words[(x+1)],words[(x+2)]...
-1
2016-07-31T23:06:01Z
38,689,243
<p>You problem is that you can't just flat out say <code>words[0]</code> when all you assigned <code>words</code> to is <code>open(filename)</code> the open function in python does not return a list(as you seem to think) instead is returns a <code>file</code> object as said in the python docs about what the <code>open(...
0
2016-07-31T23:27:24Z
[ "python" ]
how to get rid of pandas converting large numbers in excel sheet to exponential?
38,689,125
<p>In the excel sheet , i have two columns with large numbers.</p> <p>But when i read the excel file with read_excel() and display the dataframe,</p> <p>those two columns are printed in scientific format with exponential.</p> <p>How can get rid of this format?</p> <p>Thanks </p> <p>Output in Pandas</p> <p><a hre...
1
2016-07-31T23:08:26Z
38,691,325
<p>The way scientific notation is applied is controled via pandas' options:</p> <pre><code>import pandas as pd pd.set_option('display.precision',3) pd.DataFrame({'x':[.001]}) x 0 0.001 </code></pre> <p>but</p> <pre><code>pd.DataFrame({'x':[.0001]}) x 0 1.000e-04 </code></pre> <p>but</p...
0
2016-08-01T05:03:19Z
[ "python", "pandas", "machine-learning", "data-analysis" ]
get UTF-8 encoded hex value for international character
38,689,160
<p>Using Mac OSX and if there is a file encoded with UTF-8 (contains international characters besides ASCII), wondering if any tools or simple command (e.g. in Python 2.7 or shell) we can use to find the related hex (base-16) values (in terms of byte stream)? For example, if I write some Asian characters into the file,...
0
2016-07-31T23:14:40Z
38,689,190
<p>You can use the command <code>iconv</code> to convert between encodings. The basic command is:</p> <pre><code>iconv -f from_encoding -t to_encoding inputfile </code></pre> <p>and you can see a list of supported encodings with</p> <pre><code>iconv --list </code></pre> <p>In your case,</p> <pre><code>iconv -f UT...
0
2016-07-31T23:18:24Z
[ "python", "python-2.7", "shell", "unicode", "utf-8" ]
get UTF-8 encoded hex value for international character
38,689,160
<p>Using Mac OSX and if there is a file encoded with UTF-8 (contains international characters besides ASCII), wondering if any tools or simple command (e.g. in Python 2.7 or shell) we can use to find the related hex (base-16) values (in terms of byte stream)? For example, if I write some Asian characters into the file,...
0
2016-07-31T23:14:40Z
38,705,587
<p><code>od</code> is the right command, but you need to specify an optional argument <code>-t x1</code>:</p> <pre><code>$ od -t x1 ~/Downloads/12 0000000 31 0000001 </code></pre> <p>If you prefer not to see the file offsets, try adding <code>-A none</code>:</p> <pre><code>$ od -A none -t x1 ~/Downloads/12 31 </cod...
1
2016-08-01T18:22:13Z
[ "python", "python-2.7", "shell", "unicode", "utf-8" ]
get UTF-8 encoded hex value for international character
38,689,160
<p>Using Mac OSX and if there is a file encoded with UTF-8 (contains international characters besides ASCII), wondering if any tools or simple command (e.g. in Python 2.7 or shell) we can use to find the related hex (base-16) values (in terms of byte stream)? For example, if I write some Asian characters into the file,...
0
2016-07-31T23:14:40Z
38,705,658
<p>I'm not sure exactly what you want, but this script can help you look up the Unicode codepoint and UTF-8 byte sequence for any character. Be sure to save the source as UTF-8.</p> <pre><code># coding: utf8 s = u'我是美国人。' for c in s: print c,'U+{:04X} {}'.format(ord(c),repr(c.encode('utf8'))) </code><...
2
2016-08-01T18:27:21Z
[ "python", "python-2.7", "shell", "unicode", "utf-8" ]
How can update my code for a django app without earasing the existing database (Read Description)?
38,689,171
<p>I have a python django application that I published to heroku by connecting to github. I want some people to be able to add some information to the database from the website. If I make changes to the code, push to github and deploy the branch the database will go back to how it was at first. How can update my code f...
0
2016-07-31T23:16:13Z
38,689,489
<p>If you host your database on a separate server, like with <a href="https://aws.amazon.com/rds/mysql/" rel="nofollow">Amazon RDS</a> or <a href="https://www.heroku.com/postgres" rel="nofollow">Heroku Postgres</a>, and configure your code to connect to this remote host, you should have sufficient decoupling to avoid w...
1
2016-08-01T00:15:10Z
[ "python", "django", "database", "heroku", "web" ]
Delay between printing characters in Tkinter
38,689,182
<p>I'm trying to make a program that prints to a scrollable textbox. The only problem is that I want a delay between the characters. I've seen it using the print method but when I try to replace it with a textbox and insert it doesnt do anything. Here is the code using the print method.</p> <pre><code>from time import...
-1
2016-07-31T23:17:22Z
38,689,321
<p>Tkinter widgets have a method named <code>after</code> which you can use to run a command in the future. You can set up a function that inserts one letter, then calls itself again after a day. </p> <p>I don't know what you mean by a "scrollable textbox" since tkinter doesn't have a "textbox" widget. There is a sing...
0
2016-07-31T23:41:57Z
[ "python", "user-interface", "tkinter", "textbox" ]
How do I make a triangle of numbers using python loops?
38,689,185
<p>I am trying to achieve this</p> <pre><code>0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 0 1 2 3 4 5 0 1 2 3 4 0 1 2 3 0 1 2 0 1 0 </code></pre> <p>And I'm getting close but now I'm stuck. Here is my cu...
2
2016-07-31T23:17:57Z
38,689,263
<p>interesting puzzle, you could try this:</p> <pre><code>n = range(0,10) #set your range while len(n)&lt;20: #loop until it exhausts where you want it too print ''.join(str(e) for e in n[0:10]) #print as a string! n = [' ']+n #prepend blank spaces </code></pre> <p><a href="http://rextester.com/DTSBRB5...
1
2016-07-31T23:30:13Z
[ "python", "loops" ]
How do I make a triangle of numbers using python loops?
38,689,185
<p>I am trying to achieve this</p> <pre><code>0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 0 1 2 3 4 5 0 1 2 3 4 0 1 2 3 0 1 2 0 1 0 </code></pre> <p>And I'm getting close but now I'm stuck. Here is my cu...
2
2016-07-31T23:17:57Z
38,689,267
<p>You can try this code:</p> <pre><code>def triangle(): for i in range(10): print i * " ", for j in range(10 - i): print j, print triangle() </code></pre> <p>The code is almost self explaining.</p> <p>Online example is <a href="http://www.codeskulptor.org/#user41_988HYx...
2
2016-07-31T23:30:45Z
[ "python", "loops" ]
How do I make a triangle of numbers using python loops?
38,689,185
<p>I am trying to achieve this</p> <pre><code>0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 0 1 2 3 4 5 0 1 2 3 4 0 1 2 3 0 1 2 0 1 0 </code></pre> <p>And I'm getting close but now I'm stuck. Here is my cu...
2
2016-07-31T23:17:57Z
38,689,887
<p>The other solutions are fine, but life becomes a little easier with <code>numpy</code>'s <code>arange</code> and the overloaded <code>*</code> operator for strings. Python's built-ins are very powerful.</p> <pre><code>for i in range(11): print ' ' * i + ''.join(str(elt) for elt in np.arange(10 - i)) </code></pr...
0
2016-08-01T01:31:53Z
[ "python", "loops" ]
Creating a save as function in python
38,689,271
<p>I'm trying to create a function to save data taken from multiple Entry widgets in my code and create a new save file storing the data from all the entries.</p> <p>I made a entry list called entries and try to pull from that but can't get it quite right. It will create the file but its always blank. </p> <p>This is...
-2
2016-07-31T23:31:21Z
38,690,231
<pre><code>def file_save_as(self): fout = asksaveasfilename(defaultextension = '.txt') try: with open(fout, 'w') as output: for x in self.entries: output.write(x.get()) except FileNotFoundError: print("Cancelled save or error in filename") </code></pre>
2
2016-08-01T02:30:21Z
[ "python", "file", "tkinter", "save" ]
Trying to install pip error with configparser
38,689,289
<p>I am trying to install pip and am getting some issues with configparser. Somehow the import configparser is pointing to the system version of python, python 2.7 instead of python 3.5 </p> <pre><code>&gt;&gt; pip install -U pip Traceback (most recent call last): File "/Users/../anaconda3/bin/pip", line 9, in &lt;...
0
2016-07-31T23:35:37Z
38,689,344
<p>I'm assuming you are using Linux OS based on the command. Give it a try to install with <strong>apt-get</strong>:</p> <pre><code>apt-get install python-pip </code></pre> <p>when not logged in as root use, you must know root password:</p> <pre><code>sudo apt-get install python-pip </code></pre> <p>I used the same...
0
2016-07-31T23:46:39Z
[ "python", "python-2.7", "configparser" ]
Trying to install pip error with configparser
38,689,289
<p>I am trying to install pip and am getting some issues with configparser. Somehow the import configparser is pointing to the system version of python, python 2.7 instead of python 3.5 </p> <pre><code>&gt;&gt; pip install -U pip Traceback (most recent call last): File "/Users/../anaconda3/bin/pip", line 9, in &lt;...
0
2016-07-31T23:35:37Z
38,689,800
<p>Modify PYTHONPATH to have python 3.x packages path before 2.x packages path</p>
0
2016-08-01T01:16:46Z
[ "python", "python-2.7", "configparser" ]
How should I be going about exiting python script when user types 'q'?
38,689,323
<p>I'm trying to add code to exit my curses python script correctly when the user types <code>q</code>. I can't merely do <code>CTRL+C</code> because then curses won't be de-initialized correctly.</p> <p>I haven't found a good solution with getting user input that has a timeout so the program doesn't sit there until t...
-2
2016-07-31T23:42:11Z
38,707,781
<p>The suggested answer <a href="http://stackoverflow.com/questions/24308583/python3-curses-how-to-press-q-for-ending-program-immediately">Python3 + Curses: How to press “q” for ending program immediately?</a> is a starting point, but (like the suggestion for using a separate thread) is not what is needed.</p> <p>...
1
2016-08-01T20:42:47Z
[ "python", "curses", "python-curses" ]
Copying Attributes from Superclass Instance while Inheriting?
38,689,362
<p>I'm trying to make a subclass that inherits from an instance of its superclass, and bases the majority of its attributes on the superclass attributes. </p> <pre><code>class Thing: def __init__(self, a, b, c): self.a = a self.b = b self.c = c class ThingWithD(Thing): def __init__(sel...
0
2016-07-31T23:50:33Z
38,689,449
<p>With class <code>Thing</code> defined as such:</p> <pre><code>class Thing: def __init__(self, a, b, c): self.a = a self.b = b self.c = c </code></pre> <p>I can think of 3 ways to do achieve what you are asking using classical inheritence. The first, is to take advantage of your known ar...
1
2016-08-01T00:07:46Z
[ "python", "inheritance", "subclass", "python-3.4", "superclass" ]
Copying Attributes from Superclass Instance while Inheriting?
38,689,362
<p>I'm trying to make a subclass that inherits from an instance of its superclass, and bases the majority of its attributes on the superclass attributes. </p> <pre><code>class Thing: def __init__(self, a, b, c): self.a = a self.b = b self.c = c class ThingWithD(Thing): def __init__(sel...
0
2016-07-31T23:50:33Z
38,689,483
<p>The most concise—and object-oriented—way would probably be to just call the superclass's <code>__init__()</code> method and avoid the repetition:</p> <pre><code>class Thing: def __init__(self, a, b, c): self.a = a self.b = b self.c = c class ThingWithD(Thing): def __init__(self,...
2
2016-08-01T00:14:27Z
[ "python", "inheritance", "subclass", "python-3.4", "superclass" ]
Python Error 'list index out of range' When Using Split Function
38,689,515
<p>Im am trying to pull info from yahoo finance using urllib2 and then using the split function to display the Net Income. When I go to run the program in the Python 2.7.12 shell I have to print the command "yahooNetIncome('')" with the stock symbol in the single quotes. Whenever I do this it comes up with the error "f...
-2
2016-08-01T00:21:04Z
38,689,551
<p>Your list index out of range means that your call to the <code>split()</code> method didn't find anything to split on. Therefore, there wouldn't be an index <code>1</code> (no splits, only one index), causing a list index out of range error to be thrown. </p>
0
2016-08-01T00:28:44Z
[ "python", "python-2.7" ]
Python Error 'list index out of range' When Using Split Function
38,689,515
<p>Im am trying to pull info from yahoo finance using urllib2 and then using the split function to display the Net Income. When I go to run the program in the Python 2.7.12 shell I have to print the command "yahooNetIncome('')" with the stock symbol in the single quotes. Whenever I do this it comes up with the error "f...
-2
2016-08-01T00:21:04Z
38,689,674
<p>You're getting bitten by a couple of things.</p> <p>The out-of-range error you're getting is due to there being nothing in the list that you're trying to get the zeroth element of in your <code>NI</code> assignment line. That list is empty because the <code>split()</code> call is failing, and it's failing because t...
1
2016-08-01T00:54:09Z
[ "python", "python-2.7" ]
Multiprocessing using map
38,689,526
<p>I have a list of strings and on every string I am doing some changes that you can see in <code>wordify()</code>. Now, to speed this up, I split up the list into sublists using <code>chunked()</code> (the number of sublists is the number of CPU cores - 1). That way I get lists that look like <code>[[,,],[,,],[,,],[,,...
0
2016-08-01T00:22:35Z
38,689,558
<p>You have write your code so that you're just passing a single function to <code>map</code>; it's not smart enough to know that your hoping it passes <code>wordlist</code> into the second argument of your function. </p> <p>TBH partial function application is a bit clunky in Python, but you can use <code>functools.pa...
1
2016-08-01T00:29:39Z
[ "python", "dictionary", "multiprocess" ]
How to get dictionary values from list of lists (any language)?
38,689,547
<p>I most interested in simplicity, so would appreciate solution in any language (also interesting how it would look using LINQ). I tried to do it in Python, but failed.</p> <p>From these two lists:</p> <pre><code>init_li1 = [[234,45,1,86,2,0],[324,6,1],[123,1111,3]] init_li2 = ["Alpha", "Beta", "Gamma"] </code></pre...
-1
2016-08-01T00:27:28Z
38,689,555
<p>Actually, it's very easy in Python:</p> <pre><code>dictionary = dict(zip(init_li2, init_li1)) </code></pre> <p>You see, the <code>dict</code> constructor can be used like this:</p> <pre><code>dict(('key1', 'value1'), ('key2', 'value2')) </code></pre> <p>Well, <code>zip()</code> will generate tuples by taking cor...
1
2016-08-01T00:29:05Z
[ "c#", "python", "list", "dictionary" ]