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
Duplicates / common elements between two lists
39,614,083
<p>I have a stupid question for people who are familiar with lists in Python. I want to get the common items in two lists. Assuming that I have this list :</p> <pre><code>dates_list = ['2016-07-08 02:00:02', '2016-07-08 02:00:17', '2016-07-08 02:00:03', '2016-07-08 02:00:20...
0
2016-09-21T10:32:09Z
39,614,264
<p>In order to find common elements in two lists, you may use <code>set()</code> as:</p> <pre><code>&gt;&gt;&gt; a = [1, 2, 3, 4] &gt;&gt;&gt; b = [3, 4, 5, 6] &gt;&gt;&gt; list(set(a).intersection(set(b))) [3, 4] </code></pre> <p>In your case, <code>b</code> is the list of lists. You need to firstly flatten the list...
2
2016-09-21T10:40:31Z
[ "python", "list", "python-2.7", "for-loop" ]
Duplicates / common elements between two lists
39,614,083
<p>I have a stupid question for people who are familiar with lists in Python. I want to get the common items in two lists. Assuming that I have this list :</p> <pre><code>dates_list = ['2016-07-08 02:00:02', '2016-07-08 02:00:17', '2016-07-08 02:00:03', '2016-07-08 02:00:20...
0
2016-09-21T10:32:09Z
39,616,046
<pre><code>import collections def flatten(iterable): for item in iterable: if isinstance(item, (str, bytes)): yield item if isinstance(item, collections.Sequence): yield from flatten(item) else: yield item a = [1, 6, 10] b = [[0, 1, 2], 3, [4], [5, (6, ...
0
2016-09-21T12:02:06Z
[ "python", "list", "python-2.7", "for-loop" ]
Assigning Group ID to components in networkx
39,614,149
<p>I have a graph which consists of nodes having "parentid" of hotels and "phone_search" stored in them. My main aim to build this graph was to connect all "parentid" which have similar "phone_search" (recursively), eg, if parentid A has phone_search 1,2; B has 2,3; C has 3,4; D has 5,6 and E has 6,7, then A,B, C will...
1
2016-09-21T10:35:16Z
39,614,615
<p>You want basically a list of nodes based on their component (not cluster), which is fairly straightforward. You need <a href="http://networkx.readthedocs.io/en/stable/reference/generated/networkx.algorithms.components.connected.connected_component_subgraphs.htmlhttp://" rel="nofollow"><code>connected_component_subgr...
1
2016-09-21T10:57:03Z
[ "python", "dictionary", "grouping", "networkx" ]
How to work with cookies with httplib in python
39,614,307
<p>I am sending soap request using httplib but when I send it I am getting the following issue:</p> <pre><code>INFO:root:Response:&lt;!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"&gt; &lt;html&gt;&lt;head&gt; &lt;title&gt;401 Authorization Required&lt;/title&gt; &lt;/head&gt;&lt;body&gt; &lt;h1&gt;Authorization Req...
1
2016-09-21T10:42:53Z
39,633,251
<p>Instead of httplib, I used the <code>urllib2</code> module. I need not set a cookie, I changed the code to use Digest type authentication, instead of Basic authentication:</p> <pre><code>password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm() password_mgr.add_password(None,uri=uri,user=username,passwd=password) au...
1
2016-09-22T07:49:26Z
[ "python", "python-2.7" ]
how __name__ change in python decorator
39,614,346
<p>Recently I'm learning Python decorator and the use of <code>functools.wraps</code>.</p> <pre><code>def a(): def b(): def c(): print('hello') return c return b print a.__name__ #output:a </code></pre> <p>I understand why the output is a.But I don't know how <code>__name__</code...
0
2016-09-21T10:44:37Z
39,614,464
<p>The point of decorators is to <em>replace</em> a function or class with what is returned by the decorator, when called with that function/class as argument. Decorators with arguments are a bit more convoluted, as you first call the outer method (<code>log</code>) to obtain a "parameterized" decorator (<code>decorato...
0
2016-09-21T10:50:01Z
[ "python" ]
how __name__ change in python decorator
39,614,346
<p>Recently I'm learning Python decorator and the use of <code>functools.wraps</code>.</p> <pre><code>def a(): def b(): def c(): print('hello') return c return b print a.__name__ #output:a </code></pre> <p>I understand why the output is a.But I don't know how <code>__name__</code...
0
2016-09-21T10:44:37Z
39,614,583
<pre><code>@log('...') def simple(... </code></pre> <p>is equivalent to</p> <pre><code>def simple(... simple = log('...')(simple) </code></pre> <p>so <code>log</code> is actually called, returning <code>decorator</code>, which is called with <code>simple</code> as argument which is then replaced by <code>decorator</...
0
2016-09-21T10:55:36Z
[ "python" ]
how __name__ change in python decorator
39,614,346
<p>Recently I'm learning Python decorator and the use of <code>functools.wraps</code>.</p> <pre><code>def a(): def b(): def c(): print('hello') return c return b print a.__name__ #output:a </code></pre> <p>I understand why the output is a.But I don't know how <code>__name__</code...
0
2016-09-21T10:44:37Z
39,614,587
<p>Some basics:</p> <pre><code>@decorator def f(): pass </code></pre> <p>is equivalent to:</p> <pre><code>def f(): pass f = decorator(f) </code></pre> <p>Decorator with args:</p> <pre><code>@decorator(*args, **kwargs) def f(): pass </code></pre> <p>is equivalent to:</p> <pre><code>def f(): pass d...
1
2016-09-21T10:55:51Z
[ "python" ]
Using an IF THEN loop with nested JSON files in Python
39,614,449
<p>I am currently writing a program which uses the ComapaniesHouse API to return a json file containing information about a certain company. </p> <p>I am able to retrieve the data easily using the following commands:</p> <pre><code>r = requests.get('https://api.companieshouse.gov.uk/company/COMPANY-NO/filing-history'...
0
2016-09-21T10:49:05Z
39,614,543
<p>You need to first convert your date variable to a datetime type using <a href="https://docs.python.org/2/library/datetime.html#datetime.datetime.strptime" rel="nofollow">datetime.strptime()</a></p> <p>You are comparing a list type variable <code>date</code> with datetime type variable <code>date_threshold</code>.</...
0
2016-09-21T10:53:37Z
[ "python", "json", "python-3.x" ]
Using a numpy array to assign values to another array
39,614,516
<p>I have the following numpy array <code>matrix</code> ,</p> <pre><code>matrix = np.zeros((3,5), dtype = int) array([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]) </code></pre> <p>Suppose I have this numpy array <code>indices</code> as well</p> <pre><code>indices = np.array([[1,3], [2,4], [0,4]...
2
2016-09-21T10:52:08Z
39,614,559
<p>Here's one approach using <a href="http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#combining-advanced-and-basic-indexing" rel="nofollow"><code>NumPy's fancy-indexing</code></a> -</p> <pre><code>matrix[np.arange(matrix.shape[0])[:,None],indices] = 1 </code></pre> <p><strong>Explanation</strong></p> ...
5
2016-09-21T10:54:09Z
[ "python", "arrays", "numpy", "indexing", "vectorization" ]
Using a numpy array to assign values to another array
39,614,516
<p>I have the following numpy array <code>matrix</code> ,</p> <pre><code>matrix = np.zeros((3,5), dtype = int) array([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]) </code></pre> <p>Suppose I have this numpy array <code>indices</code> as well</p> <pre><code>indices = np.array([[1,3], [2,4], [0,4]...
2
2016-09-21T10:52:08Z
39,647,476
<p>this involves loop and hence may not be very efficient for large arrays</p> <pre><code>for i in range(len(indices)): matrix[i,indices[i]] = 1 &gt; matrix Out[73]: array([[0, 1, 0, 1, 0], [0, 0, 1, 0, 1], [1, 0, 0, 0, 1]]) </code></pre>
0
2016-09-22T19:33:13Z
[ "python", "arrays", "numpy", "indexing", "vectorization" ]
sending raw data in python requests
39,614,675
<p>I'm trying to send a POST request with python requests, containing the following data: </p> <blockquote> <p>__VIEWSTATE=%2FwEPDwUJODgwODc4MzI2D2QWBAIEDxYCHgdWaXNpYmxlaGQCBg8WAh8AZxYCZg9kFhBmDw8WAh4EVGV4dAUl16jXmdep15XXnSDXntep16rXntepINeX15PXqSDXnNeQ16rXqGRkAgEPFgIeBWNsYXNzBSNmb3JtLWdyb3VwIGhhcy1mZWVkYmFjayBoYXMt...
0
2016-09-21T10:59:54Z
39,615,067
<p>There's no issue sending raw post data:</p> <pre><code>raw_data = '__VIEWSTATE=%2FwEPDwUJODgwODc4MzI2D2QWBAIEDxYCHgdWaXNpYmxlaGQCBg8WAh8AZxYCZg9kFhBmDw8WAh4EVGV4dAUl16jXmdep15XXnSDXntep16rXntepINeX15PXqSDXnNeQ16rXqGRkAgEPFgIeBWNsYXNzBSNmb3JtLWdyb3VwIGhhcy1mZWVkYmFjayBoYXMtc3VjY2VzcxYIAgEPDxYCHwEFLSog16nXnSDXntep16r...
2
2016-09-21T11:17:37Z
[ "python", "http", "python-requests" ]
Parsing and tabulating results
39,614,689
<p>What is a simple and flexible way to parse and tabulate output like the one below on a Unix system? </p> <p>The output has multiple entries in the following format: </p> <pre><code>===================================================== ====== SOLVING WITH MATRIX small_SPD ==== ==================================...
-3
2016-09-21T11:00:31Z
39,615,580
<p>If you're just parsing an output, I'd tackle it like this:</p> <pre><code>#!/usr/bin/env perl use strict; use warnings; #set paragraph mode - look for empty lines between records. local $/ = ''; #init the matrix/size vars. my $matrix; my $sizes; #output order my @columns = ( "COMPUTE TIME", "SOLVE TIME", "T...
1
2016-09-21T11:40:34Z
[ "python", "perl", "parsing" ]
Why isn't my monkey patching isn't working ?
39,614,766
<p>I am trying to add a method to a class that I import.</p> <p>This is my code : </p> <pre><code>from pyrser.parsing import node def to_dxml(self): return "test" node.Node().to_dxml = to_dxml tree = node.Node() tree.ls = [1, 2.0, "titi", True, [2, 3, 4, [3, [3, 4]], 5]] tree.dct = {"g":1, "y":2, "koko":{'D', ...
-1
2016-09-21T11:03:28Z
39,614,819
<p>You need to add attribute to the class, not object.</p> <pre><code>node.Node().to_dxml = to_dxml </code></pre> <p>Should be</p> <pre><code>node.Node.to_dxml = to_dxml </code></pre>
6
2016-09-21T11:05:50Z
[ "python" ]
Why is my condition in python not being met
39,614,869
<p>I have a list of filenames sorted by creation date. These files contain a datetime in the filename for their creation date time. I am attempting to create a sub list for all files after a certain time. </p> <p>Full list of files -</p> <pre><code>Allfilenames = ['CCN-200 data 130321055347.csv', 'CCN-200 data 130321...
0
2016-09-21T11:08:44Z
39,615,114
<p>In your filenames <code>hhmmss</code> exist from index <code>19:25</code> rather than <code>19:24</code>. So the correct statement to get the <code>hhmmss</code> from filename is:</p> <pre><code>filenames = [s for s in Allfilenames if os.path.basename(s)[19:25] &gt;= TOffRound] </code></pre>
0
2016-09-21T11:19:39Z
[ "python" ]
Why is my condition in python not being met
39,614,869
<p>I have a list of filenames sorted by creation date. These files contain a datetime in the filename for their creation date time. I am attempting to create a sub list for all files after a certain time. </p> <p>Full list of files -</p> <pre><code>Allfilenames = ['CCN-200 data 130321055347.csv', 'CCN-200 data 130321...
0
2016-09-21T11:08:44Z
39,615,387
<p>Instead of checking the time part as a string, I would suggest a stronger method to test the time part of your filename. This includes extracting the date part of the filename, retrieving the time value and comparing it on your specified time as a time object.</p> <pre><code>import re import datetime TOffRound = d...
1
2016-09-21T11:31:33Z
[ "python" ]
Why is my condition in python not being met
39,614,869
<p>I have a list of filenames sorted by creation date. These files contain a datetime in the filename for their creation date time. I am attempting to create a sub list for all files after a certain time. </p> <p>Full list of files -</p> <pre><code>Allfilenames = ['CCN-200 data 130321055347.csv', 'CCN-200 data 130321...
0
2016-09-21T11:08:44Z
39,617,662
<p>The problem with the code given, as suggested by others, is that you are missing the last digit. In terms of slicing a list, the "stop" number given after the : is not considered.</p> <pre><code>(eg): &gt;&gt; a = "hello world" &gt;&gt; print a[0:4] hell &gt;&gt; print a[0:5] hello </code></pre> <p>So, change this...
0
2016-09-21T13:16:12Z
[ "python" ]
How to create a prescription pill count like pain management facilities use?
39,614,930
<p>I don't understand why this code won't work. I want to create some code to help me know exactly how many pills need to be taken back to pain management. If you don't take the right amount back, then you get kicked out of pain management. So I'm just wanting to create a script that will help me so I don't take too...
0
2016-09-21T11:11:06Z
39,625,271
<p>In this line:</p> <pre><code>date1 = datetime.date(datetime.strptime((str(year) + "-" + str(starting_Month) + "-" + str(starting_Month) + "-" + str(starting_Day)), '%Y-%m-%d')) </code></pre> <p>You're telling <code>datetime.strptime</code> to parse a string of the form "year-month-day", but the string you give it ...
0
2016-09-21T19:44:23Z
[ "python" ]
Programming a function that saves and returns values in python
39,614,966
<p>I am currently experimenting with Python and programming a little text-adventure. In my game the player has certain properties like hp, attack damage and inventory slots for items. I want to be able to call these properties from everywhere in my code. For that I created a function that receives three values: </p> <...
1
2016-09-21T11:12:50Z
39,615,607
<p>First of all, your error is caused because of retrieving a variable that is not assigned - that just doesn't work. When you edit <code>player_hp</code>, it's not stored anywhere. you are returning it to the function that called it and not assigning it to anything. It just gets lost.</p> <p>Second of all, you should...
1
2016-09-21T11:41:47Z
[ "python", "function", "variables", "save", "call" ]
Programming a function that saves and returns values in python
39,614,966
<p>I am currently experimenting with Python and programming a little text-adventure. In my game the player has certain properties like hp, attack damage and inventory slots for items. I want to be able to call these properties from everywhere in my code. For that I created a function that receives three values: </p> <...
1
2016-09-21T11:12:50Z
39,617,454
<p>You asked, "<strong>Does the function not save the variable properly?</strong>"</p> <p>In general, <strong>Python functions do not save their state</strong>. The exception is functions that use the <code>yield</code> statement. If you write a function like this</p> <pre><code>def save_data(data): storage = dat...
0
2016-09-21T13:07:20Z
[ "python", "function", "variables", "save", "call" ]
Convert date string to UTC datetime
39,615,093
<p>I returned dates between two given dates:</p> <pre><code>for date in rrule(DAILY, dtstart = date1, until = date2): print date_item.strftime("%Y-%m-%d") </code></pre> <p>How to convert the <code>date_item</code> e.g. <code>2016-01-01</code> to ISO 8601 format like:<code>2016-01-01T18:10:18.000Z</code> in py...
1
2016-09-21T11:18:45Z
39,615,433
<p>I created a sample datetime object like shown below:</p> <pre><code>from datetime import datetime now = datetime.now() print now 2016-09-21 16:59:18.175038 </code></pre> <p>Here is the output, formatted to your requirement:</p> <pre><code>print datetime.strftime(now, "%Y-%m-%dT%H:%M:%S.000Z") '2016-09-21T16:59:1...
0
2016-09-21T11:33:37Z
[ "python" ]
Convert date string to UTC datetime
39,615,093
<p>I returned dates between two given dates:</p> <pre><code>for date in rrule(DAILY, dtstart = date1, until = date2): print date_item.strftime("%Y-%m-%d") </code></pre> <p>How to convert the <code>date_item</code> e.g. <code>2016-01-01</code> to ISO 8601 format like:<code>2016-01-01T18:10:18.000Z</code> in py...
1
2016-09-21T11:18:45Z
39,615,551
<p>You can use <code>strftime</code> to convert <code>date_item</code> in any format as per your requirement.see the below example</p> <pre><code>current_time = strftime("%Y-%m-%dT%H:%M:%SZ",gmtime()) print(current_time) </code></pre> <p>Output: </p> <pre><code>'2016-09-21T11:30:04Z' </code></pre> <p>so you can us...
1
2016-09-21T11:39:22Z
[ "python" ]
fill NaN with another lookup table
39,615,199
<p>Is there a way to fill the <code>NaN</code> with value for <code>test=default</code> by matching name, reticle and cell rev?</p> <p><a href="http://i.stack.imgur.com/8gZ38.png" rel="nofollow"><img src="http://i.stack.imgur.com/8gZ38.png" alt="enter image description here"></a></p> <p><a href="http://i.stack.imgur....
1
2016-09-21T11:23:11Z
39,615,395
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="nofollow"><code>set_index</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.unstack.html" rel="nofollow"><code>unstack</code></a> for reshaping, then <a href=...
2
2016-09-21T11:31:52Z
[ "python", "pandas", "dataframe", "multiple-columns", null ]
fill NaN with another lookup table
39,615,199
<p>Is there a way to fill the <code>NaN</code> with value for <code>test=default</code> by matching name, reticle and cell rev?</p> <p><a href="http://i.stack.imgur.com/8gZ38.png" rel="nofollow"><img src="http://i.stack.imgur.com/8gZ38.png" alt="enter image description here"></a></p> <p><a href="http://i.stack.imgur....
1
2016-09-21T11:23:11Z
39,620,971
<pre><code>for i in range(len(df)): if df.loc[i, 'value_new'] != df.loc[i, 'value_new']: df.loc[i, 'value_new'] = df.loc[(df.test == 'default') &amp; (df.name == df.loc[i, 'name']) &amp; (df.reticle == df.loc[i, 'reticle']) &amp...
0
2016-09-21T15:37:47Z
[ "python", "pandas", "dataframe", "multiple-columns", null ]
Python returns wrong truth table for logical implication
39,615,368
<p><a href="http://i.stack.imgur.com/CChne.png" rel="nofollow"><img src="http://i.stack.imgur.com/CChne.png" alt="enter image description here"></a></p> <p>I have implemented the above implication in Python but it does not return the expected results:</p> <pre><code> True True None True False None Fals...
-3
2016-09-21T11:30:41Z
39,615,430
<pre><code>def implies(a,b): if a: return b else:True return </code></pre> <p>Your error is in the last two lines, if !a, you aren't returning a specific value, so the result is <code>None</code>. You want:</p> <pre><code>def implies(a,b): if a: return b else: return True <...
2
2016-09-21T11:33:23Z
[ "python", "boolean-logic", "discrete-mathematics" ]
doc2vec - Input Format for doc2vec training and infer_vector() in python
39,615,420
<p>In gensim, when I give a string as input for training doc2vec model, I get this error : </p> <blockquote> <p>TypeError('don\'t know how to handle uri %s' % repr(uri))</p> </blockquote> <p>I referred to this question <a href="https://stackoverflow.com/questions/36780138/doc2vec-taggedlinedocument">Doc2vec : Tagg...
1
2016-09-21T11:33:05Z
39,715,845
<p><code>TaggedLineDocument</code> is a convenience class that expects its source file (or file-like object) to be space-delimited tokens, one per line. (That is, what you refer to as 'Case 1' in your 1st question.)</p> <p>But you can write your own iterable object to feed to gensim <code>Doc2Vec</code> as the <code>d...
0
2016-09-27T04:13:50Z
[ "python", "gensim", "word2vec", "doc2vec" ]
Fails to fix the seed value in LDA model in gensim
39,615,436
<p>When using LDA model, I get different topics each time and I want to replicate the same set. I have searched for the similar question in Google such as <a href="https://groups.google.com/forum/#!topic/gensim/s1EiOUsqT8s" rel="nofollow">this</a>.</p> <p>I fix the seed as shown in the article by <code>num.random.seed...
0
2016-09-21T11:33:45Z
39,651,384
<p>The dictionary generated by <code>corpora.Dictionary</code> may be different to the same corpus(such as same words but different order).So one should fix the dictionary as well as seed to get tht same topic each time.The code below may help to fix the dictionary:</p> <pre><code>dic = corpora.Dictionary(corpus) dic....
0
2016-09-23T01:55:03Z
[ "python", "numpy", "gensim" ]
Script to create multiple socket connections to multiple servers fast
39,615,439
<p>I have a list of server address in a file as below:</p> <pre><code>192.168.1.100 192.168.1.101 192.168.1.102 ... 192.168.1.200 </code></pre> <p>I want to write a program which create multiple socket connections from one PC client to all these servers (using the same source IP, source port and destination port) in ...
-1
2016-09-21T11:33:54Z
39,626,566
<p>You should be able to issue the 7K connects in a non-blocking fashion, then wait on them. Assuming they all succeed, the wait time of all of them will be overlapped. That should result in a much smaller overall delay.</p> <p>In other words, try something like this:</p> <pre><code>for (i = 0; i &lt; 7000; ++i) { ...
0
2016-09-21T21:04:13Z
[ "java", "python", "shell", "tcp", "network-programming" ]
What can cause this unicode object is not callable error in nosetests lib?
39,615,464
<p>I have a test case that tests some flow in an API (uses <code>requests.Session()</code> and makes multiple calls to our backend.)</p> <p>This test case passes on my mac and on other peoples macs. But when its executed in Jenkins I get an error. There are other similar tests cases like this that pass without issues ...
0
2016-09-21T11:34:56Z
39,617,973
<p>So there was a problem with my code.</p> <p>I used a statement <code>self.id = r.json()["orders"][0]["id"]</code></p> <pre><code># filename: test_payment_visa.py import unittest from tests.utils import WWHTTPClient import math from nose.plugins.attrib import attr class TestPaymentWorkflow(unittest.TestCase): ...
0
2016-09-21T13:28:32Z
[ "python", "jenkins", "nose" ]
converting dataframe to list of tuples on condition
39,615,476
<p>I have following df:</p> <pre><code> 1 2 3 4 1 NaN 0.000000 0.000000 0.000000 2 NaN 0.027273 0.000000 0.000000 3 NaN 0.000000 0.101449 0.000000 4 NaN 0.000000 0.000000 0.194245 5 NaN 0.000000 0.000000 0.000000 6 NaN 0.000000 0.000000 0.000000 7 NaN 0.000000 0.0...
1
2016-09-21T11:35:09Z
39,615,610
<p>You can first cast columns to <code>int</code> (if necessary), <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.unstack.html" rel="nofollow"><code>unstack</code></a> and use list comprehension, where is necessary convert first and second value in <code>tuples</code> to <code>int</code>...
1
2016-09-21T11:41:54Z
[ "python", "list", "pandas", "dataframe", "tuples" ]
How can I generate a random point (x, y) 10 steps apart from y0(a, b) in xy-plane?
39,615,495
<p>I have generated a random point named <code>y0=(a,b)</code> in xy-plane , How can I generate another random point <code>(x,y)</code> 10 steps apart from <code>y0</code>? </p> <p>note: by 10 steps apart from the firt point I don't mean the Euclidean distance. I mean the number of steps on lattice between the two po...
1
2016-09-21T11:36:02Z
39,615,688
<p>Let's say that your new point (x, y) is on a cercle of radius 10 and center (x0, y0). The random component is the angle.</p> <pre><code>import math as m # radius of the circle r = 10 # create random angle and compute coordinates of the new point theta = 2*m.pi*random.random() x = x0 + r*m.cos(theta) y = y0 + r*m.si...
1
2016-09-21T11:45:59Z
[ "python", "random" ]
How can I generate a random point (x, y) 10 steps apart from y0(a, b) in xy-plane?
39,615,495
<p>I have generated a random point named <code>y0=(a,b)</code> in xy-plane , How can I generate another random point <code>(x,y)</code> 10 steps apart from <code>y0</code>? </p> <p>note: by 10 steps apart from the firt point I don't mean the Euclidean distance. I mean the number of steps on lattice between the two po...
1
2016-09-21T11:36:02Z
39,615,862
<p>Let's say you have a point <code>(x, y)</code></p> <ol> <li><p>create another random point <em>anywhere</em> on the plane: <code>(x1, y2) = (random(), random())</code></p></li> <li><p>take the vector from your point to the new point: <code>(vx, vy) = (x1-x, y1-y)</code></p></li> <li><p>get the length <code>l</code>...
1
2016-09-21T11:54:34Z
[ "python", "random" ]
How can I generate a random point (x, y) 10 steps apart from y0(a, b) in xy-plane?
39,615,495
<p>I have generated a random point named <code>y0=(a,b)</code> in xy-plane , How can I generate another random point <code>(x,y)</code> 10 steps apart from <code>y0</code>? </p> <p>note: by 10 steps apart from the firt point I don't mean the Euclidean distance. I mean the number of steps on lattice between the two po...
1
2016-09-21T11:36:02Z
39,616,057
<pre><code>from random import random from math import sqrt # Deviation dev = 50 # Required distance between points l = 10 if __name__ == '__main__': # First random point x0, y0 = dev*random(), dev*random() # Second point x1 = dev*random() y1 = y0 + sqrt(l**2 - (x1 - x0)**2) # Output pr...
1
2016-09-21T12:02:57Z
[ "python", "random" ]
How can I generate a random point (x, y) 10 steps apart from y0(a, b) in xy-plane?
39,615,495
<p>I have generated a random point named <code>y0=(a,b)</code> in xy-plane , How can I generate another random point <code>(x,y)</code> 10 steps apart from <code>y0</code>? </p> <p>note: by 10 steps apart from the firt point I don't mean the Euclidean distance. I mean the number of steps on lattice between the two po...
1
2016-09-21T11:36:02Z
39,616,446
<p>So, you got the formula <code>d=d1+d2=|x-x0|+|y-y0| , for d=10</code></p> <p>Let's examine what's going on with this formula:</p> <ul> <li>Let's say we generate a random point P at (0,0) </li> <li>Let's say we generate <code>y=random.randint(0,50)</code> and let's imagine the value is 50. </li> </ul> <p>What does...
0
2016-09-21T12:22:26Z
[ "python", "random" ]
How can I generate a random point (x, y) 10 steps apart from y0(a, b) in xy-plane?
39,615,495
<p>I have generated a random point named <code>y0=(a,b)</code> in xy-plane , How can I generate another random point <code>(x,y)</code> 10 steps apart from <code>y0</code>? </p> <p>note: by 10 steps apart from the firt point I don't mean the Euclidean distance. I mean the number of steps on lattice between the two po...
1
2016-09-21T11:36:02Z
39,645,657
<p>this code generate a random point xy-plane named y0 then generate another point x0 10 steps apart from y0 in taxi distance .</p> <p>------- begining of the code-------- import random y0=(random.randint(0,50),random.randint(0,50))</p> <pre><code> while True: y=random.randint(0,50) x=(10 -abs(y-...
0
2016-09-22T17:46:53Z
[ "python", "random" ]
How can I generate a random point (x, y) 10 steps apart from y0(a, b) in xy-plane?
39,615,495
<p>I have generated a random point named <code>y0=(a,b)</code> in xy-plane , How can I generate another random point <code>(x,y)</code> 10 steps apart from <code>y0</code>? </p> <p>note: by 10 steps apart from the firt point I don't mean the Euclidean distance. I mean the number of steps on lattice between the two po...
1
2016-09-21T11:36:02Z
39,737,936
<p><code>abs(x)+abs(y)=10</code> defines a <a href="http://www.wolframalpha.com/input/?i=plot+abs(x)%2Babs(y)+%3D+10" rel="nofollow">square</a>, so all you need to do is pick a random value along the perimeter of the square (40 units long), and map that random distance back to your x,y coordinate pair.</p> <p>Somethin...
0
2016-09-28T04:14:08Z
[ "python", "random" ]
Django Login Form Returning false on is_valid() if username already exists
39,615,504
<p>I have a login form I created from Django's <code>User</code> model:</p> <p><strong>forms.py</strong>:</p> <pre><code>class LoginForm(ModelForm): class Meta: model = User fields = ['username', 'password'] widgets = { 'username': forms.TextInput(attrs={'placeholder': '@userna...
-1
2016-09-21T11:36:42Z
39,615,579
<p>A login form should not be a ModelForm. That's for creating or editing model instances - in this case, since you don't supply an <code>instance</code> parameter, Django assumes you want to create a new user.</p> <p>Just use a standard Form and define the username and password fields explicitly.</p> <p>Alternativel...
1
2016-09-21T11:40:30Z
[ "python", "django", "forms" ]
Pandas: write condition to filter in dataframe
39,615,506
<p>I have dataframe</p> <pre><code>member_id,event_time,event_path,event_duration 19440,"2016-08-09 08:26:48",accounts.google.com/ServiceLogin?service=mail&amp;passive=true&amp;rm=false&amp;continue=https://mail.google.com/mail/&amp;ss=1&amp;scc=1&amp;ltmpl=default&amp;ltmplcache=2&amp;emr=1&amp;osid=1#identifier,0 19...
0
2016-09-21T11:36:48Z
39,627,483
<p>Consider a <code>groupby.apply()</code> which uses a loop through <code>event_path</code> strings. With loop you can search adjacent elements by list indices:</p> <pre><code>def findevent(row): event_paths = row['event_path'].tolist() row['visiting'] = 2 for i in range(len(event_paths)): if...
1
2016-09-21T22:25:12Z
[ "python", "pandas" ]
Pandas: create word cloud from a column with strings
39,615,520
<p>I have a following <code>dataframe</code> with <code>string</code> values:</p> <pre><code> text 0 match of the day 1 euro 2016 2 wimbledon 3 euro 2016 </code></pre> <p>How can I create a <code>word cloud</code> from this column?</p>
1
2016-09-21T11:37:14Z
39,616,033
<p>I think you need <a href="http://stackoverflow.com/a/39172275/2901002">tuple of tuples</a> with frequencies, so use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.value_counts.html" rel="nofollow"><code>value_counts</code></a> with <code>list comprehension</code>:</p> <pre><code>tuples...
1
2016-09-21T12:01:30Z
[ "python", "string", "python-2.7", "pandas", "word-cloud" ]
NumPy genfromxt TypeError: data type not understood error
39,615,628
<p>I would like to read in this file (test.txt)</p> <pre><code>01.06.2015;00:00:00;0.000;0;-9.999;0;8;0.00;18951;(SPECTRUM)ZERO(/SPECTRUM) 01.06.2015;00:01:00;0.000;0;-9.999;0;8;0.00;18954;(SPECTRUM)ZERO(/SPECTRUM) 01.06.2015;00:02:00;0.000;0;-9.999;0;8;0.00;18960;(SPECTRUM)ZERO(/SPECTRUM) 01.06.2015;09:23:00;0.327;61...
0
2016-09-21T11:42:52Z
39,616,162
<p>From the <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.genfromtxt.html" rel="nofollow">numpy documentation</a></p> <blockquote> <p><strong>invalid_raise</strong> : bool, optional<br> If True, an exception is raised if an inconsistency is detected in the number of columns. If False, a warn...
2
2016-09-21T12:07:25Z
[ "python", "numpy", "genfromtxt" ]
NumPy genfromxt TypeError: data type not understood error
39,615,628
<p>I would like to read in this file (test.txt)</p> <pre><code>01.06.2015;00:00:00;0.000;0;-9.999;0;8;0.00;18951;(SPECTRUM)ZERO(/SPECTRUM) 01.06.2015;00:01:00;0.000;0;-9.999;0;8;0.00;18954;(SPECTRUM)ZERO(/SPECTRUM) 01.06.2015;00:02:00;0.000;0;-9.999;0;8;0.00;18960;(SPECTRUM)ZERO(/SPECTRUM) 01.06.2015;09:23:00;0.327;61...
0
2016-09-21T11:42:52Z
39,621,491
<p><code>usecols</code> can be used to ignore excess delimiters, e.g.</p> <pre><code>In [546]: np.genfromtxt([b'1,2,3',b'1,2,3,,,,,,'], dtype=None, delimiter=',', usecols=np.arange(3)) Out[546]: array([[1, 2, 3], [1, 2, 3]]) </code></pre>
0
2016-09-21T16:05:42Z
[ "python", "numpy", "genfromtxt" ]
send_mail is clearly sending email but no email is showing up in inbox
39,615,860
<p>I have these email settings in my <code>settings.py</code></p> <pre><code>EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = '[email protected]' EMAIL_HOST_PASSWORD = 'password' EMAIL_PORT = 587 </code></pre> <p>and am using this function to send email to recipients.</p> <pre><code>def send_emai...
1
2016-09-21T11:54:14Z
39,620,478
<p>Try to add the following in settings.py</p> <pre><code>EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' DEFAULT_FROM_EMAIL = EMAIL_HOST_USER </code></pre>
0
2016-09-21T15:16:17Z
[ "python", "django", "python-2.7", "email", "webserver" ]
Google App Engine Memcache Python
39,615,861
<p>Using Google App Engine <strong>Memcache</strong>... Can more than one user access the same key-value pair? or in other words.. Is there a Memcache created per user or is it shared across multiple users?</p>
0
2016-09-21T11:54:33Z
39,623,880
<p>Memcache is shared across users. It is not a cookie, but exists in RAM on the server for all pertinent requests to access.</p>
0
2016-09-21T18:22:18Z
[ "python", "google-app-engine", "memcached" ]
Google App Engine Memcache Python
39,615,861
<p>Using Google App Engine <strong>Memcache</strong>... Can more than one user access the same key-value pair? or in other words.. Is there a Memcache created per user or is it shared across multiple users?</p>
0
2016-09-21T11:54:33Z
40,032,242
<p>It's not shared between multiple applications if that's what you asked. Each of your instances on a single application will see a consistent view of the cache. </p> <p>From <a href="https://cloud.google.com/appengine/docs/java/memcache/?csw=1" rel="nofollow">documentation</a>: The cache is global and is shared acro...
2
2016-10-13T22:46:49Z
[ "python", "google-app-engine", "memcached" ]
Function to calculate value from first row in Python Pandas
39,615,871
<p>Is there any function in pandas to simulate excel formula like '=sum($A$1:A10'(for 10th row), i.e. the formula should take rolling data from 1st row.</p> <p>Pandas rolling function needs a integer value as window argument.</p>
0
2016-09-21T11:55:00Z
39,616,114
<p>The equivalent of <code>=SUM($A$1:A1)</code> in pandas is <code>.expanding().sum()</code> (requires pandas 0.18.0):</p> <pre><code>ser = pd.Series([1, 2, 3, 4]) ser Out[3]: 0 1 1 2 2 3 3 4 dtype: int64 ser.expanding().sum() Out[4]: 0 1.0 1 3.0 2 6.0 3 10.0 </code></pre> <p>You can al...
2
2016-09-21T12:05:31Z
[ "python", "pandas", "numpy" ]
Python for loop over list with directories does not find every value
39,616,041
<p>I have a list of directories. I try just to keep those, which are named by number and not have some string name, e.g. "lastStableBuild". The following code removes every non-digit named directory except from "lastUnsuccessfulBuild".</p> <pre><code>for dir in listdir: print(dir, " ", end="") if not dir.isdig...
0
2016-09-21T12:01:58Z
39,616,149
<p>Well, <a href="http://stackoverflow.com/questions/1207406/remove-items-from-a-list-while-iterating-in-python">don't change a list while iterating over it</a>.</p> <p>Use list comprehension:</p> <pre><code>listdir = [dir for dir in listdir if dir.isdigit()] </code></pre>
1
2016-09-21T12:07:02Z
[ "python", "for-loop" ]
Is there any difference between closing a cursor or a connection in SQLite?
39,616,077
<p>I have been using always the command <code>cur.close()</code> once I'm done with the database:</p> <pre><code>import sqlite3 conn = sqlite3.connect('mydb') cur = conn.cursor() # whatever actions in the database cur.close() </code></pre> <p>However, I just saw in some cases the following approach:</p> <pre><code>...
2
2016-09-21T12:03:35Z
39,616,258
<p><em>[On closing cursors]</em></p> <p>If you close the cursor, you are simply flagging it as invalid to process further requests ("I am done with this"). </p> <p>So, in the end of a function/transaction, you should keep closing the cursor, giving hint to the database that that transaction is finished.</p> <p>A goo...
1
2016-09-21T12:13:29Z
[ "python", "sqlite", "sqlite3", "cursor" ]
UPDATE MySQL with 'onclick' button command in Django Project
39,616,301
<p>I am extremely new to django and web dev on the whole, so please bear with me.</p> <p>I have created a simple site with a MySQL backend for my local football team and want to create a page to update the score of a game (stored on a table) simply by clicking a button (increment the current score by + 1). I have no ...
-3
2016-09-21T12:15:31Z
39,616,893
<p>Well... First of all I do not understand why are you creating cursors and stuff. </p> <p>I`ll try to help you out here in most easy way I can imagine.</p> <p><strong>STEP 1 (if you do not have model)</strong></p> <p>Create model</p> <pre><code>class Match(models.Model): goals = models.IntegerField(default=) ...
0
2016-09-21T12:43:43Z
[ "javascript", "python", "html", "mysql", "django" ]
Open/edit utf8 fits header in python (pyfits)
39,616,304
<p>I have to deal with some fits files which contain utf8 text in their header. This means basically all functions of the pyfits package do not work. Also <strong>.decode</strong> does not work as the fits header is a class not a list. Does someone know how to decode the header so I can process the data? The actual con...
0
2016-09-21T12:15:34Z
39,616,496
<p>Looks like <code>PyFITS</code> just doesn't support it (yet?)</p> <p>From <a href="https://github.com/astropy/astropy/issues/3497" rel="nofollow">https://github.com/astropy/astropy/issues/3497</a>:</p> <blockquote> <p>FITS predates unicode and has never been updated to support anything beyond the ASCII printable...
0
2016-09-21T12:25:21Z
[ "python", "decode", "fits", "pyfits" ]
Open/edit utf8 fits header in python (pyfits)
39,616,304
<p>I have to deal with some fits files which contain utf8 text in their header. This means basically all functions of the pyfits package do not work. Also <strong>.decode</strong> does not work as the fits header is a class not a list. Does someone know how to decode the header so I can process the data? The actual con...
0
2016-09-21T12:15:34Z
39,637,762
<p>As anatoly techtonik <a href="http://stackoverflow.com/a/39616496/982257">pointed out</a> non-ASCII characters in FITS headers are outright invalid, and make invalid FITS files. That said, it would be nice if <code>astropy.io.fits</code> could at least read the invalid entries. Support for that is currently broken...
0
2016-09-22T11:28:03Z
[ "python", "decode", "fits", "pyfits" ]
Alexa lambda_handler not creating event session
39,616,470
<p>I am having a problem getting my python lambda function to work. I get an invalid key for the event array that should be created when the skill is invoked. The error I get is:</p> <pre><code>{ "stackTrace": [ [ "/var/task/lambda_function.py", 163, "lambda_handler", ...
1
2016-09-21T12:24:01Z
39,617,854
<p>The problem was I had configured the wrong test in the Lambda Function dashboard. When I changed it to an Alexa Start Session, the event object got created. :)</p>
1
2016-09-21T13:23:32Z
[ "python", "aws-lambda", "alexa", "alexa-skills-kit" ]
Alexa lambda_handler not creating event session
39,616,470
<p>I am having a problem getting my python lambda function to work. I get an invalid key for the event array that should be created when the skill is invoked. The error I get is:</p> <pre><code>{ "stackTrace": [ [ "/var/task/lambda_function.py", 163, "lambda_handler", ...
1
2016-09-21T12:24:01Z
39,797,358
<p>We just started a project <a href="https://github.com/bespoken/bstpy" rel="nofollow">bstpy</a> to expose a Python lambda as an http service. You may find it useful for testing. You can throw json payloads at it with curl or postman. If you try it with other <a href="https://github.com/bespoken/bst" rel="nofollow">Be...
0
2016-09-30T17:55:46Z
[ "python", "aws-lambda", "alexa", "alexa-skills-kit" ]
Dictionaries and unicode
39,616,578
<p>I have recently started learning Python and have got stuck in a small project I was trying. I have an array which contains data for my project, I wanted to link this by using the code.</p> <pre><code> &gt;&gt;&gt; keys = ['a', 'b', 'c'] &gt;&gt;&gt; values = [1, 2, 3] &gt;&gt;&gt; dictionary = dict(zip(k...
0
2016-09-21T12:29:04Z
39,616,916
<p>There are two major flavours of Python - Python2 and Python3, and one of the differences between them is how they treat Unicode. As a rule-of-thumb, you should be using Python3, because it is a much better language and getting better over time. Most of the bigger libraries support it.</p> <p>In Python3, this should...
0
2016-09-21T12:44:14Z
[ "python", "dictionary", "unicode" ]
Converting to/getting original list object from string representation of original list object in python
39,616,631
<p>I want to convert string representation of arbitrary list back to the original-like list object as explained in the code below:</p> <pre><code>list1 = [1,2,3,4] list1str = str(list1) str2list1 = list1str[1:-1].split(",") #stripping off square brackets from [1,2,3,4] and then splitting print(list1) #[1,2,3,4] ...
1
2016-09-21T12:31:45Z
39,616,906
<p>Easiest way, use <em>eval()</em>:</p> <pre><code>lst = "[1, 2, 3, 4, ['a', 'b'], 5, 6]" newlst = eval(lst) </code></pre> <p>so the newlst will be the exact python list you want</p> <pre><code>print (newlst) # [1, 2, 3, 4, ['a', 'b'], 5, 6] </code></pre> <p>There's one more way to do what you want with <em>exec()...
2
2016-09-21T12:43:58Z
[ "python" ]
Converting to/getting original list object from string representation of original list object in python
39,616,631
<p>I want to convert string representation of arbitrary list back to the original-like list object as explained in the code below:</p> <pre><code>list1 = [1,2,3,4] list1str = str(list1) str2list1 = list1str[1:-1].split(",") #stripping off square brackets from [1,2,3,4] and then splitting print(list1) #[1,2,3,4] ...
1
2016-09-21T12:31:45Z
39,617,082
<p>You can try:</p> <pre><code>&gt;&gt;&gt; import ast &gt;&gt;&gt; ast.literal_eval("[1,2,['a','b'],4]") [1, 2, ['a', 'b'], 4] </code></pre>
3
2016-09-21T12:50:49Z
[ "python" ]
pack and unpack at the right format in python
39,616,638
<p>I'm looking to unpack from a buffer a string and its length.</p> <blockquote> <p>For example to obtain (4, 'Gégé') from this buffer : b'\x00\x04G\xE9g\xe9'</p> </blockquote> <p>Does someone know how to do ?</p>
0
2016-09-21T12:32:15Z
39,617,185
<p>The length data looks like a big-endian unsigned 16 bit integer, and the string data looks like it's using the Latin1 encoding. If that's correct, you can extract it like this:</p> <pre><code>from struct import unpack def extract(buff): return unpack(b'&gt;H', buff[:2])[0], buff[2:].decode('latin1') buff = b'...
1
2016-09-21T12:55:20Z
[ "python", "python-3.x", "pack", "unpack" ]
pass python lists tp methods
39,616,639
<p>I want to read a file and create a list from one of its columns by split() method and pass on this list to another method. Can someone explain what is the most pythonic way to achieve that ??</p> <pre><code>def t(fname): k = [] with open(fname, 'rU') as tx: for line in tx: lin = line...
0
2016-09-21T12:32:15Z
39,616,757
<p>When you want to create a new list, lsit comprehensions ate the prefered way:</p> <pre><code>def t(fname): with open(fname, 'rU') as tx: k = [(line.split())[1] for line in tx] res = anno(k) for i in res.items(): if i &gt; 0.05: print(i) </code></pre>
0
2016-09-21T12:36:41Z
[ "python", "list", "methods" ]
pass python lists tp methods
39,616,639
<p>I want to read a file and create a list from one of its columns by split() method and pass on this list to another method. Can someone explain what is the most pythonic way to achieve that ??</p> <pre><code>def t(fname): k = [] with open(fname, 'rU') as tx: for line in tx: lin = line...
0
2016-09-21T12:32:15Z
39,616,943
<p>instead of appending to that list one by one why don't you just have a loop for that particular statement like <code>k = [(line.split())[1] for line in tx]</code>.</p> <p>And instead of using <code>with open(file) as:</code> I have used <code>tx = open(file)</code> so whenever you have it's need you can use it and ...
1
2016-09-21T12:45:11Z
[ "python", "list", "methods" ]
pass python lists tp methods
39,616,639
<p>I want to read a file and create a list from one of its columns by split() method and pass on this list to another method. Can someone explain what is the most pythonic way to achieve that ??</p> <pre><code>def t(fname): k = [] with open(fname, 'rU') as tx: for line in tx: lin = line...
0
2016-09-21T12:32:15Z
39,617,118
<p>I think you just did a mistake with the nesting. You have to call <code>anno()</code> after you've build the list, outside the for loop.</p> <pre><code>def t(fname): k = [] for line in open('fname'): k.append(line.split()[1]) res = anno(k) </code></pre>
0
2016-09-21T12:52:09Z
[ "python", "list", "methods" ]
NameError: global name 'query' is not defined
39,616,647
<p>I have a small django project and Im trying to pass a variable from my views.py into tasks.py and run a task using the variable, but I am getting name is not defined error, ive tried many solutions ive seen on other questions but i cannot seem to get it to work</p> <p>here is my views.py</p> <pre><code># -*- codin...
0
2016-09-21T12:32:27Z
39,616,731
<p>You have to change defining of your method to <code>def rti(query):</code> and use it in view <code>rti(query)</code>, because you background task don't know anything about your query variable inside.</p>
0
2016-09-21T12:35:35Z
[ "python", "django" ]
NameError: global name 'query' is not defined
39,616,647
<p>I have a small django project and Im trying to pass a variable from my views.py into tasks.py and run a task using the variable, but I am getting name is not defined error, ive tried many solutions ive seen on other questions but i cannot seem to get it to work</p> <p>here is my views.py</p> <pre><code># -*- codin...
0
2016-09-21T12:32:27Z
39,616,739
<p>You need to modify your task so that it takes the query as an argument.</p> <pre><code>@background(schedule=1) def rti(query): ... </code></pre> <p>Then pass the query when you call the task in your view</p> <pre><code>rti(query) </code></pre>
0
2016-09-21T12:35:43Z
[ "python", "django" ]
NameError: global name 'query' is not defined
39,616,647
<p>I have a small django project and Im trying to pass a variable from my views.py into tasks.py and run a task using the variable, but I am getting name is not defined error, ive tried many solutions ive seen on other questions but i cannot seem to get it to work</p> <p>here is my views.py</p> <pre><code># -*- codin...
0
2016-09-21T12:32:27Z
39,616,907
<p>You have not passed any argument to the method <code>rti()</code> that you have called inside <code>views.py</code>. And to do that, while defining the method <code>rti()</code> inside <code>tasks.py</code>, the method should take an argument like query. After that you will be able to use <code>query</code> inside <...
0
2016-09-21T12:43:59Z
[ "python", "django" ]
How can I tell SQLAlchemy to use a different identity rule for Session.merge (instead of the PK)?
39,616,663
<p>I have a legacy DB which was blindly created with auto-increment IDs even though there's a perfectly valid natural key in the table.</p> <p>This ends up with code littered with code along the lines:</p> <pre><code>Fetch row with natural key 'x' if exists: update row with NK 'x' else: insert row with NK 'x'...
0
2016-09-21T12:32:57Z
39,619,273
<p>In situations like this, i find it best to <em>lie</em> to sqlalchemy. Tell it that the natural key is primary.</p> <pre><code>class Device(Base): hostname = Column(String(256), primary_key=True) some_other_column = Column(String(20)) </code></pre>
0
2016-09-21T14:20:38Z
[ "python", "sqlalchemy" ]
What does "1B63" mean in bash?
39,616,698
<p>When I print the string value of <code>0x1b63</code> in bash, the screen clear (exactly like <code>tput reset</code> result): <a href="http://i.stack.imgur.com/vaRX1.png" rel="nofollow"><img src="http://i.stack.imgur.com/vaRX1.png" alt="enter image description here"></a></p> <p>After pressing <code>Enter</code> but...
0
2016-09-21T12:34:22Z
39,617,222
<p>It's ANSI escape sequences. There's a list of some on <a href="https://en.wikipedia.org/wiki/ANSI_escape_code" rel="nofollow">wikipedia</a></p> <p><code>\x1b</code> means <code>ESC</code> <code>\x63</code> is a lower case <code>c</code></p> <p>On that page <code>ESC</code> <code>c</code> is shown as </p> <blockqu...
2
2016-09-21T12:56:37Z
[ "python", "xterm", "ansi-escape" ]
How to configure celery-redis in django project on microsoft azure?
39,616,701
<p>I have this django locator project deployed in azure. My redis cache host name(DNS) is mycompany.azure.microsoft.net. I created it in azure, but not sure where i can find the password for the redis server. I have got this as my configuration in my settings.py. I am using redis as a broker for my celery setup in proj...
0
2016-09-21T12:34:27Z
39,762,239
<p>You can find your redis services keys in Azure portal, click <strong>Settings</strong>=><strong>Access keys</strong>, you can select either primary or secondary key as your password in the redis connection string.<br> <a href="http://i.stack.imgur.com/UKST2.png" rel="nofollow"><img src="http://i.stack.imgur.com/UKST...
1
2016-09-29T05:41:17Z
[ "python", "django", "azure", "redis", "celery" ]
BeautifulSoup: How to extract content?
39,616,753
<p>on the website that I'm trying to parse are tags like:</p> <pre><code>&lt;a class="sku" href="http://pl.farnell.com/tdk/c3225x6s0j107m250ac/capacitor-mlcc-x6s-100uf-6-3v/dp/2526286" title="2526286"&gt;2526286&lt;/a&gt; </code></pre> <p>I would like to get a list of their content (here it is 2526286 value). How can...
1
2016-09-21T12:36:24Z
39,616,768
<p>You can use:</p> <pre><code>for node in soup.find_all('a', {'class': 'sku'}): print(node.string) </code></pre> <p>As whole code:</p> <pre><code>from bs4 import BeautifulSoup string = """ &lt;div&gt; &lt;a class="sku" href="http://pl.farnell.com/tdk/c3225x6s0j107m250ac/capacitor-mlcc-x6s-100uf-6-3v/dp/252...
2
2016-09-21T12:37:17Z
[ "python", "css-selectors", "beautifulsoup", "html-parsing" ]
Pandas per group imputation of missing values
39,616,764
<h2>How can I achieve such a per-country imputation for each indicator in pandas?</h2> <p>I want to impute the missing values per group</p> <ul> <li><em>no-A-state</em> should get <code>np.min</code> per indicatorKPI </li> <li><em>no-ISO-state</em> should get the <code>np.mean</code> per indicatorKPI</li> <li><p>for ...
1
2016-09-21T12:37:11Z
39,617,769
<p>Based on your new example df the following works for me:</p> <pre><code>In [185]: mydf.loc[mydf['Country'] == 'no-A-state', 'value'] = mydf['value'].min() mydf.loc[mydf['Country'] == 'no-ISO-state', 'value'] = mydf['value'].mean() mydf.loc[mydf['value'].isnull(), 'value'] = mydf['indicatorKPI'].map(mydf.groupby('in...
1
2016-09-21T13:20:14Z
[ "python", "pandas", "group-by", "missing-data", "imputation" ]
Write from a query to table in BigQuery only if query is not empty
39,616,849
<p>In BigQuery it's possible to write to a new table the results of a query. I'd like the table to be created only whenever the query returns at least one row. Basically I don't want to end up creating empty table. I can't find an option to do that. (I am using the Python library, but I suppose the same applies to the ...
0
2016-09-21T12:41:28Z
39,616,971
<p>Since you have to specify the destination on the query definition and you don't know what it will return when you run it can you tack a <code>LIMIT 1</code> to the end?</p> <p>You can check the row number in the <a href="https://developers.google.com/resources/api-libraries/documentation/bigquery/v2/python/latest/b...
1
2016-09-21T12:46:38Z
[ "python", "google-bigquery" ]
Write from a query to table in BigQuery only if query is not empty
39,616,849
<p>In BigQuery it's possible to write to a new table the results of a query. I'd like the table to be created only whenever the query returns at least one row. Basically I don't want to end up creating empty table. I can't find an option to do that. (I am using the Python library, but I suppose the same applies to the ...
0
2016-09-21T12:41:28Z
39,632,118
<p>There's no option to do this in one step. I'd recommend running the query, inspecting the results, and then performing a table copy with WRITE_TRUNCATE to commit the results to the final location if the intermediate output contains at least one row.</p>
1
2016-09-22T06:50:36Z
[ "python", "google-bigquery" ]
Array operations using multiple indices of same array
39,616,919
<p>I am very new to Python, and I am trying to get used to performing Python's array operations rather than looping through arrays. Below is an example of the kind of looping operation I am doing, but am unable to work out a suitable pure array operation that does not rely on loops:</p> <pre><code>import numpy as np ...
1
2016-09-21T12:44:23Z
39,623,009
<p>The use of an arbitrary <code>f</code> function, and this <code>[i, :i]</code> business complicates by passing a loop.</p> <p>Most of the fast compiled <code>numpy</code> operations work on the whole array, or whole rows and/or columns, and effectively do so in parallel. Loops that are inherently sequential (value...
0
2016-09-21T17:30:49Z
[ "python", "arrays", "numpy" ]
How to create rows and columns in a .csv file from .log file
39,616,931
<p>I am trying to parse a <code>.log</code>-file from MTurk in to a <code>.csv</code>-file with rows and columns using Python. My data looks like:</p> <blockquote> <p>P:,14142,GREEN,800,9;R:,14597,7,y,NaN,Correct;P:,15605,#E5DC22,800,9;R:,16108,7,f,NaN,Correct;P:,17115,GREEN,100,9;R:,17548,7,y,NaN,Correct;P:,18552,#...
2
2016-09-21T12:44:43Z
39,617,086
<p>You can use</p> <pre><code>In [16]: df = pd.read_csv('log.txt', lineterminator=';', sep=':', header=None) </code></pre> <p>to read the file (say, <code>'log.txt'</code>) assuming that the lines are terminated by <code>';'</code>, and the separators within lines are <code>':'</code>.</p> <p>Unfortunately, your sec...
1
2016-09-21T12:51:02Z
[ "python", "csv", "pandas", "numpy" ]
How to create rows and columns in a .csv file from .log file
39,616,931
<p>I am trying to parse a <code>.log</code>-file from MTurk in to a <code>.csv</code>-file with rows and columns using Python. My data looks like:</p> <blockquote> <p>P:,14142,GREEN,800,9;R:,14597,7,y,NaN,Correct;P:,15605,#E5DC22,800,9;R:,16108,7,f,NaN,Correct;P:,17115,GREEN,100,9;R:,17548,7,y,NaN,Correct;P:,18552,#...
2
2016-09-21T12:44:43Z
39,617,237
<p>Another faster solution:</p> <pre><code>import pandas as pd import numpy as np import io temp=u"""P:,14142,GREEN,800,9;R:,14597,7,y,NaN,Correct;P:,15605,#E5DC22,800,9;R:,16108,7,f,NaN,Correct;P:,17115,GREEN,100,9;R:,17548,7,y,NaN,Correct;P:,18552,#E5DC22,100,9;R:,18972,7,f,NaN,Correct;P:,19979,GREEN,800,9;R:,20379...
0
2016-09-21T12:57:17Z
[ "python", "csv", "pandas", "numpy" ]
Else statement in Python 3 always runs
39,616,937
<p>I've been making a basic calculator with Python and I have come across this issue. After the calculations are made "Invalid Number" always prints and then the pause happens. I think it has something to do with the newline breaking the <strong>if</strong> block but I'm not sure.</p> <p>Any help will be appreciated. ...
0
2016-09-21T12:44:57Z
39,616,983
<p>No, it has got something to do with how you have written your code, consider this with <code>if...elif</code>:</p> <pre><code>ac = int(input("&gt;&gt;&gt;")) if ac == 1: print("First number :") fn = float(input("&gt;&gt;&gt;")) print("Second number :") sn = float(input("&gt;&gt;&gt;"...
2
2016-09-21T12:47:01Z
[ "python", "python-3.x", "if-statement" ]
Else statement in Python 3 always runs
39,616,937
<p>I've been making a basic calculator with Python and I have come across this issue. After the calculations are made "Invalid Number" always prints and then the pause happens. I think it has something to do with the newline breaking the <strong>if</strong> block but I'm not sure.</p> <p>Any help will be appreciated. ...
0
2016-09-21T12:44:57Z
39,616,989
<p>You shoud use <code>elif</code>:</p> <pre><code>if ac == 1: ... elif ac == 2: ... elif ac == 3: ... elif ac == 4: ... else: ... </code></pre>
2
2016-09-21T12:47:19Z
[ "python", "python-3.x", "if-statement" ]
Else statement in Python 3 always runs
39,616,937
<p>I've been making a basic calculator with Python and I have come across this issue. After the calculations are made "Invalid Number" always prints and then the pause happens. I think it has something to do with the newline breaking the <strong>if</strong> block but I'm not sure.</p> <p>Any help will be appreciated. ...
0
2016-09-21T12:44:57Z
39,617,163
<p>If I understand you correctly, you just need to replace second and further <code>if</code> with <code>elif</code>:</p> <pre><code>if ac == 1: ... elif ac == 2: ... if ac == 3: ... if ac == 4: ... else: ... </code></pre> <p>And "Invalid Number" will not be printed after each calculation.</p>
0
2016-09-21T12:54:19Z
[ "python", "python-3.x", "if-statement" ]
Django using functions from a python class from frontend?
39,616,960
<p>I am new to Django, but i managed to create the back-end and front end for my website but in the front end i am connecting to an external socket and getting data on the fly and i implemented a class that has the function <code>add_data2GraphDB(Data)</code> that adds the element to my graph database</p> <p>How can I...
1
2016-09-21T12:45:52Z
39,617,480
<p>You can start providing an api point to your Django app that will take parameters from the request body (or/and request parameters) and call your function. So create an url like <code>/api/add2grah</code>. And you call it in the front end with a classic async call.</p> <p>Now if your function takes a long time, you...
1
2016-09-21T13:08:28Z
[ "javascript", "python", "html", "django", "neo4j" ]
Django using functions from a python class from frontend?
39,616,960
<p>I am new to Django, but i managed to create the back-end and front end for my website but in the front end i am connecting to an external socket and getting data on the fly and i implemented a class that has the function <code>add_data2GraphDB(Data)</code> that adds the element to my graph database</p> <p>How can I...
1
2016-09-21T12:45:52Z
39,628,690
<p>I solved the issue by using ajax and also @Ehvince helped me with the concept of the api basically in the front-end i used:</p> <pre><code>$.ajax({ type:'POST', url:'/app/add2Graph/', data:{ tx:data.txid, csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val() }, success:...
0
2016-09-22T01:02:02Z
[ "javascript", "python", "html", "django", "neo4j" ]
Adding custom user registration fields in django
39,617,102
<p>I couldn't find much information/am having trouble adding custom user fields to the django create_user function. I have quite a few fields and am not sure how to get them into the database, as currently this function only allows username, password, first name and last name. My views/form/models are:</p> <p>views:</...
0
2016-09-21T12:51:31Z
39,617,301
<p>If you want to extend your User you cannot create model with username as char field. Just follow this <a href="https://docs.djangoproject.com/en/dev/topics/auth/customizing/#extending-the-existing-user-model" rel="nofollow">Django Docs</a>. </p>
1
2016-09-21T13:00:40Z
[ "python", "django", "forms", "user", "registration" ]
Convert string to list without elements being individual characters?
39,617,157
<p>Suppose I have a function called <code>support</code> that counts the number of times passed items occur in elements in a list:</p> <pre><code>&gt;&gt;&gt; rows = ['candy apple banana cookie', 'candy apple banana', 'candy', 'apple', 'apple banana candy', 'candy apple', 'banana'] &gt;&gt;&gt; def support(item, rows...
0
2016-09-21T12:53:54Z
39,617,426
<p>You've actually already figured out how to convert a <code>str</code> to a <code>list</code> without the elements being individual characters: <code>row.split()</code>. Your problem is that this leaves you with bunch of a small lists (like <code>['candy', 'apple', 'banana', 'cookie']</code>) rather than flattening a...
1
2016-09-21T13:06:02Z
[ "python", "string" ]
Convert string to list without elements being individual characters?
39,617,157
<p>Suppose I have a function called <code>support</code> that counts the number of times passed items occur in elements in a list:</p> <pre><code>&gt;&gt;&gt; rows = ['candy apple banana cookie', 'candy apple banana', 'candy', 'apple', 'apple banana candy', 'candy apple', 'banana'] &gt;&gt;&gt; def support(item, rows...
0
2016-09-21T12:53:54Z
39,617,634
<p>If I understand you right you are searching for something like this</p> <pre><code>def joint_support(items, rows): return sum([1 for row in rows if set(items).issubset(set(row.split()))]) </code></pre> <p>The second <code>set</code> is optional</p> <pre><code>rows = ['candy apple banana cookie', 'candy apple ...
1
2016-09-21T13:15:00Z
[ "python", "string" ]
Convert string to list without elements being individual characters?
39,617,157
<p>Suppose I have a function called <code>support</code> that counts the number of times passed items occur in elements in a list:</p> <pre><code>&gt;&gt;&gt; rows = ['candy apple banana cookie', 'candy apple banana', 'candy', 'apple', 'apple banana candy', 'candy apple', 'banana'] &gt;&gt;&gt; def support(item, rows...
0
2016-09-21T12:53:54Z
39,617,688
<p>When passing a list of items, add a leading <em>asterisk</em> to the parameter, so the list is treated as a container of separate items:</p> <pre><code>def joint_support(rows, *items): if len(items) == 1: return float(sum(items[0] in row for row in rows)) elif len(items) &gt; 1: return float...
1
2016-09-21T13:17:14Z
[ "python", "string" ]
Convert string to list without elements being individual characters?
39,617,157
<p>Suppose I have a function called <code>support</code> that counts the number of times passed items occur in elements in a list:</p> <pre><code>&gt;&gt;&gt; rows = ['candy apple banana cookie', 'candy apple banana', 'candy', 'apple', 'apple banana candy', 'candy apple', 'banana'] &gt;&gt;&gt; def support(item, rows...
0
2016-09-21T12:53:54Z
39,618,705
<p>If you are looking for only checking whether all the items exist in the list, you can use <code>set</code> and subtract it.</p> <pre><code>def joint_support(item, rows): if isinstance(item, str): item = (item,) return float(sum[1 for row in rows if not set(item)-set(row.split(" "))]) </code></pre>
0
2016-09-21T13:57:46Z
[ "python", "string" ]
Reverse the list while creation
39,617,160
<p>I have this code:</p> <pre><code>def iterate_through_list_1(arr): lala = None for i in range(len(arr))[::-1]: lala = i def iterate_through_list_2(arr): lala = None for i in range(len(arr), 0, -1): lala = i </code></pre> <p>Logically, iterating through list created by <code>range()<...
-2
2016-09-21T12:54:01Z
39,617,655
<p>Well designed test shows that first function is slowest on Python 2.x (mostly because two lists have to be created, first one as a increasing range, second one as a reverted first one). I also included a demo using <code>reversed</code>.</p> <pre><code>from __future__ import print_function import sys import timeit ...
1
2016-09-21T13:15:51Z
[ "python", "performance", "list", "memory" ]
Nesting mpi calls with mpi4py
39,617,250
<p>I am trying to use mpi4py to call a second instance of an mpi executable.</p> <p>I am getting the error:</p> <pre><code>Open MPI does not support recursive calls of mpirun </code></pre> <p>But I was under the impression that is exactly what Spawn is supposed to be able to handle - i.e. setting up a new communicat...
0
2016-09-21T12:58:10Z
39,637,553
<p>The following code seems to perform the way I wanted.</p> <pre><code>#!/usr/bin/env python from mpi4py import MPI import numpy import sys import os rank = MPI.COMM_WORLD.Get_rank() new_comm = MPI.COMM_WORLD.Split(color=rank, key=rank) print(new_comm.Get_rank()) cwd=os.getcwd() os.mkdir(str(rank)) directory=os.pat...
1
2016-09-22T11:17:36Z
[ "python", "parallel-processing", "mpi", "python-3.4", "mpi4py" ]
Make a table from 2 columns
39,617,298
<p>I'm fairly new on Python.</p> <p>I have 2 columns on a dataframe, columns are something like: </p> <pre><code>db = pd.read_excel(path_to_file/file.xlsx) db = db.loc[:,['col1','col2']] col1 col2 C 4 C 5 A 1 B 6 B 1 A 2 C 4 </code></pre> <p>I need them to be like this:</p> <pre><code>...
2
2016-09-21T13:00:25Z
39,617,447
<p>I think you need aggreagate by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.size.html" rel="nofollow"><code>size</code></a> and add missing values to columns by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.reindex.html" rel="nofollow"><code...
1
2016-09-21T13:07:01Z
[ "python", "pandas", "group-by", "aggregate", "multiple-columns" ]
Make a table from 2 columns
39,617,298
<p>I'm fairly new on Python.</p> <p>I have 2 columns on a dataframe, columns are something like: </p> <pre><code>db = pd.read_excel(path_to_file/file.xlsx) db = db.loc[:,['col1','col2']] col1 col2 C 4 C 5 A 1 B 6 B 1 A 2 C 4 </code></pre> <p>I need them to be like this:</p> <pre><code>...
2
2016-09-21T13:00:25Z
39,617,474
<p>Say your columns are called <code>cat</code> and <code>val</code>:</p> <pre><code>In [26]: df = pd.DataFrame({'cat': ['C', 'C', 'A', 'B', 'B', 'A', 'C'], 'val': [4, 5, 1, 6, 1, 2, 4]}) In [27]: df Out[27]: cat val 0 C 4 1 C 5 2 A 1 3 B 6 4 B 1 5 A 2 6 C 4 </code></pre> <p>Th...
2
2016-09-21T13:08:12Z
[ "python", "pandas", "group-by", "aggregate", "multiple-columns" ]
Python: variables shared betwen modules and namespaces
39,617,347
<p>After reading at <a href="http://stackoverflow.com/questions/15959534/python-visibility-of-global-variables-in-imported-modules">Python - Visibility of global variables in imported modules</a></p> <p>I was curious about this example:</p> <pre><code>import shared_stuff import module1 shared_stuff.a = 3 module1.f(...
0
2016-09-21T13:02:29Z
39,617,448
<p>Importing <code>*</code> copies all the references from the module into the current scope; there is no connection to the original module at all.</p>
1
2016-09-21T13:07:02Z
[ "python", "module", "global-variables" ]
Do AND, OR strings have special meaning in PLY?
39,617,450
<p>When using PLY (<a href="http://www.dabeaz.com/ply/" rel="nofollow">http://www.dabeaz.com/ply/</a>) I've noticed what seems to be a very strange problem: when I'm using tokens like <code>&amp;</code> for conjunction, the program below works, but when I use <code>AND</code> in the same place, PLY claims syntax error....
0
2016-09-21T13:07:09Z
39,628,385
<p>Ply has a slightly eccentric approach to ordering token regular expressions, in part because it depends on the underlying python regular expression library. Tokens defined with functions, such as your <code>number</code> token, are recognuzed in the order they appear, and unlike many lexical scanner generators, Ply ...
0
2016-09-22T00:20:12Z
[ "python", "parsing", "ply" ]
Listing all directories recursively within the zipfile without extracting in python
39,617,494
<p>In Python we can get the list of all files within a zipfile without extracting the zip file using the below code.</p> <pre><code>import zipfile zip_ref = zipfile.ZipFile(zipfilepath, 'r') for file in zip_ref.namelist(): print file </code></pre> <p>Similarly is there a way to fetch the list of all direc...
1
2016-09-21T13:09:20Z
39,618,800
<pre><code>import zipfile with zipfile.ZipFile(zipfilepath, 'r') as myzip: print(myzip.printdir()) </code></pre>
1
2016-09-21T14:01:48Z
[ "python", "file", "directory", "zipfile", "filestructure" ]
Listing all directories recursively within the zipfile without extracting in python
39,617,494
<p>In Python we can get the list of all files within a zipfile without extracting the zip file using the below code.</p> <pre><code>import zipfile zip_ref = zipfile.ZipFile(zipfilepath, 'r') for file in zip_ref.namelist(): print file </code></pre> <p>Similarly is there a way to fetch the list of all direc...
1
2016-09-21T13:09:20Z
39,632,125
<p>Thanks everyone for your help.</p> <pre><code>import zipfile subdirs_list = [] zip_ref = zipfile.ZipFile('C:/Download/sample.zip', 'r') for dir in zip_ref.namelist(): if dir.endswith('/'): subdirs_list.append(os.path.basename(os.path.normpath(dir))) print subdirs_list </code></pre> <p>With the above ...
0
2016-09-22T06:51:01Z
[ "python", "file", "directory", "zipfile", "filestructure" ]
Unable to access docker SimpleHTTPServer container
39,617,497
<p>This question has been asked before, but I have not found a solution to my issue. I have some static files that I want to serve using Python's <code>SimpleHTTPServer</code> module. I have successfully built the image and run it, but I am unable to access the files from the browser. Here is my DockerFile:</p> <pre>...
0
2016-09-21T13:09:25Z
39,617,880
<p>The <code>-p</code> option publishes the container's ports to the host. You may need to use <a href="http://localhost:8080/Test.html" rel="nofollow">http://localhost:8080/Test.html</a> if you run the container with <code>-p 8080:8080</code> specified.</p>
1
2016-09-21T13:24:22Z
[ "python", "windows", "docker", "simplehttpserver" ]
Tensorflow Data Input Toggle: Train/Validation
39,617,686
<p>I have data that comes into my graph through queue runners, after I switched from the handy but speed-inferior placeholders.</p> <p>After each training epoch, I wish to run a validation pass. Other than the the training pass, the validation pass uses different data, no augmentation and no shuffling.</p> <p>The que...
0
2016-09-21T13:17:10Z
39,620,485
<p>The method that works well for me is to use <code>tf.placeholder_with_default</code>:</p> <blockquote> <pre><code>images_train, labels_train = train_data_pipeline(fnlist_train, ref_grid) images_val, labels_val = val_data_pipeline(fnlist_val, ref_grid) images = tf.placeholder_with_default(images_train, shape=[None, ...
1
2016-09-21T15:16:36Z
[ "python", "tensorflow" ]
Tensorflow Data Input Toggle: Train/Validation
39,617,686
<p>I have data that comes into my graph through queue runners, after I switched from the handy but speed-inferior placeholders.</p> <p>After each training epoch, I wish to run a validation pass. Other than the the training pass, the validation pass uses different data, no augmentation and no shuffling.</p> <p>The que...
0
2016-09-21T13:17:10Z
39,622,064
<p>One probable answer is usage of <code>make_template</code> This is outlined in <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/kernel_tests/template_test.py" rel="nofollow">https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/kernel_tests/template_test.py</a> ; It ba...
0
2016-09-21T16:38:09Z
[ "python", "tensorflow" ]
Semantic error during if-statement check in program
39,617,727
<p>So I have a form that requires the user to put in all info. Only by entering all the info does the information get saved. However a weird little bug has come about.After submitting with no checkbox selected and then switching to yes afterwards (Yes this is intended) as long as a radio-button is selected, data is sav...
0
2016-09-21T13:18:33Z
39,619,041
<p>You do not need to test <code>option</code> more than once.<br> Use <code>if first.get():</code> instead of <code>if first.get() != ""</code>.<br> You are testing <code>yes</code> in the second <code>if</code> statement, so remove it from the first one (needed to show different messagebox).</p> <pre><code># Check r...
0
2016-09-21T14:11:12Z
[ "python", "if-statement", "tkinter" ]
Django Rest Framework return True if relation exist
39,617,817
<p>I have two questions. How i can just return true if relation exist? For example I have post model and comment model also, comment have foreginKey to post. Now after post serialization i wanna have something like this </p> <pre><code>{ id: 2 content: "My first post!" has-comments: True } </code></pre> <p>And my sec...
0
2016-09-21T13:22:15Z
39,618,197
<p>The closest thing I can come up with is a custom <code>has_comments</code> field (rather than <code>has-comments</code>) with this in the serializer:</p> <pre><code>from rest_framework import serializers class YourSerializer(Either Serializer or ModelSerializer...): has_comments = serializers.SerializerMethodF...
1
2016-09-21T13:37:55Z
[ "python", "django", "django-rest-framework" ]
Python - No valuerror on int with isalpha
39,617,822
<p>Why is no ValueError raised on this try / except when isalpha should fail.</p> <p>I know that isalpha returns false if given a number</p> <pre><code>In [9]: ans = input("Enter a Letter") Enter a Letter4 In [10]: ans.isalpha() Out[10]: False </code></pre> <p>How do I get the value error if they supply a number in...
-1
2016-09-21T13:22:20Z
39,617,925
<p>You need to raise the error yourself. There is no exception raised by typing in something that you don't prefer:</p> <pre><code>try: answer = input("\t &gt;&gt; ").isalpha() if not answer: raise ValueError print(v0 * t - 0.5 * g * t ** 2) except ValueError as err: print("Not a valid entry",...
1
2016-09-21T13:26:11Z
[ "python", "python-3.x" ]
Python - No valuerror on int with isalpha
39,617,822
<p>Why is no ValueError raised on this try / except when isalpha should fail.</p> <p>I know that isalpha returns false if given a number</p> <pre><code>In [9]: ans = input("Enter a Letter") Enter a Letter4 In [10]: ans.isalpha() Out[10]: False </code></pre> <p>How do I get the value error if they supply a number in...
-1
2016-09-21T13:22:20Z
39,617,941
<p><code>except ValueError as err:</code> only happens when there is a ValueError thrown. The value of <code>answer</code> is <code>False</code>, but that is just an arbitrary boolean value, not an error.</p> <p>See <a href="https://docs.python.org/2/library/exceptions.html#exceptions.ValueError" rel="nofollow"><code>...
3
2016-09-21T13:27:11Z
[ "python", "python-3.x" ]
Python - No valuerror on int with isalpha
39,617,822
<p>Why is no ValueError raised on this try / except when isalpha should fail.</p> <p>I know that isalpha returns false if given a number</p> <pre><code>In [9]: ans = input("Enter a Letter") Enter a Letter4 In [10]: ans.isalpha() Out[10]: False </code></pre> <p>How do I get the value error if they supply a number in...
-1
2016-09-21T13:22:20Z
39,617,978
<p>In general you should prefer to use normal control flow logic to handle a range of user input rather than raising/catching exceptions.</p>
2
2016-09-21T13:28:35Z
[ "python", "python-3.x" ]
Python - No valuerror on int with isalpha
39,617,822
<p>Why is no ValueError raised on this try / except when isalpha should fail.</p> <p>I know that isalpha returns false if given a number</p> <pre><code>In [9]: ans = input("Enter a Letter") Enter a Letter4 In [10]: ans.isalpha() Out[10]: False </code></pre> <p>How do I get the value error if they supply a number in...
-1
2016-09-21T13:22:20Z
39,630,518
<p>Posting an answer for clarity trying to provide a way to be more consistent and explicit with the treatment of <em>strings</em> and <em>int's</em>. By using <em>isinstance</em> I declare to a person reading my code explicitly what my values are to be hopefully improving readability.</p> <pre><code>answer = input("\...
0
2016-09-22T04:52:30Z
[ "python", "python-3.x" ]
Python Slice a List Using a List of Multiple Tuples
39,617,956
<p>I have a list of numbers that I would like to slice the range of numbers that is given from a list of multiple tuples. For example, I have a list that looks like:</p> <pre><code>my_list = [ 5, 8, 3, 0, 0, 1, 3, 4, 8, 13, 0, 0, 0, 0, 21, 34, 25, 91, 61, 0, 0,] </code></pre> <p>I also have a list of tuples that are...
1
2016-09-21T13:27:48Z
39,618,075
<p>a possibility</p> <pre><code>from itertools import chain my_iter = chain(*[my_list[start:end] for start, end in my_tups]) [l for l in my_iter] </code></pre> <p>gives </p> <pre><code>[1, 3, 4, 8, 21, 34, 25, 91] </code></pre>
0
2016-09-21T13:32:49Z
[ "python", "list", "tuples", "slice" ]
Python Slice a List Using a List of Multiple Tuples
39,617,956
<p>I have a list of numbers that I would like to slice the range of numbers that is given from a list of multiple tuples. For example, I have a list that looks like:</p> <pre><code>my_list = [ 5, 8, 3, 0, 0, 1, 3, 4, 8, 13, 0, 0, 0, 0, 21, 34, 25, 91, 61, 0, 0,] </code></pre> <p>I also have a list of tuples that are...
1
2016-09-21T13:27:48Z
39,618,085
<p>If I understand the question correctly, you want to return the values from <code>my_list</code> in the ranges <code>5:9</code> and <code>14:18</code>. The following code should do it</p> <pre><code>my_list = [ 5, 8, 3, 0, 0, 1, 3, 4, 8, 13, 0, 0, 0, 0, 21, 34, 25, 91, 61, 0, 0] my_tups = [(5,9), (14,18)] def flatt...
0
2016-09-21T13:33:03Z
[ "python", "list", "tuples", "slice" ]