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
Access to Django settings using Redis
39,427,603
<p>I have a project on Heroku. I just recently added Redis for job queueing through Heroku's add-ons feature.</p> <p>I've followed Heroku's simple <a href="https://devcenter.heroku.com/articles/python-rq" rel="nofollow">tutorial</a> to get things up and running.</p> <p>I call the function like so: <code>result = q.en...
0
2016-09-10T15:31:15Z
39,460,208
<p>Someone with the power please close this question.</p> <p>It turns at that <code>DJANGO_SETTINGS_MODULE</code> was not set properly.</p>
0
2016-09-12T23:32:20Z
[ "python", "django", "heroku" ]
Adding/Updating object to/in nested array in mongodb
39,427,607
<p>I have a document:</p> <pre><code>{ "_id": "57d421bbbc44538f0634081c", "in_date": "1473724800", "bboxes": [ { "bbox_index": "4124432432311", "data": {} }, { "bbox_index": "4124435342332", "data": {} }, ... ] } </code></pre> <p>I'm trying to update entire object found in <code>bboxes</code...
1
2016-09-10T15:31:28Z
39,608,868
<p>Instead of using <code>$push</code>, you can use <code>$addToSet</code> which will insert a new entry in the array only if the entry doesn't exist yet.</p> <p>To paraphrase the relevant manual page <a href="https://docs.mongodb.com/manual/reference/operator/update/addToSet/" rel="nofollow">https://docs.mongodb.com/...
0
2016-09-21T06:22:25Z
[ "python", "mongodb", "pymongo" ]
How to traverse cyclic directed graphs with modified DFS algorithm
39,427,638
<p><strong>OVERVIEW</strong></p> <p>I'm trying to figure out how to traverse <strong>directed cyclic graphs</strong> using some sort of DFS iterative algorithm. Here's a little mcve version of what I currently got implemented (it doesn't deal with cycles):</p> <pre><code>class Node(object): def __init__(self, na...
22
2016-09-10T15:34:11Z
39,456,032
<p>Before I start, <a href="http://www.codeskulptor.org/#user42_MYuqELNPFl_7.py" rel="nofollow">Run the code on CodeSkulptor!</a> I also hope that the comments elaborate what I have done enough. If you need more explanation, look at my explanation of the <em>recursive</em> approach below the code.</p> <pre><code># If ...
7
2016-09-12T17:54:10Z
[ "python", "algorithm", "python-2.7", "depth-first-search", "demoscene" ]
How to traverse cyclic directed graphs with modified DFS algorithm
39,427,638
<p><strong>OVERVIEW</strong></p> <p>I'm trying to figure out how to traverse <strong>directed cyclic graphs</strong> using some sort of DFS iterative algorithm. Here's a little mcve version of what I currently got implemented (it doesn't deal with cycles):</p> <pre><code>class Node(object): def __init__(self, na...
22
2016-09-10T15:34:11Z
39,465,446
<p>As per <a href="http://stackoverflow.com/questions/39427638/how-to-traverse-cyclic-directed-graphs-with-modified-dfs-algorithm#comment66244567_39427638">comment66244567</a> - reducing the graph to a tree by ignoring links to visited nodes and performing a breadth-first search, as this would produce a more natural-lo...
1
2016-09-13T08:27:56Z
[ "python", "algorithm", "python-2.7", "depth-first-search", "demoscene" ]
How to send parameters in bitstamp api using python requests module
39,427,756
<p>I am trying to use Bitstamp api and am able to successfully call any thing that only requires key, signature, and nonce parameters. However, when I try transferring or ordering, which require additional parameters like address or price and amount, my request seems to get messed up. I am new to programming, apis and ...
0
2016-09-10T15:44:48Z
39,429,943
<p>You should be using <em>data =</em> not <em>params</em>:</p> <pre><code>requests.post(self.url + 'sell/btcusd/', data={'key':self.api_key, 'signature':signature, 'nonce': nonce, 'amount': amount, 'price':price}) </code></pre> <p>When you use <em>data =</em>, the data is sent in the body of the request:</p> <pre><...
0
2016-09-10T19:41:49Z
[ "python", "python-requests", "bitcoin" ]
Is there a way to manually install modules for python?
39,427,840
<p>I keep running into problems with installing modules for python. Either because the modules themselves aren't able to be downloaded via pip or because of some error or another. </p> <p>Is it possible to simply download the module as a .zip or tar.gz file (as I see a lot of links to do just that) and then somehow pl...
-1
2016-09-10T15:53:06Z
39,437,190
<p>As you noticed, you can download a module's source (usually in the form of a <code>.tar.gz</code> archive) from <a href="https://pypi.python.org" rel="nofollow">PyPI</a>. First, unpack the archive, then enter the folder that is created. Assuming that your Python binary is on your path, simply run</p> <pre><code>pyt...
0
2016-09-11T14:39:18Z
[ "python", "module", "install" ]
How to import the six library to python 2.5.2
39,427,946
<p>I'm wondering how I can import the six library to python 2.5.2? It's not possible for me to install using pip, as it's a closed system I'm using.</p> <p>I have tried to add the six.py file into the lib path. and then use "import six". However, it doesnt seem to be picking up the library from this path.</p>
0
2016-09-10T16:03:53Z
39,427,972
<p>You can't use <code>six</code> on Python 2.5; it requires Python 2.6 or newer.</p> <p>From the <a href="https://bitbucket.org/gutworth/six" rel="nofollow"><code>six</code> project homepage</a>:</p> <blockquote> <p>Six supports every Python version since 2.6.</p> </blockquote> <p>Trying to install <code>six</cod...
0
2016-09-10T16:05:45Z
[ "python", "python-import" ]
How to import the six library to python 2.5.2
39,427,946
<p>I'm wondering how I can import the six library to python 2.5.2? It's not possible for me to install using pip, as it's a closed system I'm using.</p> <p>I have tried to add the six.py file into the lib path. and then use "import six". However, it doesnt seem to be picking up the library from this path.</p>
0
2016-09-10T16:03:53Z
39,428,032
<p>According to project history, <a href="https://bitbucket.org/gutworth/six/src/a9b120c9c49734c1bd7a95e7f371fd3bf308f107?at=1.9.0" rel="nofollow">version 1.9.0</a> supports Python 2.5. Compatibility broke with 1.10.0 release.</p> <blockquote> <p>Six supports every Python version since 2.5. It is contained in only ...
1
2016-09-10T16:12:11Z
[ "python", "python-import" ]
Removing new line character from Resultset (Python)
39,427,977
<p>I have ResultSet that contains information as below - </p> <pre><code>[&lt;div id="Description"&gt;\n This is the content example.\n\r\nThese characters I need to remove from complete string.\n\r\nI tried strip,lstrip,rstrip and replace.\n\r\nBut for these I found the Attributeerror: resultset object has no attr...
-1
2016-09-10T16:06:04Z
39,428,029
<p><code>ResultSet</code> is a simple <code>list</code> subclass. <code>str.strip()</code> does not exist on lists, nor on the <code>div</code> element.</p> <p>Get the <em>text</em> from each element, you can use the <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#get-text" rel="nofollow"><code>Tag.get...
1
2016-09-10T16:12:08Z
[ "python", "beautifulsoup" ]
Use selenium with chromedriver on Mac
39,428,042
<p>I want to use selenium with chromedriver on Mac,but I have some troubles on it.</p> <ol> <li>I download the chromedriver from <a href="https://sites.google.com/a/chromium.org/chromedriver/home" rel="nofollow">ChromeDriver - WebDriver for Chrome</a></li> <li>But I don't want to put it to PATH.So I do this.</li> </ol...
0
2016-09-10T16:12:58Z
39,428,368
<blockquote> <p>selenium.common.exceptions.WebDriverException: Message: 'chromedriver' executable needs to be in PATH.</p> </blockquote> <p><a href="http://stackoverflow.com/questions/8255929/running-webdriver-chrome-with-selenium">To launch chrome browser using <code>ChromeDriver</code></a> you need to pass <a href...
0
2016-09-10T16:48:35Z
[ "python", "selenium" ]
Using a list as arguments for a function in OCaml
39,428,119
<p>I am currently trying to learn OCaml. And I am searching for the equivalent of this python code:</p> <pre><code>f(*l[:n]) </code></pre> <p>I thought I'd try to write a function that emulates this behavior, but it doesn't work. Here is the code:</p> <pre><code>let rec arg_supply f xs n = if n = 0 then ...
3
2016-09-10T16:20:40Z
39,428,421
<p>Your Python function <code>f</code> is being passed different numbers of arguments, depending on the value of <code>n</code>. This can't be expressed in OCaml. Functions take a statically fixed number of arguments (i.e., you can tell the number of arguments by reading the source code).</p> <p>The way to pass differ...
3
2016-09-10T16:53:50Z
[ "python", "ocaml" ]
How to find and group similar permutations of 4 digits
39,428,151
<p>I am not good at these, but please bear with me. I have a set of numbers from my database / list, all are 4 digit numbers with the numbers between and include 0000 through 9999.</p> <p>Say the list is:</p> <pre><code>[1234, 4354, 6554, 2134, 3214, 5456, 9911, 1199] </code></pre> <p>Basically, I want to group them...
-4
2016-09-10T16:24:40Z
39,429,226
<p>Here's a (tested in Python 2.7.10) solution:</p> <pre><code>def index(number): digits = list(str(number)) return ''.join(sorted(digits)) groups = {} numbers = [1234, 4354, 6554, 2134, 3214, 5456, 9911, 1199] for number in numbers: key = index(number) if key not in groups: groups[key] = []...
0
2016-09-10T18:22:56Z
[ "python", "permutation" ]
How to find and group similar permutations of 4 digits
39,428,151
<p>I am not good at these, but please bear with me. I have a set of numbers from my database / list, all are 4 digit numbers with the numbers between and include 0000 through 9999.</p> <p>Say the list is:</p> <pre><code>[1234, 4354, 6554, 2134, 3214, 5456, 9911, 1199] </code></pre> <p>Basically, I want to group them...
-4
2016-09-10T16:24:40Z
39,429,263
<p>Not sure what you want to do about naming the groups, but you can use <code>itertools.groupby</code> after converting the ints to strings, and sorting those characters</p> <pre><code>from itertools import groupby l = [1234, 4354, 6554, 2134, 3214, 5456, 9911, 1199] # ints to (int, sorted str) s = map(lambda x: (x...
0
2016-09-10T18:26:12Z
[ "python", "permutation" ]
Why am I getting NameError?
39,428,155
<p>Here's a part of the the code I'm trying to run:</p> <pre><code>def func1(): a = True while a == True: try: guess = int(input("guess it: ")) a = False except ValueError: print("Not a valid number.") import random number = random.randint(0, 50) print("Im t...
2
2016-09-10T16:24:58Z
39,428,221
<p>You're getting the error because <code>guess</code> only exists in the scope of <code>func1()</code>. You need to return the value <code>guess</code> from <code>func1()</code> to use it. </p> <p>Like so:</p> <pre><code>def func1(): a = True while a == True: try: guess = int(input("guess...
1
2016-09-10T16:33:25Z
[ "python", "python-3.5" ]
Determine list of all possible products from a list of integers in Python
39,428,179
<p>In Python 2.7 I need a method that returns all possible products of a <code>list or tuple of int</code>. Ie. if input is <code>(2, 2, 3, 4)</code>, then I'd want a output like</p> <ul> <li><code>(3, 4, 4)</code>, 2 * 2 = 4</li> <li><code>(2, 4, 6)</code>, 2 * 3 = 6</li> <li><code>(2, 3, 8)</code>, 2 * 4 = 8</li> <l...
-2
2016-09-10T16:27:38Z
39,428,545
<p>Your problem is basically one of find all subsets of a given set (multiset in your case). Once you have the subsets its straight forward to construct the output you've asked for.</p> <p>For a set A find all the subsets [S0, S1, ..., Si]. For each subset Si, take <code>(A - Si) | product(Si)</code>, where <code>|</c...
0
2016-09-10T17:07:28Z
[ "python", "algorithm", "combinations", "combinatorics" ]
Determine list of all possible products from a list of integers in Python
39,428,179
<p>In Python 2.7 I need a method that returns all possible products of a <code>list or tuple of int</code>. Ie. if input is <code>(2, 2, 3, 4)</code>, then I'd want a output like</p> <ul> <li><code>(3, 4, 4)</code>, 2 * 2 = 4</li> <li><code>(2, 4, 6)</code>, 2 * 3 = 6</li> <li><code>(2, 3, 8)</code>, 2 * 4 = 8</li> <l...
-2
2016-09-10T16:27:38Z
39,428,550
<p>Suppose you have a vector of 4 numbers (for instance (2,2,3,4)).</p> <p>You can generate a grid (as that one showed below):</p> <pre><code>0 0 0 0 0 0 0 1 0 0 1 0 0 0 1 1 0 1 0 0 0 1 0 1 0 1 1 0 0 1 1 1 1 0 0 0 1 0 0 1 1 0 1 0 1 0 1 1 1 1 0 0 1 1 0 1 1 1 1 0 1 1 1 1 </code></pre> <p>Now remove the rows with all ...
0
2016-09-10T17:08:05Z
[ "python", "algorithm", "combinations", "combinatorics" ]
Determine list of all possible products from a list of integers in Python
39,428,179
<p>In Python 2.7 I need a method that returns all possible products of a <code>list or tuple of int</code>. Ie. if input is <code>(2, 2, 3, 4)</code>, then I'd want a output like</p> <ul> <li><code>(3, 4, 4)</code>, 2 * 2 = 4</li> <li><code>(2, 4, 6)</code>, 2 * 3 = 6</li> <li><code>(2, 3, 8)</code>, 2 * 4 = 8</li> <l...
-2
2016-09-10T16:27:38Z
39,428,596
<p>You can break this down into three steps:</p> <ul> <li>get all the permutations of the list of numbers</li> <li>for each of those permutations, create all the possible partitions</li> <li>for each sublist in the partitions, calculate the product</li> </ul> <p>For the permutations, you can use <code>itertools.permu...
-1
2016-09-10T17:13:42Z
[ "python", "algorithm", "combinations", "combinatorics" ]
Why does "".join() appear to be slower than +=
39,428,239
<p>Despite this question <a href="http://stackoverflow.com/questions/39312099/why-is-join-faster-than-in-python">Why is &#39;&#39;.join() faster than += in Python?</a> and it's answers and this great explanation of the code behind the curtain: <a href="https://paolobernardi.wordpress.com/2012/11/06/python-string-concat...
-5
2016-09-10T16:35:06Z
39,428,265
<p>You called <code>''.join()</code> on <strong>one huge string</strong>, not a list (multiplying a string produces a larger string). This forces <code>str.join()</code> to iterate over that huge string, joining 74k <em>individual <code>'x'</code> characters</em>. In other words, your second test does 74 times more wor...
4
2016-09-10T16:38:00Z
[ "python" ]
Why does "".join() appear to be slower than +=
39,428,239
<p>Despite this question <a href="http://stackoverflow.com/questions/39312099/why-is-join-faster-than-in-python">Why is &#39;&#39;.join() faster than += in Python?</a> and it's answers and this great explanation of the code behind the curtain: <a href="https://paolobernardi.wordpress.com/2012/11/06/python-string-concat...
-5
2016-09-10T16:35:06Z
39,428,310
<p>You are not comparing the same operation because your first operation added the long string every iteration while join added every item of the string seperatly. (See also @MartijnPieters answer)</p> <p>If I run a comparison I get completly different timings suggesting that <code>str.join</code> is much faster:</p> ...
2
2016-09-10T16:42:27Z
[ "python" ]
Simple way to use the google contacts API from a python script
39,428,290
<p>I'm currently trying to write a script and I would need to access my GMail contacts to finish it. I tried googling that a bit and it looks like there are a few libraries to do that, but some answers seems very old, and some others aren't that clear.</p> <p>What is the correct way currently to access the contacts AP...
0
2016-09-10T16:40:05Z
39,436,655
<p>Here is what I'm using in the end :</p> <pre><code>if arg == "--init": gflow = OAuth2WebServerFlow(client_id='&lt;ID&gt;', client_secret='&lt;secret&gt;', scope='https://www.googleapis.com/auth/contacts.readonly', redirect_uri='http://localhost'); gflo...
0
2016-09-11T13:35:55Z
[ "python", "google-api", "google-api-python-client" ]
Django model form doesn't populate when instance=object is set
39,428,350
<p>I'm trying to populate a ModelForm with existing data if it exists or create a new instance if not. I've read the <a href="https://docs.djangoproject.com/en/1.9/topics/forms/modelforms/" rel="nofollow">django docs</a> and several questions here on Stack Overflow but I can't figure out why my form doesn't populate wi...
0
2016-09-10T16:46:38Z
39,428,513
<p>Because you're <em>also</em> passing <code>request.POST</code>. That is supposed to contain the <em>submitted</em> data, which would naturally override the values already in the instance; but since you're doing that on a GET, the POST data is empty, so your form is displayed empty.</p> <p>Only pass request.POST int...
1
2016-09-10T17:03:55Z
[ "python", "django", "modelform" ]
Debugging TemplateNotFound postmortem django 1.9
39,428,395
<p>Been couple days of trying to get my template loaded in view - keep getting error in subj. Here is postmortem <a href="http://pastebin.com/JJCtPyYj" rel="nofollow">http://pastebin.com/JJCtPyYj</a> You can see in there TEMPLATE_DIRS being defined. Tried django 1.10, 1.9.9, 1.8.7. Any clues on how to further debug thi...
0
2016-09-10T16:51:59Z
39,428,499
<p>TEMPLATE_DIRS is not relevant, and has not been since Django 1.8. As you can see from the traceback, the relevant setting is the DIRS part of TEMPLATES, and that is empty: you need to put the directories in there.</p>
0
2016-09-10T17:02:20Z
[ "python", "django" ]
Unknown layer type (crop) in Caffe for windows
39,428,481
<p>I want to use the following convolutional neural network:</p> <p><a href="http://lmb.informatik.uni-freiburg.de/people/ronneber/u-net/" rel="nofollow">http://lmb.informatik.uni-freiburg.de/people/ronneber/u-net/</a></p> <p>with caffe built from <a href="https://github.com/BVLC/caffe/tree/windows" rel="nofollow">ht...
2
2016-09-10T16:59:39Z
39,432,128
<p><strong>Solution:</strong></p> <p>You should modify <code>net.prototxt</code> from:</p> <p><code>layers { ... type: CROP }</code> to </p> <p><code>layer { ... type: "Crop" }</code></p> <p>and meanwhile, other layers' parameter in the prototxt should also be modified similarly to:</p> <p><code>layer { ... type...
1
2016-09-11T01:44:56Z
[ "python", "caffe" ]
How to add a dimension to a numpy array in Python
39,428,496
<p>I have an array that is size (214, 144). I need it to be (214,144,1) is there a way to do this easily in Python? Basically the dimensions are supposed to be (Days, Times, Stations). Since I only have 1 station's data that dimension would be a 1. However if I could also make the code flexible enough work for say 2 st...
0
2016-09-10T17:01:43Z
39,428,598
<p>You could use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html" rel="nofollow"><code>reshape</code></a>:</p> <pre><code>&gt;&gt;&gt; a = numpy.array([[1,2,3,4,5,6],[7,8,9,10,11,12]]) &gt;&gt;&gt; a.shape (2, 6) &gt;&gt;&gt; a.reshape((2, 6, 1)) array([[[ 1], [ 2], [ 3]...
4
2016-09-10T17:14:13Z
[ "python", "arrays", "numpy", "dimensions" ]
How to add a dimension to a numpy array in Python
39,428,496
<p>I have an array that is size (214, 144). I need it to be (214,144,1) is there a way to do this easily in Python? Basically the dimensions are supposed to be (Days, Times, Stations). Since I only have 1 station's data that dimension would be a 1. However if I could also make the code flexible enough work for say 2 st...
0
2016-09-10T17:01:43Z
39,428,642
<p><strong>1)</strong> To add a dimension to an array <code>a</code> of arbitrary dimensionality:</p> <pre><code>b = numpy.reshape (a, list (numpy.shape (a)) + [1]) </code></pre> <p><strong>Explanation:</strong></p> <p>You get the shape of <code>a</code>, turn it into a list, concatenate <code>1</code> to that list,...
0
2016-09-10T17:18:38Z
[ "python", "arrays", "numpy", "dimensions" ]
How to "flatten" a Panda Panel by summing up specific columns
39,428,505
<p>I am still familairizing myself with Pandas, and Python in general, so please excuse if this is a simple question. I'd also like to avoid one liners so I can understand the underlying actions if possible! :)</p> <p>I've managed to pull data data which results in a Panel, with four items. The key of each item is a...
1
2016-09-10T17:02:53Z
39,433,840
<pre><code>agg_dict = {'Quarterly Sales': 'sum', 'Ending Inventory': 'last'} pnl.to_frame().T.stack(0).groupby(level='Type').agg(agg_dict) </code></pre> <p><a href="http://i.stack.imgur.com/ztaiy.png" rel="nofollow"><img src="http://i.stack.imgur.com/ztaiy.png" alt="enter image description here"></a></p>
0
2016-09-11T07:30:12Z
[ "python", "pandas" ]
Best approach to make a reverse five-star calculator
39,428,609
<p>In the 5-star rating system, I have a known number of ratings.<br> I have the final (weighted) average of all those N ratings, let's say it is R (float to two decimal places).<br> I would like to write a python script which generates all possible combinations (Total of weighted averages) and print out only the one(s...
2
2016-09-10T17:15:12Z
39,428,989
<p>(inefficient) Brute force solution. </p> <p>Note: Can make more efficient by replacing <code>product(range(0, N+1), repeat=5)</code> with something else that can generate a list of 5 numbers that sum to N. </p> <p>Find all lists of length 5 (for the ratings) up to N, then calculate the weighted average and compare...
0
2016-09-10T17:57:07Z
[ "python", "algorithm" ]
Best approach to make a reverse five-star calculator
39,428,609
<p>In the 5-star rating system, I have a known number of ratings.<br> I have the final (weighted) average of all those N ratings, let's say it is R (float to two decimal places).<br> I would like to write a python script which generates all possible combinations (Total of weighted averages) and print out only the one(s...
2
2016-09-10T17:15:12Z
39,429,980
<p>You can enumerate all the distributions of votes using a recursive algorithm and then check which of those have correct weighted average. But note that the number of combinations grows quickly.</p> <pre><code>def distributions(ratings, remaining): if len(ratings) &gt; 1: # more than one rating: take som...
0
2016-09-10T19:47:02Z
[ "python", "algorithm" ]
Best approach to make a reverse five-star calculator
39,428,609
<p>In the 5-star rating system, I have a known number of ratings.<br> I have the final (weighted) average of all those N ratings, let's say it is R (float to two decimal places).<br> I would like to write a python script which generates all possible combinations (Total of weighted averages) and print out only the one(s...
2
2016-09-10T17:15:12Z
39,430,271
<p>The total number of stars is N*R (20 * 3.85 = 77 in your example). Now what you have similar to <a href="https://en.wikipedia.org/wiki/Change-making_problem" rel="nofollow">the change making problem</a> except that your total number of coins is fixed.</p> <p>An efficient solution might be to start with as many la...
0
2016-09-10T20:24:03Z
[ "python", "algorithm" ]
Best approach to make a reverse five-star calculator
39,428,609
<p>In the 5-star rating system, I have a known number of ratings.<br> I have the final (weighted) average of all those N ratings, let's say it is R (float to two decimal places).<br> I would like to write a python script which generates all possible combinations (Total of weighted averages) and print out only the one(s...
2
2016-09-10T17:15:12Z
39,431,051
<p>Here is an algorithm that doesn't use brute force. The indented code shows an example.</p> <p>You have the number of ratings N and their average R.<br> Let <code>si</code> be the number of i-stars ratings (with <code>i in [1..5]</code>).<br> We have <code>s1 + s2 + s3 + s4 + s5 = N</code>.<br> We also have <code>s1...
0
2016-09-10T22:12:11Z
[ "python", "algorithm" ]
python - print a csv row into a HTML column
39,428,639
<p>I'm trying to print the data of a CSV column into an HTML table</p> <p>CSV file is like this (sample) </p> <pre><code>firstname, surname firstname, surname firstname, surname firstname, surname firstname, surname firstname, surname firstname, surname </code></pre> <p>I can read this data in ok - and get it to pri...
1
2016-09-10T17:18:27Z
39,428,709
<p>You only need one <code>&lt;tr&gt;</code> to make a single row.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>table, td { border: solid 1px #CCC; }</code></pre> ...
-1
2016-09-10T17:26:49Z
[ "python", "html" ]
python - print a csv row into a HTML column
39,428,639
<p>I'm trying to print the data of a CSV column into an HTML table</p> <p>CSV file is like this (sample) </p> <pre><code>firstname, surname firstname, surname firstname, surname firstname, surname firstname, surname firstname, surname firstname, surname </code></pre> <p>I can read this data in ok - and get it to pri...
1
2016-09-10T17:18:27Z
39,428,879
<p>Some variables in sample are not set, but this is due to reducing of sample to aminimal size I guess, so if you fill in these details, the following should work (suboptimal if more than 7 entries due to the hardcoded 15% width on the html td element.</p> <pre><code>import csv import sys from fpdf import FPDF, HTMLM...
0
2016-09-10T17:44:55Z
[ "python", "html" ]
Colouring in between two lines in 3D plot
39,428,656
<p>I am trying the fill the space between my lines in 3D. </p> <p>I have the following code:</p> <pre><code>from mpl_toolkits.mplot3d import Axes3D from matplotlib.collections import PolyCollection import matplotlib.pyplot as plt import numpy as np class plotting3D(object): """ Class to plot 3d """ ...
1
2016-09-10T17:20:43Z
39,429,621
<p>Another solution to my suggestion in the comments is to use <code>fill_between</code>; there you have the possibility to set the lower boundary. <code>fill_between</code> returns a <code>PolyCollection</code>, so you can add it to the <code>3d</code> figure similar to what you are doing now:</p> <pre><code>from mpl...
1
2016-09-10T19:07:16Z
[ "python", "matplotlib" ]
Django INSTALLED_APPS not installed and preventing makemigrations
39,428,728
<p>I recently pulled a repo from GitHub to get a local copy on my machine. The backend uses Django, and I was working on updating some models. Since I changed some models I wanted to run <code>./manage.py makemigrations</code>. At first there was an issue with python2 vs python3, so I changed the <code>#!/usr/bin/env p...
0
2016-09-10T17:28:15Z
39,428,804
<p>They are in pip, albeit not in those names; they are <code>django-autofixture</code>, <code>django-bootstrap3</code> and <code>django-formtools</code> respectively.</p> <p>So you can install them by typing:</p> <pre><code>pip install django-autofixture django-bootstrap3 django-formtools </code></pre> <p><strong>E...
1
2016-09-10T17:36:17Z
[ "python", "django", "django-models", "pip" ]
Foreign key model in Django Admin
39,428,742
<p>I have two user roles in Django:</p> <ul> <li>Commercials</li> <li>Sellers</li> </ul> <p>I have created two models, Seller Model has a ForeignKey field to Commercials (every seller has a commercial related to). When I register the models in admin I can create Commercials and related sellers using <code>StackedInli...
0
2016-09-10T17:29:19Z
39,430,137
<p>There is no way to make a reverse relation (so to say) in the form of Inlines. The Django admin panel doesn't have that ability by default.</p> <p>What you could do is unregister the default UserAdmin, create a new Admin panel by inheriting the original one, and add this Seller as an Inline. There is still the issu...
0
2016-09-10T20:06:08Z
[ "python", "django", "django-models", "django-admin" ]
Foreign key model in Django Admin
39,428,742
<p>I have two user roles in Django:</p> <ul> <li>Commercials</li> <li>Sellers</li> </ul> <p>I have created two models, Seller Model has a ForeignKey field to Commercials (every seller has a commercial related to). When I register the models in admin I can create Commercials and related sellers using <code>StackedInli...
0
2016-09-10T17:29:19Z
39,430,241
<p><a href="https://github.com/s-block/django-nested-inline" rel="nofollow">Django nested inlines</a> library might help you.</p>
1
2016-09-10T20:20:14Z
[ "python", "django", "django-models", "django-admin" ]
Unable to click invisible select python
39,428,763
<p>I am trying to retrieve all possible lists from <a href="https://www.osram-americas.com/en-us/applications/automotive-lighting-systems/Pages/lrgmain.aspx" rel="nofollow">this website</a></p> <p>Model will only open when year is selected. Similarly Make will only open when Model is selected. I want to store all comb...
1
2016-09-10T17:31:12Z
39,429,008
<p>The element IDs change on each reload of the page, you'll have to find a different way to find the dropdown.</p> <p>You can always find the <code>&lt;a&gt;</code> link with the "-- Select Year --" text, for example. </p>
1
2016-09-10T17:59:53Z
[ "python", "selenium", "web-scraping" ]
Unable to click invisible select python
39,428,763
<p>I am trying to retrieve all possible lists from <a href="https://www.osram-americas.com/en-us/applications/automotive-lighting-systems/Pages/lrgmain.aspx" rel="nofollow">this website</a></p> <p>Model will only open when year is selected. Similarly Make will only open when Model is selected. I want to store all comb...
1
2016-09-10T17:31:12Z
39,429,236
<p>Use this CSS selector to get to the arrow pointing downwards on the select year dropdown</p> <pre><code>"div[id='fldYear'] &gt; div[class='sbHolder'] &gt; a[class='sbToggle']" </code></pre> <p>or this xpath</p> <pre><code>"//div[@id='fldYear']/div[@class='sbHolder']/a[@class='sbToggle']" </code></pre> <p>Click o...
1
2016-09-10T18:23:28Z
[ "python", "selenium", "web-scraping" ]
Unable to click invisible select python
39,428,763
<p>I am trying to retrieve all possible lists from <a href="https://www.osram-americas.com/en-us/applications/automotive-lighting-systems/Pages/lrgmain.aspx" rel="nofollow">this website</a></p> <p>Model will only open when year is selected. Similarly Make will only open when Model is selected. I want to store all comb...
1
2016-09-10T17:31:12Z
39,429,410
<blockquote> <p>Message: no such element: Unable to locate element: {"method":"id","selector":"sbToggle_27562807"}</p> </blockquote> <p><code>year</code> element is not hidden, actually your locator to locate element using <code>find_element_by_id('sbToggle_27562807')</code> is not correct. In this element <code>id<...
1
2016-09-10T18:43:17Z
[ "python", "selenium", "web-scraping" ]
Resizing NVSS FITS format file in Python and operating on this file in astropy
39,428,799
<p>this questions is probably mainly for more or less advances astronomers.</p> <p>Do you know how to transform NVSS fits file to the fits with only 2 (NOT 4!) axes? Or how to deal with the file which has 4 axis and generates the following errors in Python when I'm trying to overlapp nvss countours on optical DSS data...
-1
2016-09-10T17:35:21Z
39,437,514
<p>To clarify for general use: this is a question about how to handle FITS files with degenerate axes, which are commonly produced by the <a href="https://casa.nrao.edu/" rel="nofollow">CASA data reduction program</a> and other radio data reduction tools; the degenerate axes are frequency/wavelength and stokes. Some o...
1
2016-09-11T15:10:57Z
[ "python", "astronomy", "astropy", "fits", "pyfits" ]
Is this a recursive or iterative function?
39,428,810
<p>I am using the SICP book which is build for Scheme/Racket (lisp family). In this exercise I had some problems:</p> <p><em>1.11 A function f is defined by the rule that f(n) = n if n&lt;3 and f(n) = f(n - 1) + 2f(n - 2) + 3f(n - 3) if n> 3. Write a procedure that computes f by means of a recursive process. Write a p...
-1
2016-09-10T17:36:42Z
39,428,946
<p>The function that you reported is a recursive function.</p> <p>The Wikipedia <em>Recursion</em> page sentences:</p> <blockquote> <p>Recursion in computer science is a method where the solution to a problem depends on solutions to smaller instances of the same problem (as opposed to iteration).</p> </blockquote> ...
2
2016-09-10T17:52:34Z
[ "python", "recursion", "iteration", "racket", "sicp" ]
Is this a recursive or iterative function?
39,428,810
<p>I am using the SICP book which is build for Scheme/Racket (lisp family). In this exercise I had some problems:</p> <p><em>1.11 A function f is defined by the rule that f(n) = n if n&lt;3 and f(n) = f(n - 1) + 2f(n - 2) + 3f(n - 3) if n> 3. Write a procedure that computes f by means of a recursive process. Write a p...
-1
2016-09-10T17:36:42Z
39,429,032
<p>Your <code>funcao_f</code> function is recursive.</p> <p>The definition of <strong>recursive</strong> function can be: <em>f</em> is recursive if it calls <em>f</em> directly or indirectly, eg.:</p> <pre><code>def f(x): if x &lt;= 0: return 0 else: return g(x) def g(y): return 5 + f(x ...
1
2016-09-10T18:02:28Z
[ "python", "recursion", "iteration", "racket", "sicp" ]
Is this a recursive or iterative function?
39,428,810
<p>I am using the SICP book which is build for Scheme/Racket (lisp family). In this exercise I had some problems:</p> <p><em>1.11 A function f is defined by the rule that f(n) = n if n&lt;3 and f(n) = f(n - 1) + 2f(n - 2) + 3f(n - 3) if n> 3. Write a procedure that computes f by means of a recursive process. Write a p...
-1
2016-09-10T17:36:42Z
39,429,725
<p>Note that the question asks about recursive and iterative <em>processes</em>. In scheme, both will be implemented using a recursive <em>function</em> (or <em>procedure</em>, as used in SICP), but the evaluation will be quite different. Please make sure you understand the difference between a recursive function and a...
0
2016-09-10T19:16:40Z
[ "python", "recursion", "iteration", "racket", "sicp" ]
Is this a recursive or iterative function?
39,428,810
<p>I am using the SICP book which is build for Scheme/Racket (lisp family). In this exercise I had some problems:</p> <p><em>1.11 A function f is defined by the rule that f(n) = n if n&lt;3 and f(n) = f(n - 1) + 2f(n - 2) + 3f(n - 3) if n> 3. Write a procedure that computes f by means of a recursive process. Write a p...
-1
2016-09-10T17:36:42Z
39,430,548
<p>Adapting an iterative fibonacci answer</p> <p><a href="http://stackoverflow.com/a/15047141/901925">http://stackoverflow.com/a/15047141/901925</a></p> <pre><code>def f(n): a, b = 0, 1 for i in range(0, n): a, b = b, a + b return a </code></pre> <p>This problem is:</p> <pre><code>def far(n): ...
0
2016-09-10T21:04:08Z
[ "python", "recursion", "iteration", "racket", "sicp" ]
Creating a unique list with beautiful soup from href attribute Python
39,428,834
<p>I am trying to crate a unique list of all the hrefs on my anchor tags</p> <pre><code>from urllib2 import urlopen from bs4 import BeautifulSoup import pprint url = 'http://barrowslandscaping.com/' soup = BeautifulSoup(urlopen(url), "html.parser") print soup tag = soup.find_all('a', {"href": True}) set(tag) for ...
0
2016-09-10T17:39:39Z
39,428,883
<p>First, you can't call <code>set()</code> in place, it's a conversion that returns a value.</p> <pre><code>tag_set = set(tags) </code></pre> <p>Second, <code>set</code> doesn't necessarily understand the difference between Tag objects in BeautifulSoup. As far as it's concerned, two separate tags were found in the H...
3
2016-09-10T17:45:06Z
[ "python", "beautifulsoup", "unique", "href" ]
Templates doesnot exist
39,428,853
<p>I just start to learn Django and I stuck with a issue that i Can't solve. Me and My friend want to create a Web site, our project structure is like that <code>Projet --home ----migrations ----static ----templates ------home --------home.html --Projet --manage.py --db.sqlite3</code></p> <p>I get this error :</p> <p...
0
2016-09-10T17:42:00Z
39,428,914
<p>Put your <code>templates</code> folder in the same level of <code>manage.py</code></p> <pre><code>--home ----migrations ----static --Projet --templates ----home ------home.html --manage.py --db.sqlite3 </code></pre>
0
2016-09-10T17:48:32Z
[ "python", "django" ]
Python: Searching a file for a specific string and outputting the total string count
39,428,907
<p>Attempting to build a search functionality in python that takes an input value/string from the user, searches an external file, and then returns the total count (sum) of that requested value in the file.</p> <pre><code>if user_search_method == 1: with open("file.txt", 'r') as searchfile: for word in searchfile:...
2
2016-09-10T17:47:49Z
39,428,960
<p>You are printing the <code>total</code> in each iteration, you have to put it out of <code>for</code> loop. Also you can do this job more pythonic, using one generator expression:</p> <pre><code>if user_search_method == 1: with open("file.txt") as searchfile: total = sum(line.lower().split().count(user_...
2
2016-09-10T17:54:31Z
[ "python", "full-text-search" ]
Python: Searching a file for a specific string and outputting the total string count
39,428,907
<p>Attempting to build a search functionality in python that takes an input value/string from the user, searches an external file, and then returns the total count (sum) of that requested value in the file.</p> <pre><code>if user_search_method == 1: with open("file.txt", 'r') as searchfile: for word in searchfile:...
2
2016-09-10T17:47:49Z
39,428,977
<pre><code>if user_search_method == 1: total = 0 with open('file.txt') as f: for line in f: total += line.casefold().split().count(user_search_value.casefold()) print(total) </code></pre> <p>This is probably what you wanted doing.</p>
-1
2016-09-10T17:56:18Z
[ "python", "full-text-search" ]
Python: Searching a file for a specific string and outputting the total string count
39,428,907
<p>Attempting to build a search functionality in python that takes an input value/string from the user, searches an external file, and then returns the total count (sum) of that requested value in the file.</p> <pre><code>if user_search_method == 1: with open("file.txt", 'r') as searchfile: for word in searchfile:...
2
2016-09-10T17:47:49Z
39,429,046
<p>It feels like there might be something missing from your question, but I will try to get you to where it seems you want to go...</p> <pre><code>user_search_value = 'test' # adding this for completeness of # this example if user_search_method == 1: ...
0
2016-09-10T18:04:03Z
[ "python", "full-text-search" ]
Python Selenium - Timeout Exception
39,428,939
<p><br></p> <p>I'm using selenium to get the html for this site: <br> <code>http://timesofindia.indiatimes.com/world/us</code><br></p> <p>I'm using selenium because this site only gives you all the html if you scroll down. However when I run this code: <br></p> <pre><code> # Open the Driver driver = webdriver.Chrom...
1
2016-09-10T17:51:51Z
39,429,180
<p>You may need to <em>adjust the script timeout</em>:</p> <pre><code>driver.set_script_timeout(10) </code></pre>
0
2016-09-10T18:17:40Z
[ "python", "selenium-webdriver", "web-scraping", "timeout" ]
Insert items to lists within a list
39,428,982
<p>I want to create a list of multiple lists, considering one list in particular.</p> <p>For example: I want to add items from <code>a</code>, <code>b</code>, <code>c</code> into <code>x</code> list, and then append <code>x</code> to one main list.</p> <pre><code>mainlist = [] x = [1, 2, 3] # items will be added hear...
2
2016-09-10T17:56:27Z
39,428,996
<p>Just <em>zip</em> <em>x</em> with each of the lists <em>a,b,c</em> using a <em>list comp</em>:</p> <pre><code>x = [1, 2, 3] # items will be added hear. a = ['a1', 'b1', 'c1'] b = ['a2', 'b2', 'c2'] c = ['a3', 'b3', 'c3'] main_list = [zip(x, y) for y in a,b,c] </code></pre> <p>That will give you:</p> <pre><code>...
3
2016-09-10T17:58:36Z
[ "python", "list", "python-3.x" ]
All Permutations of a String in Python using Recursion
39,429,055
<p>I have this following Python code which returns a list of all the permutations of a given string using recursion. I tried my best to understand the working of the code but I am failed to do so. Can anyone please give me a breakdown of the code mentioned below?</p> <pre><code>def permute(s): out = [] # Base...
-1
2016-09-10T18:04:58Z
39,429,161
<p>If the length of the string is one, there is only on permutation, so it returns only that string in this case.</p> <p>If there are more letters, however, it goes through every letter in the string, they are each treated as the first letter in the permutations that get added in <code>out</code> in that iteration. Th...
0
2016-09-10T18:15:41Z
[ "python", "recursion", "data-structures", "permutation" ]
Simulate impulsive signal and plotting
39,429,058
<p>im trying to plot an impulsive signal (Taken from a scientific paper), the equation of the impulsive signal is: <a href="http://i.stack.imgur.com/Zxhig.png" rel="nofollow"><img src="http://i.stack.imgur.com/Zxhig.png" alt="Impact formula"></a></p> <p>where:</p> <p>Ar= Amplitude of the impulses and equals 1.5</p> ...
0
2016-09-10T18:05:16Z
39,429,260
<h1>1.</h1> <blockquote> <p>F=sampling freq. equals to 10 kHz</p> </blockquote> <p>But you wrote</p> <pre><code>F = 10 ** 3 </code></pre> <p>In Python <code>**</code> mean exponentiation, so this is just 10<sup>3</sup> = 1000. That is, you have used F = 1 kHz in your code.</p> <p>If you want to express 10.0 &tim...
2
2016-09-10T18:25:23Z
[ "python", "numpy", "signal-processing" ]
python find image with path in file
39,429,089
<p>I'd like to find svgs or pngs withing a file. The images are in a attribue v="..."</p> <p>A part of the file looks like this:</p> <pre><code>&lt;symbol alpha="1" type="marker" name="0"&gt; &lt;layer pass="0" class="SvgMarker" locked="0"&gt; &lt;prop k="angle" v="0"/&gt; &lt;prop k="fill" v="#000000"/&gt; &lt;prop ...
2
2016-09-10T18:07:48Z
39,429,432
<p>Is using regex a requirement? In case it isn't, an easier and cleaner approach would be to use <a href="http://lxml.de/" rel="nofollow">lxml</a>.</p> <p>As it seems that the URIs you want appear in <code>prop</code> elements where <code>k="name"</code>, you could use <a href="http://lxml.de/xpathxslt.html" rel="nof...
1
2016-09-10T18:46:42Z
[ "python", "regex" ]
python find image with path in file
39,429,089
<p>I'd like to find svgs or pngs withing a file. The images are in a attribue v="..."</p> <p>A part of the file looks like this:</p> <pre><code>&lt;symbol alpha="1" type="marker" name="0"&gt; &lt;layer pass="0" class="SvgMarker" locked="0"&gt; &lt;prop k="angle" v="0"/&gt; &lt;prop k="fill" v="#000000"/&gt; &lt;prop ...
2
2016-09-10T18:07:48Z
39,429,916
<p>This fails because you are using <code>regex.findall</code> and you have a group in your regex: <code>(\.svg|\.png)</code>. If you change that to non-capturing group <code>(?:\.svg|\.png)</code>, then <code>findall</code> will find the whole match.</p> <p>See the <a href="https://docs.python.org/2/library/re.html#r...
0
2016-09-10T19:38:13Z
[ "python", "regex" ]
Django admin - Inline with choices from database
39,429,127
<p>I need some basic help with the django admin site. What I basically want to do is to be able to populate an inline with choices from the database. For example consider the following models:</p> <pre><code>class Item(models.Model): description = models.CharField(max_length=100) class Category(models.Model): ...
0
2016-09-10T18:11:45Z
39,429,178
<p>You should replace your <code>ChoiceField</code> with a <a href="https://docs.djangoproject.com/en/1.10/ref/forms/fields/#modelchoicefield" rel="nofollow"><code>ModelChoiceField</code></a>. They allow you to specify a queryset to populate the choices.</p> <pre><code>category = forms.ModelChoiceField(queryset=Catego...
0
2016-09-10T18:17:27Z
[ "python", "django", "django-admin" ]
String information not saving on calendar array Python
39,429,155
<p>I created a script that would let me choose a month, then a day and save the name of a student.But when it loops, all the information previously entered is erased(when choosing another day in the same month). I really don't know how to save the info on the array. Here's my code, i use Python 3.0:</p> <pre><code>def...
0
2016-09-10T18:15:15Z
39,429,529
<p>Keeping each new student name could get unwieldy quickly using arrays. Instead of the list comprehension making a 2d array for each month, you could try creating a <a href="https://docs.python.org/3.5/tutorial/datastructures.html#dictionaries" rel="nofollow">dictionary</a> for each month instead using <code>day</cod...
0
2016-09-10T18:57:08Z
[ "python", "arrays", "calendar", "sublist" ]
pandas.DataFrame: mappings a column of a list of keys to a column of the list of values
39,429,189
<p>Here is the input:</p> <pre><code>df = pd.DataFrame({'keys': [('K0', 'K1'), ('K1', 'K2')], 'A': ['A0', 'A1']}) lookup_df = pd.DataFrame({'val': ['V1', 'V2', 'V3']}, index = ['K0', 'K1', 'K2']) </code></pre> <p>After some "join" operation, I'd like a new column be adde...
2
2016-09-10T18:18:37Z
39,430,871
<p>you can do it this way:</p> <pre><code>In [83]: df['val'] = df['keys'].str.join(',').str.split(',', expand=True).stack().map(lookup_df.val).unstack().apply(tuple) In [84]: df Out[84]: A keys val 0 A0 (K0, K1) (V1, V2) 1 A1 (K1, K2) (V2, V3) In [85]: lookup_df Out[85]: val K0 V1 K1 V2 K2 ...
2
2016-09-10T21:44:57Z
[ "python", "pandas", "dataframe" ]
pandas.DataFrame: mappings a column of a list of keys to a column of the list of values
39,429,189
<p>Here is the input:</p> <pre><code>df = pd.DataFrame({'keys': [('K0', 'K1'), ('K1', 'K2')], 'A': ['A0', 'A1']}) lookup_df = pd.DataFrame({'val': ['V1', 'V2', 'V3']}, index = ['K0', 'K1', 'K2']) </code></pre> <p>After some "join" operation, I'd like a new column be adde...
2
2016-09-10T18:18:37Z
39,432,808
<p>Shorter and avoid string manipulation:</p> <pre><code>df['val'] = df['keys'].apply(pd.Series).replace(lookup_df.val).apply(tuple) </code></pre>
2
2016-09-11T04:19:06Z
[ "python", "pandas", "dataframe" ]
pandas.DataFrame: mappings a column of a list of keys to a column of the list of values
39,429,189
<p>Here is the input:</p> <pre><code>df = pd.DataFrame({'keys': [('K0', 'K1'), ('K1', 'K2')], 'A': ['A0', 'A1']}) lookup_df = pd.DataFrame({'val': ['V1', 'V2', 'V3']}, index = ['K0', 'K1', 'K2']) </code></pre> <p>After some "join" operation, I'd like a new column be adde...
2
2016-09-10T18:18:37Z
39,433,605
<p>This isn't meant to be pretty.</p> <pre><code>dk = pd.DataFrame(df['keys'].tolist()).applymap(lambda x: lookup_df.val[x]) df['val'] = zip(dk[0], dk[1]) df </code></pre> <p><a href="http://i.stack.imgur.com/A5L1H.png" rel="nofollow"><img src="http://i.stack.imgur.com/A5L1H.png" alt="enter image description here"><...
2
2016-09-11T06:55:44Z
[ "python", "pandas", "dataframe" ]
Turtle Graphics Python, .mainloop()
39,429,227
<p>I am programming in Python and I have a few questions that I can't find the answer to anywhere(please read all questions as they build up to my last question):</p> <p>1.What Does the .mainloop() really do?I read the all the answers in Stack Overflow, I also checked the documentations explanation.</p> <p>2.Does the...
0
2016-09-10T18:22:56Z
39,429,408
<p>So mainloop() is an infinite loop that basically blocks the execution of your code at a certain point. You call it once (and only once). </p> <p>so lets say:</p> <pre><code>while true: circle.draw() sumden.mainloop() print "circle is being drawn" time.sleep(0.1) </code></pre> <p>You will never see the output and...
0
2016-09-10T18:43:12Z
[ "python", "user-interface", "events", "turtle-graphics", "event-loop" ]
Python Multiprocessing, Pool map - cancel all running processes if one, returns the desired result
39,429,243
<p>given the following Python code:</p> <pre><code>import multiprocessing def unique(somelist): return len(set(somelist)) == len(somelist) if __name__ == '__main__': somelist = [[1,2,3,4,5,6,7,8,9,10,11,12,13,2], [1,2,3,4,5], [1,2,3,4,5,6,7,8,9,1], [0,1,5,1]] pool = multiprocessing.Pool() reslist =...
3
2016-09-10T18:24:14Z
39,429,590
<p>Use <code>pool.imap_unordered</code> to view the results in any order they come up.</p> <pre><code>reslist = pool.imap_unordered(unique, somelist) pool.close() for res in reslist: if res: # or set other condition here pool.terminate() break pool.join() </code></pre> <p>You can iterate over an ...
4
2016-09-10T19:04:08Z
[ "python", "dictionary", "multiprocessing", "pool" ]
Python Multiprocessing, Pool map - cancel all running processes if one, returns the desired result
39,429,243
<p>given the following Python code:</p> <pre><code>import multiprocessing def unique(somelist): return len(set(somelist)) == len(somelist) if __name__ == '__main__': somelist = [[1,2,3,4,5,6,7,8,9,10,11,12,13,2], [1,2,3,4,5], [1,2,3,4,5,6,7,8,9,1], [0,1,5,1]] pool = multiprocessing.Pool() reslist =...
3
2016-09-10T18:24:14Z
39,429,604
<p>Without fancy IPC (inter-process communication) tricks, easiest is to use a <code>Pool</code> method with a callback function instead. The callback runs in the main program (in a thread created by <code>multiprocessing</code>), and consumes each result as it becomes available. When the callback sees a result you l...
1
2016-09-10T19:05:26Z
[ "python", "dictionary", "multiprocessing", "pool" ]
Statsmodels fit distribution among 0 and 1
39,429,297
<p>I am trying to fit a beta distribution that should be defined between 0 and 1 on a data set that only has samples in a subrange. My problem is that using the <code>fit()</code> function will cause the fitted PDF to be defined only between my smallest and largest values. For instance, if my dataset has samples betwe...
2
2016-09-10T18:29:37Z
39,435,822
<p>I came up with a partial solution that does the trick for me: I replicate my samples (for the datasets that are too small) and add dummy samples at 0 and 1. Although that increases the fit error, it is low enough for my purpose. Also, I asked in Google groups and got <a href="https://groups.google.com/d/msg/pystatsm...
0
2016-09-11T11:58:12Z
[ "python", "numpy", "statistics", "statsmodels" ]
Python regular expression. Find a sentence in a sentence
39,429,345
<p>I'm trying to find an expression "K others" in a sentence "Chris and 34K others"</p> <p>I tried with regular expression, but it doesn't work :(</p> <pre><code>import re value = "Chris and 34K others" m = re.search("(.K.others.)", value) if m: print "it is true" else: print "it is not" </code></pre>
1
2016-09-10T18:34:40Z
39,429,374
<p>You should use <code>search</code> rather than <code>match</code> unless you expect your regular expression to match at the beginning. The help string for <code>re.match</code> mentions that the pattern is applied at the start of the string.</p>
2
2016-09-10T18:38:57Z
[ "python", "regex", "python-2.7" ]
Python regular expression. Find a sentence in a sentence
39,429,345
<p>I'm trying to find an expression "K others" in a sentence "Chris and 34K others"</p> <p>I tried with regular expression, but it doesn't work :(</p> <pre><code>import re value = "Chris and 34K others" m = re.search("(.K.others.)", value) if m: print "it is true" else: print "it is not" </code></pre>
1
2016-09-10T18:34:40Z
39,429,396
<p>If you want to match something <em>within</em> the string, use <code>re.search</code>. <code>re.match</code> starts at the beginning, Also, change your RegEx to: <code>(K.others)</code>, the last <code>.</code> ruins the RegEx as there is nothing after, and the first <code>.</code> matches any character before. I re...
2
2016-09-10T18:41:45Z
[ "python", "regex", "python-2.7" ]
Python regular expression. Find a sentence in a sentence
39,429,345
<p>I'm trying to find an expression "K others" in a sentence "Chris and 34K others"</p> <p>I tried with regular expression, but it doesn't work :(</p> <pre><code>import re value = "Chris and 34K others" m = re.search("(.K.others.)", value) if m: print "it is true" else: print "it is not" </code></pre>
1
2016-09-10T18:34:40Z
39,429,525
<p>Guessing that you're web-page scraping "<em>you and 34k others liked this on Facebook</em>", and you're wrapping "K others" in a capture group, I'll jump straight to how to get the number:</p> <pre><code>import re value = "Chris and 34K others blah blah" # regex describes # a leading space, one or more characters...
3
2016-09-10T18:56:45Z
[ "python", "regex", "python-2.7" ]
Python basic spanning tree algorithm
39,429,376
<p>I cannot figure out how to implement a basic spanning tree in Python; an un-weighted spanning tree.</p> <p>I've learned how to implement an adjacency list:</p> <pre><code>for edge in adj1: x, y = edge[int(0)], edge[int(1)] if x not in adj2: adj2[x] = set() if y not in adj2: adj2[y] = set() adj2[x]....
0
2016-09-10T18:39:00Z
39,430,850
<p>You don't say which spanning-tree algorithm you need to use. DFS? BFS? Prim's with constant weights? Kruskal's with constant weights? Also, what do you mean by "nearest" unconnected vertex, since the graph is unweighted? All the vertices adjacent to a given vertex v will be at the same distance from v. Finally, are ...
0
2016-09-10T21:41:58Z
[ "python", "spanning-tree" ]
Loop to print name, removing one character at a time
39,429,397
<p>I'm having a little trouble creating a program which prints out the name of the user downwards that always removes the first character each row then when it's at the last letter go up again.</p> <p>This is what i have so far: </p> <pre><code>name = input("Put in a name: ") name_length = len(name) for counter in r...
1
2016-09-10T18:41:46Z
39,429,486
<p>I think it will work:</p> <pre><code>name = input("Put in a name: ") for i in range(len(name)): # for 1st half print(name[i:]) for i in range(len(name)-2,-1,-1): # for 2nd half print(name[i:]) </code></pre> <p><strong>Input:</strong></p> <pre><code>stack </code></pre> <p><strong>Output:</strong...
1
2016-09-10T18:52:33Z
[ "python", "for-loop" ]
Loop to print name, removing one character at a time
39,429,397
<p>I'm having a little trouble creating a program which prints out the name of the user downwards that always removes the first character each row then when it's at the last letter go up again.</p> <p>This is what i have so far: </p> <pre><code>name = input("Put in a name: ") name_length = len(name) for counter in r...
1
2016-09-10T18:41:46Z
39,429,568
<p>This is an approach that just uses a single loop and slicing to achieve the same end. It creates a list of the indices at which the slice should begin, and then steps through that list printing as it goes.</p> <pre><code>name = "Bilbo" a = range(len(name)) a = a[:-1] + a[::-1] for idx in a: print name[idx:] <...
0
2016-09-10T19:02:14Z
[ "python", "for-loop" ]
Loop to print name, removing one character at a time
39,429,397
<p>I'm having a little trouble creating a program which prints out the name of the user downwards that always removes the first character each row then when it's at the last letter go up again.</p> <p>This is what i have so far: </p> <pre><code>name = input("Put in a name: ") name_length = len(name) for counter in r...
1
2016-09-10T18:41:46Z
39,429,572
<p>Recursive answer</p> <p>Essentially, print the same string twice, but in-between call the function again, but with the first character removed. When the start index is greater than the length of the string - 1, then you have one character left. </p> <pre><code>def printer(str, start=0): s = str[start:] if ...
0
2016-09-10T19:02:44Z
[ "python", "for-loop" ]
How to debug "IndexError: string index out of range" in Python?
39,429,442
<p>I am trying to solve Ex. 9.6 Think Python 3.</p> <blockquote> <p>Question: Write a function called is_abecedarian that returns True if the letters in a word appear in alphabetical order (double letters are ok). How many abecedarian words are there?</p> </blockquote> <p>What I have written:</p> <pre><code>fin= o...
-1
2016-09-10T18:47:15Z
39,458,632
<p><em>(Posted on behalf of the OP)</em>.</p> <p>Final solution:</p> <pre><code>fin= open('words.txt') for line in fin: line=fin.readline() word=line.strip() c=0 index=0 while index!=(len(word)-1): i=(word[index]) j=(word[index+1]) index=index+1 if ord(j)&gt;=ord(i...
1
2016-09-12T20:53:14Z
[ "python", "python-3.x" ]
Loading construct library causes error - no viable alternative
39,429,472
<p>When I try to load the construct library v 2.5.4, in python 2.5.4 it is causing this error. Any idea how to resolve? Is there something I can adapt/edit in the library to fix this</p> <pre><code>SyntaxError: ('no viable alternative at input \'""\'', ('/Users/blahblah/Documents/lib/java-classes/lib/Lib/construct/lib...
-1
2016-09-10T18:50:55Z
39,430,076
<p>You are running in some environment that suppresses a proper traceback printing and instead gives you the raw representation of the exception object. It says that the error is in line 66, column 16 and then gives the line.</p> <pre><code> return b"".join(_char_to_bin[int(ch)] for ch in data) </code></pre> ...
0
2016-09-10T19:58:13Z
[ "python", "python-module", "construct" ]
How to specify "nullable" return type with type hints
39,429,526
<p>Suppose I have a function:</p> <pre><code>def get_some_date(some_argument: int=None) -&gt; %datetime_or_None%: if some_argument is not None and some_argument == 1: return datetime.utcnow() else: return None </code></pre> <p>How do I specify the return type for something that can be <code>No...
6
2016-09-10T18:56:49Z
39,429,578
<p>Since your return type can be <code>datetime</code> (as returned from <code>datetime.utcnow()</code>) or <code>None</code> you should use <code>Optional[datetime]</code>:</p> <pre><code>from typing import Optional def get_some_date(some_argument: int=None) -&gt; Optional[datetime]: # as defined </code></pre> ...
10
2016-09-10T19:03:06Z
[ "python", "python-3.x", "python-3.5", "type-hinting" ]
TypeError: int() argument must be a string, a bytes-like object or a number, not datetime.datetime
39,429,579
<p>TypeError: int() argument must be a string, a bytes-like object or a number, not datetime.datetime</p> <p>Okay.. I deleted complete database. EVEN Restarted My PC.</p> <p>Models.py</p> <pre><code>from django.db import models from django.core.urlresolvers import reverse class Register(models.Model): first_n...
-2
2016-09-10T19:03:08Z
39,430,715
<p>You are defining a <strong>default</strong> value of a <code>ForeignKey</code> to be a <code>datetime</code> object. A <code>ForeignKey</code> should be an <code>Integer</code> representing the ID of some other table.</p> <p>The problem is in this piece of code</p> <pre><code>migrations.AddField( model_name='l...
2
2016-09-10T21:27:13Z
[ "python", "django", "datetime", "typeerror" ]
Using stack in python gives NoneType error
39,429,582
<p>I am trying to push an item on to stack in Python. Below is the code for trying to push the item :</p> <pre><code>class Search def generalGraphSearch(problem,fringe): closed=set() #If no nodes if problem.isGoalState(problem.getStartState()): return problem.getStartState() #Create object of Stack...
-2
2016-09-10T19:03:22Z
39,429,648
<p>You are trying to print the result of <code>push()</code> method call, but the method <em>does not return anything</em> - that's why you see <code>None</code> printed.</p> <p>Instead, you meant to either explore the contents of the <code>list</code> attribute:</p> <pre><code>stackOb.push(problem.getStartState()) p...
0
2016-09-10T19:09:30Z
[ "python", "python-2.7", "stack" ]
converting chr() / ord() with multi characters
39,429,601
<p>beginner programming in python (3.4)<br> is it possible to pass multiple values inside chr() and ord()? what i tried is the following:</p> <pre><code>userInput = input('Please write your input: ') &gt; Hello result = ord(userInput) #here is the error because i put multiple values instead of just one print(result) <...
1
2016-09-10T19:05:20Z
39,429,634
<p>You can use <code>map</code> to apply the function to each element:</p> <pre><code>&gt;&gt;&gt; for n in map(ord, 'Hello'): ... print(n, end=' ') ... 72 101 108 108 111 </code></pre>
0
2016-09-10T19:08:34Z
[ "python" ]
converting chr() / ord() with multi characters
39,429,601
<p>beginner programming in python (3.4)<br> is it possible to pass multiple values inside chr() and ord()? what i tried is the following:</p> <pre><code>userInput = input('Please write your input: ') &gt; Hello result = ord(userInput) #here is the error because i put multiple values instead of just one print(result) <...
1
2016-09-10T19:05:20Z
39,429,635
<p>You can use <code>map</code> function, in order to apply the <code>ord</code> on all characters separately:</p> <pre><code>In [18]: list(map(ord, 'example')) Out[18]: [101, 120, 97, 109, 112, 108, 101] </code></pre> <p>Or use <code>bytearray</code> directly on string:</p> <pre><code>In [23]: list(bytearray('examp...
0
2016-09-10T19:08:34Z
[ "python" ]
converting chr() / ord() with multi characters
39,429,601
<p>beginner programming in python (3.4)<br> is it possible to pass multiple values inside chr() and ord()? what i tried is the following:</p> <pre><code>userInput = input('Please write your input: ') &gt; Hello result = ord(userInput) #here is the error because i put multiple values instead of just one print(result) <...
1
2016-09-10T19:05:20Z
39,429,650
<p>Use a list comprehension - apply <code>ord</code> to each character in the string.</p> <pre><code>In [777]: [ord(i) for i in 'hello'] Out[777]: [104, 101, 108, 108, 111] </code></pre>
0
2016-09-10T19:09:32Z
[ "python" ]
converting chr() / ord() with multi characters
39,429,601
<p>beginner programming in python (3.4)<br> is it possible to pass multiple values inside chr() and ord()? what i tried is the following:</p> <pre><code>userInput = input('Please write your input: ') &gt; Hello result = ord(userInput) #here is the error because i put multiple values instead of just one print(result) <...
1
2016-09-10T19:05:20Z
39,429,656
<p>You could use a list comprehension to apply <code>ord</code> to every character of the string, and then join them to get the result you're looking for:</p> <pre><code>result = " ".join([str(ord(x)) for x in userInput]) </code></pre>
0
2016-09-10T19:10:21Z
[ "python" ]
Pydrive deleting file from Google Drive
39,429,627
<p>I´m writing a small script in python 3.5.2 with pydrive 1.2.1 and I need to be able to delete a file which is not stored locally in my computer, but in my account of Google Drive. The <a href="http://pythonhosted.org/PyDrive/filemanagement.html#delete-trash-and-un-trash-files" rel="nofollow">docs</a> only show how ...
1
2016-09-10T19:07:50Z
39,429,783
<p>From the docs seems that <code>drive.CreateFile()</code> create only a reference to a file, this can be local or remote. As you can se <a href="http://pythonhosted.org/PyDrive/filemanagement.html#download-file-content" rel="nofollow">here</a> <code>drive.CreateFile()</code> is used to download a remote file.</p> <p...
1
2016-09-10T19:23:03Z
[ "python", "pydrive" ]
Pandas selecting duplicates that occur n times
39,429,671
<p>I have a dataframe how would I select duplicates that occur two times only</p> <pre><code>import pandas as pd df=pd.DataFrame({'Name':['Two','Twice','Twice','three','three','three','one', 'Two'], 'key':[2,2,2,1,1,3,1,1,], 'Last':['Foo','Macy','Gayson','Simpson','Diablo','Niggah','Simpson', 'Mortimer'] }) r=df[df...
0
2016-09-10T19:11:23Z
39,429,788
<p>try this:</p> <pre><code>In [80]: df.groupby('Name').filter(lambda x: len(x) == 2) Out[80]: Last Name key 0 Foo Two 2 1 Macy Twice 2 2 Gayson Twice 2 7 Mortimer Two 1 </code></pre>
0
2016-09-10T19:23:31Z
[ "python", "pandas", "dataframe", "duplicates" ]
Python paramiko: redirecting stderr is affected by get_pty = True
39,429,680
<p>I am trying to implement an ssh agent that will allow me later, among other things, to execute commands in blocking mode, where output is being read from the channel as soon as it is available.<br> Here's what I have so far: </p> <pre><code>from paramiko import client class SSH_Agent: def __init__(self, serv...
0
2016-09-10T19:11:58Z
39,526,279
<p>Assuming you're running on a *nix system, you could try setting <code>TERM</code> in your command environment instead of creating a pty.</p> <p>For example:</p> <pre><code>def execute_command(self, command, out_streams = [sys.stdout], err_streams = [sys.stderr], poll_intervals = POLL_INTERVALS): # Pre-pend req...
1
2016-09-16T07:46:57Z
[ "python", "ssh", "paramiko", "stderr", "io-redirection" ]
How to use nameFilters with QDirIterator?
39,429,800
<p>In PySide, when I use <code>QDirIterator</code>, how I can filter on files by name?</p> <p>In the documentation, it talks about the parameter <code>nameFilters</code>:</p> <ul> <li><a href="https://srinikom.github.io/pyside-docs/PySide/QtCore/QDirIterator.html" rel="nofollow">https://srinikom.github.io/pyside-docs...
1
2016-09-10T19:24:26Z
39,430,301
<p>The <code>nameFilters</code> parameter is not a keyword argument.</p> <p>Unfortunately, PySide never raises an error if you pass keyword arguments that don't exist, which is a very poor design. APIs should never fail silently when given invalid inputs.</p> <p>Anyway, your code will work correctly if you use a posi...
0
2016-09-10T20:27:33Z
[ "python", "iterator", "pyside", "qdir" ]
No Reverse Match with Django Auth Views
39,429,807
<p>I created a custom User model following the example in the Django documentation, now I'm trying to use Django auth views but I keep getting <code>NoReverseMatch at /accounts/login/</code></p> <pre><code>Reverse for 'django.contrib.auth.views.login' with arguments '()' and keyword arguments '{}' not found. 0 pattern...
0
2016-09-10T19:24:55Z
39,429,835
<pre><code>{% url 'django.contrib.auth.views.login' %} </code></pre> <p>This is incorrect. We put the name given to the url here instead of the location of the view.</p> <p>Please see <a href="https://docs.djangoproject.com/en/1.10/ref/templates/builtins/#url" rel="nofollow">https://docs.djangoproject.com/en/1.10/ref...
2
2016-09-10T19:27:56Z
[ "python", "django" ]
When filtering content of 2 models together getting - 'tuple' object has no attribute '_meta'?
39,429,823
<p>I usually display filter options by one model.But now I have to allow to filter by the content of 2 models.</p> <pre><code>class Lease(CommonInfo): version = IntegerVersionField( ) amount = models.DecimalField(max_digits=7, decimal_places=2) is_notrenewed = models.BooleanField(default=False) unit =...
0
2016-09-10T19:26:37Z
39,430,112
<p><code>model</code> property must be a model, not a tuple of models - you are specifying two models for an object that accepts only one. For filtering based on related objects, you can do it like this: </p> <pre><code>class LeaseFilter(django_filters.FilterSet): class Meta: model = LeaseConditions ...
1
2016-09-10T20:02:50Z
[ "python", "django-filter" ]
Putting pixels with PIL gives error
39,429,886
<p>Newbie here. i tried to put some number of pixel with random RGB-colors (like adding noise):</p> <pre><code>from PIL import Image import random img=Image.open('pic.bmp') randomenter=int(input('Enter numpix: ')) for numpix in range(0, randomenter): x=random.randint(0,int(img.size[0])) y=random.randint(0,int(...
0
2016-09-10T19:34:06Z
39,430,146
<p>How posted @ŁukaszRogalsk, it solves by editing <code>x</code> and <code>y</code> to <code>img.size[0]-1</code> and <code>img.size[1]-1</code></p>
0
2016-09-10T20:07:25Z
[ "python", "python-imaging-library" ]
measure progress (time left) while os.listdir is generating a list (Python)
39,429,978
<p>In Python 2.7, I am using <code>os.listdir</code> to generate a list of files in a folder. There are lots of files and my connection to the folder is slow so it can take up to 30 seconds to complete. Here is an example:</p> <pre><code>import os import time start_time = time.time() dir_path = r'C:\Users\my_name\Doc...
2
2016-09-10T19:46:55Z
39,430,021
<p>You ought to use <code>scandir</code> which is only available with Python 3. </p> <p>But there is a <a href="https://pypi.python.org/pypi/scandir" rel="nofollow">back port.</a> </p> <p>To understand the problem, read <a href="https://www.python.org/dev/peps/pep-0471/" rel="nofollow">PEP 471</a>. </p>
0
2016-09-10T19:51:50Z
[ "python", "tkinter", "operating-system", "listdir" ]
Python Encode Spaces are incorrectly encoded
39,430,032
<p>I have a dictionary as follows </p> <pre><code>params = { 'response_type': 'token', 'client_id': o_auth_client_id, 'redirect_url': call_back_url, 'scope': 'activity heartrate location' } print urllib.urlencode(params) </code></pre> <p>and um encoding it </p> <p>but in results </p>...
0
2016-09-10T19:52:59Z
39,430,218
<p>Check the documentation for the <a href="https://docs.python.org/2/library/urllib.html#urllib.urlencode" rel="nofollow">urlencode</a>.</p> <p>The <code>quote_plus</code> method is used to change the spaces to plus symbol when it comes to passing key values. You can use <code>unquote_plus</code> method to remove the...
1
2016-09-10T20:17:55Z
[ "python", "encoding", "urlencode" ]
Python Encode Spaces are incorrectly encoded
39,430,032
<p>I have a dictionary as follows </p> <pre><code>params = { 'response_type': 'token', 'client_id': o_auth_client_id, 'redirect_url': call_back_url, 'scope': 'activity heartrate location' } print urllib.urlencode(params) </code></pre> <p>and um encoding it </p> <p>but in results </p>...
0
2016-09-10T19:52:59Z
39,430,347
<p>This program might do what you ask for. </p> <pre><code>import urllib def my_special_urlencode(params): return '&amp;'.join('{}={}'.format(urllib.quote(k, ''), urllib.quote(v, '')) for k,v in params.items()) params = { 'response_type': 'token', 'client_id': 'xxxxxx', 'redirect_url': 'h...
1
2016-09-10T20:34:03Z
[ "python", "encoding", "urlencode" ]
Extracting images from excel sheet by row with python
39,430,039
<p>I am trying to extract images from excel sheet. The excel sheet is basically a list of products with images and details of products.</p> <p>with</p> <pre><code>EmbeddedFiles = zipfile.ZipFile(path).namelist() ImageFiles = [F for F in EmbeddedFiles if F.count('.jpg') or F.count('.jpeg')] </code></pre> <p>I can ext...
1
2016-09-10T19:54:09Z
39,430,329
<p>The <code>xlsx</code> file is indeed in compressed format, but that does not mean that you have to expand it to work with it. Let <code>openpyxl</code> do that for you. The library in its documentation mentions that it can handle this format pretty well.</p> <p>So try opening the file and reading line by line using...
0
2016-09-10T20:30:39Z
[ "python", "excel", "image" ]
Raising exception from within except clause
39,430,157
<p>I'm wondering if we can do something like the following:<br> We catch socket error and if the message is different than some value,<br> raise the exception forward to be caught on the next general except clause below? </p> <pre><code>try: some logic to connect to a server.. except socket.error as se: ...
1
2016-09-10T20:09:12Z
39,430,304
<p>You can simply re-raise the exception with <code>raise</code> without arguments:</p> <pre><code>try: # some code except: if condition: raise </code></pre>
0
2016-09-10T20:27:44Z
[ "python", "exception-handling" ]
Raising exception from within except clause
39,430,157
<p>I'm wondering if we can do something like the following:<br> We catch socket error and if the message is different than some value,<br> raise the exception forward to be caught on the next general except clause below? </p> <pre><code>try: some logic to connect to a server.. except socket.error as se: ...
1
2016-09-10T20:09:12Z
39,430,332
<p>To do this, you need a set of try-catch blocks. Once, an exception has been caught, re-throwing the exception results in it being caught at the outer level. Try if else inside the blocks or simply nest try-except block in another one like this:</p> <pre><code>try: try: #... except: raise exc...
2
2016-09-10T20:31:02Z
[ "python", "exception-handling" ]
Raising exception from within except clause
39,430,157
<p>I'm wondering if we can do something like the following:<br> We catch socket error and if the message is different than some value,<br> raise the exception forward to be caught on the next general except clause below? </p> <pre><code>try: some logic to connect to a server.. except socket.error as se: ...
1
2016-09-10T20:09:12Z
39,450,876
<p>Here is an example:</p> <pre><code>#!/usr/bin/env python # -*- coding: utf-8 -*- try: num = 10 while True: denum = int(raw_input("&gt; ")) res = num/denum print str(res) except ZeroDivisionError: print "ZeroDivisionError" exit(0) except KeyboardInterrupt: pr...
0
2016-09-12T12:58:07Z
[ "python", "exception-handling" ]
Get UTC timestamp from time zone aware datetime object in Python
39,430,161
<p>I have a datetime object that I created with<code>datetime.datetime(year, month, day, hour, minute, tzinfo=pytz.timezone('US/Pacific'))</code>. Please correct me if I'm wrong, but I believe that my datetime object is NOT naïve. How do I convert this datetime object to a UTC timestamp?</p>
2
2016-09-10T20:09:27Z
39,430,248
<pre><code>non_naive_datetime_obj.astimezone(pytz.utc).timestamp() </code></pre>
0
2016-09-10T20:20:56Z
[ "python", "datetime", "utc" ]
Get UTC timestamp from time zone aware datetime object in Python
39,430,161
<p>I have a datetime object that I created with<code>datetime.datetime(year, month, day, hour, minute, tzinfo=pytz.timezone('US/Pacific'))</code>. Please correct me if I'm wrong, but I believe that my datetime object is NOT naïve. How do I convert this datetime object to a UTC timestamp?</p>
2
2016-09-10T20:09:27Z
39,430,270
<p>Use <code>datetime.astimezone</code> to get the same datetime in UTC (or any other timezone).</p> <pre><code>dt = datetime.datetime(year, month, day, hour, minute, tzinfo=pytz.timezone('US/Pacific')) dt_utc = dt.astimezone(pytz.timezone('UTC')) </code></pre>
2
2016-09-10T20:23:59Z
[ "python", "datetime", "utc" ]
python: efficient way to check only a couple of rows in a csvreader iterator?
39,430,351
<p>I have a (very large) CSV file that looks something like this:</p> <pre><code>header1,header2,header3 name0,rank0,serial0 name1,rank1,serial1 name2,rank2,serial2 </code></pre> <p>I've written some code that processes the file, and writes it out (using csvwriter) modified as such, with some information I compute ap...
2
2016-09-10T20:34:22Z
39,430,444
<p>If you're using the usual python method to read the file (<code>with open("file.csv","r") as f:</code> or equivalent), you can "reset" the file reading by calling <code>f.seek(0)</code>. </p> <p>Here is a piece of code that should (I guess) look a bit more like the way you're reading your file. It demonstate that r...
1
2016-09-10T20:46:52Z
[ "python", "csv" ]
python: efficient way to check only a couple of rows in a csvreader iterator?
39,430,351
<p>I have a (very large) CSV file that looks something like this:</p> <pre><code>header1,header2,header3 name0,rank0,serial0 name1,rank1,serial1 name2,rank2,serial2 </code></pre> <p>I've written some code that processes the file, and writes it out (using csvwriter) modified as such, with some information I compute ap...
2
2016-09-10T20:34:22Z
39,430,632
<p>I suppose if you do not want to just test the first few lines of the file, you could create a single iterator from a list and then the continuation of the csv reader.</p> <p>Given:</p> <pre><code>header1,header2,header3 name0,rank0,serial0 name1,rank1,serial1 name2,rank2,serial2 </code></pre> <p>You can do:</p> ...
1
2016-09-10T21:15:19Z
[ "python", "csv" ]
python: efficient way to check only a couple of rows in a csvreader iterator?
39,430,351
<p>I have a (very large) CSV file that looks something like this:</p> <pre><code>header1,header2,header3 name0,rank0,serial0 name1,rank1,serial1 name2,rank2,serial2 </code></pre> <p>I've written some code that processes the file, and writes it out (using csvwriter) modified as such, with some information I compute ap...
2
2016-09-10T20:34:22Z
39,430,654
<p>I think what you're trying to achieve is to use the first lines to decide between the type of processing, then re-use those lines for your read_all_csv_WITH_processing or read_all_csv_without_processing, while still not loading the full csv file in-memory. To achieve that you can load the first lines in a list and c...
0
2016-09-10T21:18:29Z
[ "python", "csv" ]
python: efficient way to check only a couple of rows in a csvreader iterator?
39,430,351
<p>I have a (very large) CSV file that looks something like this:</p> <pre><code>header1,header2,header3 name0,rank0,serial0 name1,rank1,serial1 name2,rank2,serial2 </code></pre> <p>I've written some code that processes the file, and writes it out (using csvwriter) modified as such, with some information I compute ap...
2
2016-09-10T20:34:22Z
39,431,018
<p>I will outline what I consider a much better approach. I presume this is happening over various runs. What you need to do is persist the files seen between runs and only process what has not been seen:</p> <pre><code>import pickle import glob def process(fle): # read_all_csv_with_processing def already_proce...
-1
2016-09-10T22:05:23Z
[ "python", "csv" ]