title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
how to read json file with pandas?
39,040,250
<p>I have scraped a website with scrapy and stored the data in a json file.<br> Link to the json file: <a href="https://drive.google.com/file/d/0B6JCr_BzSFMHLURsTGdORmlPX0E/view?usp=sharing" rel="nofollow">https://drive.google.com/file/d/0B6JCr_BzSFMHLURsTGdORmlPX0E/view?usp=sharing</a></p> <p>But the json isn't stand...
2
2016-08-19T13:25:16Z
39,040,324
<p>Try following codes: (you are missing one something)</p> <pre><code>&gt;&gt;&gt; import json &gt;&gt;&gt; with open("/root/code/itjuzi/itjuzi/investorinfo.json") as file: ... data = json.load(file.read()) </code></pre>
1
2016-08-19T13:28:36Z
[ "python", "json", "list", "pandas", "scrapy" ]
how to read json file with pandas?
39,040,250
<p>I have scraped a website with scrapy and stored the data in a json file.<br> Link to the json file: <a href="https://drive.google.com/file/d/0B6JCr_BzSFMHLURsTGdORmlPX0E/view?usp=sharing" rel="nofollow">https://drive.google.com/file/d/0B6JCr_BzSFMHLURsTGdORmlPX0E/view?usp=sharing</a></p> <p>But the json isn't stand...
2
2016-08-19T13:25:16Z
39,040,375
<p>try this <a class='doc-link' href="http://stackoverflow.com/documentation/pandas/4752/json/16714/read-json#t=201608191329212576968">from SO documentation[JSON] </a>:</p> <pre><code>import json with open('data.json') as data_file: data = json.load(data_file) </code></pre> <p>This has the advantage of dealing we...
4
2016-08-19T13:31:27Z
[ "python", "json", "list", "pandas", "scrapy" ]
Python: Division by larger numbers slower?
39,040,340
<p>Why does dividing by the larger factor pair result in slower execution?</p> <p>My solution for <a href="https://codility.com/programmers/task/min_perimeter_rectangle/" rel="nofollow">https://codility.com/programmers/task/min_perimeter_rectangle/</a></p> <pre class="lang-py prettyprint-override"><code>from math imp...
0
2016-08-19T13:29:38Z
39,040,447
<p>That's obvious. The first function loops <em>many</em> more times.</p> <p>Note that <code>sqrt(n) != n - sqrt(n)</code>! in general <code>sqrt(n) &lt;&lt; n-sqrt(n)</code> where <code>&lt;&lt;</code> means <em>much</em> lesser than.</p> <p>If <code>n=1000</code> the first function is looping <code>969</code> times...
1
2016-08-19T13:35:23Z
[ "python", "performance" ]
Python: Division by larger numbers slower?
39,040,340
<p>Why does dividing by the larger factor pair result in slower execution?</p> <p>My solution for <a href="https://codility.com/programmers/task/min_perimeter_rectangle/" rel="nofollow">https://codility.com/programmers/task/min_perimeter_rectangle/</a></p> <pre class="lang-py prettyprint-override"><code>from math imp...
0
2016-08-19T13:29:38Z
39,040,480
<p>It's not division that slows it down; it's the number of iterations required.</p> <p>Let <code>L = xrange(0, x)</code> (order doesn't matter here) and <code>R = xrange(x, n+1)</code>. Every factor of <code>n</code> in <code>L</code> can be paired with exactly one factor of <code>n</code> in <code>R</code>. In gener...
3
2016-08-19T13:37:01Z
[ "python", "performance" ]
Python: Division by larger numbers slower?
39,040,340
<p>Why does dividing by the larger factor pair result in slower execution?</p> <p>My solution for <a href="https://codility.com/programmers/task/min_perimeter_rectangle/" rel="nofollow">https://codility.com/programmers/task/min_perimeter_rectangle/</a></p> <pre class="lang-py prettyprint-override"><code>from math imp...
0
2016-08-19T13:29:38Z
39,040,595
<p>I'd say the of iterations is the key which makes perfomance a little bit different between your functions as @Bakuriu already said. Also, xrange could be slightly more expensive than using a simple loop, for instance, take a look f3 will perform a little better than f1 &amp; f2:</p> <pre><code>import timeit from ma...
0
2016-08-19T13:43:44Z
[ "python", "performance" ]
Looking backward and forward in a circular loop in python
39,040,359
<p>I would like to generate a list of single digits based on user input. In a circular iterative way, the list should contain the user input, the two digits before that, and the two digits after that. The order of the digits isn't important. </p> <p>user_input = "1" output = [9, 0, 1, 2, 3]</p> <p>user_input = "9" ou...
1
2016-08-19T13:30:56Z
39,040,496
<p>You can implement like this.</p> <pre><code>def backward_list(n): numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] if n == 0 or n == 1: x = numbers.index(n) else: x = (numbers.index(n)-10) return [numbers[x-2],numbers[x-1],numbers[x],numbers[x+1],numbers[x+2]] </code></pre> <p><strong>Exec...
2
2016-08-19T13:38:26Z
[ "python", "list", "iteration" ]
Looking backward and forward in a circular loop in python
39,040,359
<p>I would like to generate a list of single digits based on user input. In a circular iterative way, the list should contain the user input, the two digits before that, and the two digits after that. The order of the digits isn't important. </p> <p>user_input = "1" output = [9, 0, 1, 2, 3]</p> <p>user_input = "9" ou...
1
2016-08-19T13:30:56Z
39,040,563
<p>Modify your statements in the iff to this:</p> <pre><code>if s in itr and len(str) == 2: lst.append(next(itr)) #getting the next digit lst = [s - 1] + lst # prepend the first value lst.append(next(itr)) lst = [s - 2] + lst # prepend the second value </code></pre> <p>Or you can also do</p> <pre><...
0
2016-08-19T13:41:57Z
[ "python", "list", "iteration" ]
Looking backward and forward in a circular loop in python
39,040,359
<p>I would like to generate a list of single digits based on user input. In a circular iterative way, the list should contain the user input, the two digits before that, and the two digits after that. The order of the digits isn't important. </p> <p>user_input = "1" output = [9, 0, 1, 2, 3]</p> <p>user_input = "9" ou...
1
2016-08-19T13:30:56Z
39,040,589
<p>You could take a range from the input and use that range to slice a numpy array</p> <p>edit: my bad for writing code and not testing it... thanks @Stefan Pochmann for pointing that out...</p> <pre><code>import numpy as np def cycle(x): #x is user input indices = np.array(range(x-2, x+3))%10 numbers = np....
0
2016-08-19T13:43:24Z
[ "python", "list", "iteration" ]
Looking backward and forward in a circular loop in python
39,040,359
<p>I would like to generate a list of single digits based on user input. In a circular iterative way, the list should contain the user input, the two digits before that, and the two digits after that. The order of the digits isn't important. </p> <p>user_input = "1" output = [9, 0, 1, 2, 3]</p> <p>user_input = "9" ou...
1
2016-08-19T13:30:56Z
39,040,871
<p>Could use a list comprehension and <code>% 10</code>:</p> <pre><code>&gt;&gt;&gt; for s in range(10): print([i % 10 for i in range(s-2, s+3)]) [8, 9, 0, 1, 2] [9, 0, 1, 2, 3] [0, 1, 2, 3, 4] [1, 2, 3, 4, 5] [2, 3, 4, 5, 6] [3, 4, 5, 6, 7] [4, 5, 6, 7, 8] [5, 6, 7, 8, 9] [6, 7, 8, 9, 0] [7, 8, 9, 0, 1] </co...
1
2016-08-19T13:55:47Z
[ "python", "list", "iteration" ]
Select/slice a multi-index dataframe time-series using a period leads to a bug?
39,040,445
<p>I have a multi index which first level index is a time series in the very same way as the following one:</p> <pre><code>In[168]: rng = pd.date_range('01-01-2000',periods=50,freq='M') In[169]: long_df = pd.DataFrame(np.random.randn(50,4),index = rng, columns=['bar','baz','foo','zoo']) In[170]: long_df = long_df.st...
2
2016-08-19T13:35:16Z
39,040,543
<p>You need add <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.loc.html" rel="nofollow"><code>loc</code></a>, but need last version of <a href="http://pandas.pydata.org/pandas-docs/stable/whatsnew.html#partial-string-indexing-on-datetimeindex-when-part-of-a-multiindex" rel="nofollow">pa...
3
2016-08-19T13:41:01Z
[ "python", "pandas", "time-series", "slice", "multi-index" ]
How to replace letters with a corresponding number
39,040,466
<p>My question is: if I have a string like “lake" and I wanted it to be replaced with a set of numbers like "1,2,3,4", how will I be able to do it? To be more clear I want each letter to have a corresponding number. Hope I'm clear. Thanks in advance.</p>
-4
2016-08-19T13:36:28Z
39,040,778
<p>Your question is a little bit generic, but let me show you a little example where you transform your input into "something" and you can recover your source string from that "something":</p> <pre><code>alphabet = "abcdefghijklmnopqrstuvwxyz0123456789 .,?!" def crypt(c, key): return ord(c)-key def decrypt(c, k...
0
2016-08-19T13:51:32Z
[ "python", "python-2.7" ]
Pandas set_Value with DatetimeIndex [Python]
39,040,544
<p>I'm trying to add the row-wise result from a function into my dataframe using <code>df.set_Value</code>.</p> <p><code>df</code> in the format :</p> <pre><code> Count DTW DateTime 2015-01-16 10 0 2015-01-17 28 0 </code></pre> <p>Using <code>df.setValue</code></p> <pre><code>dw.set_Value(idx, 'co...
3
2016-08-19T13:41:04Z
39,040,781
<p>I think you have <code>Series</code>, not <code>DataFrame</code>, so use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.set_value.html" rel="nofollow"><code>Series.set_value</code></a> with index converted to <code>datetime</code></p> <pre><code>dw = pd.Series([-2374], index = [pd.to_d...
3
2016-08-19T13:51:36Z
[ "python", "pandas", "dataframe" ]
How to check user input with csv file and print data from specific column?
39,040,662
<p>I have a CSV file, which contains patch names, their release date and some other info in separate columns. I am trying to write a Python script that will ask the user for a Patch name and once it gets the input, will check if the Patch is in the CSV file and print out the Release Date.</p> <p>So far, I have written...
0
2016-08-19T13:46:40Z
39,040,917
<p>You're almost there, though I'm a <em>wee</em> bit confused - your sample data doesn't have a header row. If it doesn't then you shouldn't be using a <code>DictReader</code> but if it does you can take this approach.</p> <pre><code>version = patch[:8] latest_patch = '' last_patch_data = None with open("CSV_File1.cs...
0
2016-08-19T13:58:14Z
[ "python", "csv", "input", "output" ]
How to check user input with csv file and print data from specific column?
39,040,662
<p>I have a CSV file, which contains patch names, their release date and some other info in separate columns. I am trying to write a Python script that will ask the user for a Patch name and once it gets the input, will check if the Patch is in the CSV file and print out the Release Date.</p> <p>So far, I have written...
0
2016-08-19T13:46:40Z
39,045,540
<p>The CSV module works fine but I just wanted to throw Pandas in as this can be a good use case for it. There may be better ways to handle this but it's a fun example. This is assuming that your columns are labels(Patch_Name, Release_Date) so you will need to correct them.</p> <pre><code>import pandas as pd my_file1...
0
2016-08-19T18:23:45Z
[ "python", "csv", "input", "output" ]
Can python compare user input with variables in program?
39,040,699
<p>This is my first post here, hope it is easily readable and also my answer is asked! (:</p> <p>First of all, to put you a bit into perspective, I wanted to create an efficiency calculator for the brand new game No Man's Sky. The economy in that game is pretty much the same as in real life. You can sell items at a mu...
1
2016-08-19T13:48:22Z
39,041,414
<p>How you save the data and access it will really depend on how you want to handle your calculator. I would say the best way to handle this would be if there were an excel file or JSON file or something of the sort that is all inclusive of all materials and items of the game (you may have to be the one to make this o...
1
2016-08-19T14:22:44Z
[ "python", "calculator" ]
Can python compare user input with variables in program?
39,040,699
<p>This is my first post here, hope it is easily readable and also my answer is asked! (:</p> <p>First of all, to put you a bit into perspective, I wanted to create an efficiency calculator for the brand new game No Man's Sky. The economy in that game is pretty much the same as in real life. You can sell items at a mu...
1
2016-08-19T13:48:22Z
39,041,640
<p>About your first question, another way would be to use <strong>json</strong> format to store your data and not to use three separate dictionaries, I mean something like:</p> <pre><code>data = {"elements":{"Th":20.6,"Pu":41.3},"alloys":{"Aronium":1546.9,"Herox":2877.5},"Products":{"Antimatter":5232,"Warp Cell":46750...
0
2016-08-19T14:32:11Z
[ "python", "calculator" ]
pyQt and QTextEdit: Why are some unicode characters are shown, others not?
39,040,732
<p>I try to display unicode text in a QTextEdit in pyQt. </p> <p>It's Python 2.7 and PyQt4 on Mac OSX El Capitan.</p> <p>I read through some Q&amp;A about python, QString and unicode and came up with the following running example. </p> <p>When run, it prints two unicode strings to the terminal and also shows them in...
0
2016-08-19T13:49:33Z
39,045,000
<p>What is the output of <code>sys.maxunicode</code> for the python youy are using? If it's 65535 (rather than 1114111), you are using a <em>narrow</em> build of python, which does not support characters outside the <a href="http://en.wikipedia.org/wiki/Plane_(Unicode)#Basic_Multilingual_Plane" rel="nofollow">BMP</a>.<...
1
2016-08-19T17:46:57Z
[ "python", "unicode", "pyqt", "emoji", "qtextedit" ]
JSON ValueError in CMS, tornado
39,040,796
<p>I'm tring to run Contest Management System (<a href="http://cms.readthedocs.io/en/v1.2/index.html" rel="nofollow">docs</a>) in Ubuntu 16.04. CMS runs quite OK, but sometimes it returns error, like this in short:</p> <pre><code>ValueError: No JSON object could be decoded </code></pre> <p>I'm afraid if make everythi...
0
2016-08-19T13:52:24Z
39,192,636
<p>Sorry, it was my mistake. For who has same errors, (predictably nobody) I filled my task scoring form improperly, so JSON couldn't decode them. closing!</p>
0
2016-08-28T15:05:22Z
[ "python", "json", "content-management-system" ]
TypeError: 'str' object is not callable di python 2.7
39,040,923
<pre><code>while True: op_list = [] for op in client.longPoll(): op_list.append(op) for op in op_list: sender = op[0] receiver = op[1] message = op[2] msg = message.text if msg("help"): receiver.sendMessage('why?') if msg("help"): </code></pre> <p>TypeError: 'str' object is not callable ,anyone ...
-3
2016-08-19T13:58:19Z
39,041,206
<p>Problem lies on line 12. msg is a text, obvious that it cannot be a callable. You should quite certainly do an equal to if you want to compare two strings.</p> <pre><code>if msg == "help": receiver.sendMessage('why?') </code></pre>
0
2016-08-19T14:12:24Z
[ "python", "string" ]
Fast counts of elements of numpy array by value thresholds in another array
39,040,924
<p>Given a <code>numpy</code> array of threshold values, what is the most efficient way to produce an array of the counts of another array meeting these values? </p> <p>Assume the threshold value array is small and sorted, and the array of values to be counted is large-ish and unsorted.</p> <p><strong>Example:</stro...
3
2016-08-19T13:58:23Z
39,041,130
<p><strong>Approach #1</strong> Using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.searchsorted.html" rel="nofollow"><code>np.searchsorted</code></a> -</p> <pre><code>values.size - np.searchsorted(values,valueLevels,sorter=values.argsort()) </code></pre> <p><strong>Approach #2</strong> Using <a ...
2
2016-08-19T14:07:50Z
[ "python", "numpy", "cumulative-frequency" ]
Fast counts of elements of numpy array by value thresholds in another array
39,040,924
<p>Given a <code>numpy</code> array of threshold values, what is the most efficient way to produce an array of the counts of another array meeting these values? </p> <p>Assume the threshold value array is small and sorted, and the array of values to be counted is large-ish and unsorted.</p> <p><strong>Example:</stro...
3
2016-08-19T13:58:23Z
39,041,202
<p>The fastest I have so far is</p> <pre><code>%timeit count_nonzero(values &gt;= atleast_2d(valueLevels).T, axis=1) # 1000 loops, best of 3: 860 µs per loop </code></pre> <p><code>sum</code> is slower:</p> <pre><code>%timeit sum(values &gt;= atleast_2d(valueLevels).T, axis=1) # 100 loops, best of 3: 2.5 ms per loo...
4
2016-08-19T14:12:04Z
[ "python", "numpy", "cumulative-frequency" ]
remove special escape python
39,040,979
<p>I have the string</p> <pre><code>a = 'ddd\ttt\nnn' </code></pre> <p>I want to remove the '\' from the string. and It will be </p> <pre><code>a = 'dddtttnnn' </code></pre> <p>how to do that in python since '\t' and '\n' has special meaning in python</p>
1
2016-08-19T14:01:32Z
39,041,476
<p>Assuming you want to remove <code>\t</code> and <code>\n</code> type characters (with those representing <code>tab</code> and <code>newline</code> in this case and remove the meaning of <code>\</code> in the string in general) you can do:</p> <pre><code>&gt;&gt;&gt; a = 'ddd\ttt\nnn' &gt;&gt;&gt; print a ddd tt nn ...
2
2016-08-19T14:25:04Z
[ "python", "string", "escaping" ]
Slack API: Do Something when button is clicked
39,040,993
<p>I am using Python and it's <code>Slacker</code> API to post messages to a slack channel and it's posting the messages nicely.</p> <p>Now what I want to do is create a button that says, <em>More Info</em> and when it's clicked, I want to show a list of items. But when the button is clicked, <code>slackbot</code> say...
1
2016-08-19T14:02:16Z
39,392,802
<p>Do you have a button endpoint setup already? If not, you will see that error message. </p> <p>Or if you made the same mistake I did, you are using the incorrect token. This is non-obvious from the Slack docs. You can post a message with a custom integration bot token, including using attachments (i.e. interactive b...
1
2016-09-08T13:52:13Z
[ "python", "slack-api", "slack" ]
Cannot seem to get read_batch_examples working alongside an Estimator
39,041,125
<p><strong>EDIT</strong>: I'm using TensorFlow version 0.10.0rc0</p> <p>I'm currently trying to use <code>tf.contrib.learn.read_batch_examples</code> working while using a TensorFlow (SKFlow/tf.contrib) Estimator, specifically the <code>LinearClassifier</code>. I create a <code>read_batch_examples</code> op feeding in...
0
2016-08-19T14:07:37Z
39,296,428
<p>I was able to figure out my mistake through the help of the great TensorFlow team! <code>read_batch_examples</code> has to be called within <code>input_fn</code>, otherwise the op has to be run beforehand as it'll be from a different graph. If someone else has this problem and I wasn't clear enough, just leave a com...
0
2016-09-02T15:53:01Z
[ "python", "python-2.7", "tensorflow" ]
SearchCursor in Arcpy Returning Tuples & Lists, Not a List
39,041,128
<p>I have a fairly simple piece of code that searches a polygon feature class and stores the data for a selection of fields in a list:</p> <pre><code>for eachSMField in smFieldList: with arcpy.da.SearchCursor(seamaskPGN, eachSMField) as cursor: for row in cursor: cfbDataList.append(row) ...
-1
2016-08-19T14:07:42Z
39,045,024
<p>The output of <code>SearchCursor</code> is an iterator of tuples. You're appending each row (tuple) to your list rather than the values themselves. Change your append statement to <code>cfbDataList.append(row[0])</code> to append the value instead of the tuple.</p> <p>Another thing to check is the value of <code>ea...
0
2016-08-19T17:48:23Z
[ "python", "list", "cursor", "tuples", "arcpy" ]
How to setup pyvisa exception handler?
39,041,142
<p>I try to use python 3 and pyvisa 1.8 to communicate with GPIB devices. </p> <p>but how to distinguish different type of excptions.</p> <p>For example:</p> <pre><code>try: visa.ResourceManager().open_resources('COM1') exception visa.VisaIOError: &lt;some code&gt; </code></pre> <p>when open fails, it generate ...
2
2016-08-19T14:08:23Z
39,066,537
<p>Visa can also raise ValueErrors and AttributeError if you somehow give it bad data. I think it can raise IOError, though I've never seen that happen.</p> <p>But yes, it mostly raises VisaIOError. </p> <p>Some things you can do to get more information about an exception are:</p> <pre><code>_rm = visa.ResourceManag...
0
2016-08-21T16:44:34Z
[ "python", "visa" ]
How to determine which python env IPython uses
39,041,147
<p>I just installed <code>anaconda</code>in order to use <code>numba</code> and I'd like to use the anaconda environment in IPython (occasionally). The issue is that I either set the anaconda install to be default system python env and then IPython always uses the anaconda env, or I can't use anaconda's env with IPytho...
0
2016-08-19T14:08:44Z
39,041,691
<p>With Anaconda you can install iPython into an environment. You would activate this environment and launch iPython. iPython will then use the environment it is launched from. Say I wanted a Python2 environment with Pandas, iPython and Numpy.</p> <p>This creates the environment:</p> <pre><code>conda create -n py27 p...
1
2016-08-19T14:34:51Z
[ "python", "ipython", "anaconda", "environment" ]
NameError: global name 'NoneType' is not defined in Spark
39,041,316
<p>I have written a UDF to replace a few specific date values in a column named "latest_travel_date" with 'NA'. However, this column also contains many null values, so I have handled this also in the UDF. (please see below)</p> <pre><code>Query: def date_cleaner(date_col): if type(date_col) == NoneType: pa...
0
2016-08-19T14:17:53Z
39,041,415
<p>The problem is this line:</p> <pre><code>if type(date_col) == NoneType: </code></pre> <p>It looks like you actually want:</p> <pre><code>if date_col is None: </code></pre>
2
2016-08-19T14:22:46Z
[ "python", "apache-spark", "bigdata", "pyspark", "user-defined-functions" ]
NameError: global name 'NoneType' is not defined in Spark
39,041,316
<p>I have written a UDF to replace a few specific date values in a column named "latest_travel_date" with 'NA'. However, this column also contains many null values, so I have handled this also in the UDF. (please see below)</p> <pre><code>Query: def date_cleaner(date_col): if type(date_col) == NoneType: pa...
0
2016-08-19T14:17:53Z
39,041,567
<p>This issue could be solved by two ways.</p> <p>If you try to find the Null values from your dataFrame you should use the <a href="https://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark.sql.types.NullType" rel="nofollow">NullType</a>.</p> <p>Like this:</p> <pre><code>if type(date_col) == NullType...
2
2016-08-19T14:28:59Z
[ "python", "apache-spark", "bigdata", "pyspark", "user-defined-functions" ]
NameError: global name 'NoneType' is not defined in Spark
39,041,316
<p>I have written a UDF to replace a few specific date values in a column named "latest_travel_date" with 'NA'. However, this column also contains many null values, so I have handled this also in the UDF. (please see below)</p> <pre><code>Query: def date_cleaner(date_col): if type(date_col) == NoneType: pa...
0
2016-08-19T14:17:53Z
39,058,977
<p>As pointed out by Michael, you cannot do</p> <pre><code>if type(date_col) == NoneType: </code></pre> <p>However, changing that to <code>None</code> won't complete the task. There is another issue with</p> <pre><code>date_col= 'NA' </code></pre> <p>It is of <code>StringType</code> but you declared the return type...
0
2016-08-20T21:48:32Z
[ "python", "apache-spark", "bigdata", "pyspark", "user-defined-functions" ]
Fastest way to send long string from C# to Python
39,041,401
<p>I have a long string of data streaming continuously, which is generated by my C# script. I would like to use it as an input to Python Machine Learning model. </p> <p>What is the fastest &amp; easiest way to implement this transmission? </p> <p>I have found some possible options:</p> <ol> <li>Use sockets.</li> <li...
2
2016-08-19T14:22:04Z
39,041,750
<p>Provided that these processes run on the same machine, I think when handling big chunks of data between process <a href="https://docs.python.org/3/library/mmap.html" rel="nofollow">memory mapping</a> is the way to go.</p> <p>In other case TCP/UDP sockets is a good option since they don't have the overhead of the Ap...
0
2016-08-19T14:37:39Z
[ "c#", "python", "sockets", "tcp", "data-stream" ]
Fastest way to send long string from C# to Python
39,041,401
<p>I have a long string of data streaming continuously, which is generated by my C# script. I would like to use it as an input to Python Machine Learning model. </p> <p>What is the fastest &amp; easiest way to implement this transmission? </p> <p>I have found some possible options:</p> <ol> <li>Use sockets.</li> <li...
2
2016-08-19T14:22:04Z
39,043,545
<p>I suggest option 6 Use Database like sqlite.</p> <p>With this option you gain:</p> <ul> <li>Both running OnLine</li> <li>Python set flags to these records in database when they processed.</li> <li>You can complete operation latter if python off, and continue processing data.</li> <li>You can add results from pytho...
0
2016-08-19T16:11:25Z
[ "c#", "python", "sockets", "tcp", "data-stream" ]
If loop continue is executing for loop again
39,041,698
<pre><code>if eqp_id: for rule in items: if rule.eqp_pricelist == True: print "id 1" print rule.id continue print "id 2 out" print rule.id #outputs: #id1 #5 #id 2 out #4 </code></pre> <p>How is it possible that <code>rule.id = 5</code> comes before <code...
0
2016-08-19T14:35:09Z
39,054,619
<p>As you noted in your comment, if <code>items</code> is acquired using: <code>items = self.pool.get('product.pricelist.item').browse(cr, uid, item_ids, context=context)</code> then <code>items</code> is a "recordset" of Odoo ORM, so you can use a <strong><code>sorted()</code></strong> function of Odoo ORM (<a href="h...
2
2016-08-20T13:21:40Z
[ "python", "openerp", "odoo-9" ]
Create "buffer" matrix from dataframe with rolling window?
39,041,769
<p>Given a dataframe of just one column, how can I convert it into another dataframe "buffer" (of size 2), described below:</p> <p>df =</p> <pre><code> 0 0 1 1 2 2 3 3 4 4 4 5 5 6 5 </code></pre> <p>expected_buffer =</p> <pre><code> 0 1 0 1 2 1 2 3 2 3 4 3 4 5 </code></pre> <p>This is my attempt:</...
3
2016-08-19T14:38:28Z
39,042,046
<pre><code>def buff(df, past): a = np.concatenate([df.values[i:i-past] for i in range(past)], axis=1) return pd.DataFrame(a, columns=list(range(past))) </code></pre> <hr> <pre><code>buff(df, 2) </code></pre> <p><a href="http://i.stack.imgur.com/hRSu9.png" rel="nofollow"><img src="http://i.stack.imgur.com/hRS...
4
2016-08-19T14:52:39Z
[ "python", "pandas", "numpy" ]
Create "buffer" matrix from dataframe with rolling window?
39,041,769
<p>Given a dataframe of just one column, how can I convert it into another dataframe "buffer" (of size 2), described below:</p> <p>df =</p> <pre><code> 0 0 1 1 2 2 3 3 4 4 4 5 5 6 5 </code></pre> <p>expected_buffer =</p> <pre><code> 0 1 0 1 2 1 2 3 2 3 4 3 4 5 </code></pre> <p>This is my attempt:</...
3
2016-08-19T14:38:28Z
39,043,020
<pre><code>import pandas as pd def buff(s, n): return (pd.concat([s.shift(-i) for i in range(n)], axis=1) .dropna().astype(int)) s = pd.Series([1,2,3,4,5]) print(buff(s, 2)) # 0 0 # 0 1 2 # 1 2 3 # 2 3 4 # 3 4 5 print(buff(s, 3)) # 0 0 0 # 0 1 2 3 # 1 2 3 4 # 2 3 4 5 pr...
3
2016-08-19T15:41:11Z
[ "python", "pandas", "numpy" ]
Three variables as heatmap
39,041,865
<p>I want to plot my data as a heatmap which has the following structure:</p> <p><code>X = [1,1,1,1,1,1,1,1,1,1], Y = [1,2,3,4,5,6,7,8,9,10] Z = [0.2, 0.33, 0.1, 0.25, 0.0, 0.9, 0.75, 0.88, 0.44, 0.95]</code></p> <p>The x and y-axis shall be represented by X and Y, while the 'heat' is represented by the values of Z.<...
0
2016-08-19T14:42:41Z
39,042,065
<p>I hope your data is just an example because it will look funny (it's more a sequence of strips; the x-dimension is constant).</p> <p>I would recommend the usage of <a href="http://pandas.pydata.org/" rel="nofollow">pandas (general data-analysis)</a> and <a href="https://stanford.edu/~mwaskom/software/seaborn/" rel=...
3
2016-08-19T14:54:10Z
[ "python", "matplotlib", "heatmap" ]
Returning data from many rows with different values
39,041,900
<p>so i have been having a problem with my code.</p> <p>What im trying to do is i have a list set up like:</p> <pre><code>locationList = [['mt', 'moon', 'mt-moon'], ['misty', 'mis'], ['surge', 'sur'], ect...] </code></pre> <p>And what this is is they are inputs the people use, so instead of having to input the whole...
0
2016-08-19T14:44:59Z
39,042,641
<p>Just taking a guess from "Its just a Local .db file" that you're using SQLite and the built-in <code>sqlite3</code> Python module.</p> <p>If so, I think you want this:</p> <pre><code>c.execute("SELECT Name, CurrentBetValue FROM Users WHERE CurrentBetLocation IN ({})".format(",".join("?"*len(sublist))), sublist) </...
1
2016-08-19T15:21:33Z
[ "python", "sql" ]
Calculate difference between 2 dates in python dataframe
39,042,102
<p>I've looked through python advice and worked out how to calculate the difference between two dates, e.g. <a href="http://stackoverflow.com/questions/8419564/difference-between-two-dates">Difference between two dates?</a>. That works, but ... I'm working with variables in a dataframe. I'm sure I'm following the advic...
0
2016-08-19T14:55:26Z
39,042,249
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow"><code>pandas.to_datetime</code></a>:</p> <pre><code>df["SDATE"] = pd.to_datetime(df["SDATE"], format="%d/%m/%Y") df["QDATE"] = pd.to_datetime(df["QDATE"], format="%d/%m/%Y") df["DAYSDIFF"] = df["SDATE"] - df[...
0
2016-08-19T15:02:48Z
[ "python", "datetime" ]
Operands could not be broadcast together error when two rows used
39,042,148
<p>Working with the following data:</p> <pre><code>import datetime,numpy as np,pandas as pd nan = np.nan a = pd.DataFrame( {'price': {datetime.time(9, 0): 1, datetime.time(10, 0): 0, datetime.time(11, 0): 3, datetime.time(12, 0): 4, datetime.time(13, 0): 7, datetime.time(14, 0): 6, datetime.time(15, 0): ...
1
2016-08-19T14:58:18Z
39,047,581
<p>Yup it has to be for loop... Now I changed it to choose first from hit or miss.</p> <pre><code>import datetime,numpy as np,pandas as pd; nan = np.nan; a = pd.DataFrame( {'price': {datetime.time(9, 0): 1, datetime.time(10, 0): 0, datetime.time(11, 0): 3, datetime.time(12, 0): 4, datetime.time(13, 0): 7, ...
1
2016-08-19T20:59:16Z
[ "python", "pandas" ]
How can I slice each element of a numpy array of strings?
39,042,214
<p>Numpy has some very useful <a href="http://docs.scipy.org/doc/numpy/reference/routines.char.html" rel="nofollow">string operations</a>, which vectorize the usual Python string operations.</p> <p>Compared to these operation and to <code>pandas.str</code>, the numpy strings module seems to be missing a very important...
11
2016-08-19T15:01:00Z
39,042,910
<p>Interesting omission... I guess you can always write your own:</p> <pre><code>import numpy as np def slicer(start=None, stop=None, step=1): return np.vectorize(lambda x: x[start:stop:step], otypes=[str]) a = np.array(['hello', 'how', 'are', 'you']) print(slicer(1, 3)(a)) # =&gt; ['el' 'ow' 're' 'ou'] </cod...
3
2016-08-19T15:35:31Z
[ "python", "arrays", "string", "numpy", "slice" ]
How can I slice each element of a numpy array of strings?
39,042,214
<p>Numpy has some very useful <a href="http://docs.scipy.org/doc/numpy/reference/routines.char.html" rel="nofollow">string operations</a>, which vectorize the usual Python string operations.</p> <p>Compared to these operation and to <code>pandas.str</code>, the numpy strings module seems to be missing a very important...
11
2016-08-19T15:01:00Z
39,043,288
<p>Most, if not all the functions in <code>np.char</code> apply existing <code>str</code> methods to each element of the array. It's a little faster than direct iteration (or <code>vectorize</code>) but not drastically so.</p> <p>There isn't a string slicer; at least not by that sort of name. Closest is indexing wit...
2
2016-08-19T15:55:55Z
[ "python", "arrays", "string", "numpy", "slice" ]
How can I slice each element of a numpy array of strings?
39,042,214
<p>Numpy has some very useful <a href="http://docs.scipy.org/doc/numpy/reference/routines.char.html" rel="nofollow">string operations</a>, which vectorize the usual Python string operations.</p> <p>Compared to these operation and to <code>pandas.str</code>, the numpy strings module seems to be missing a very important...
11
2016-08-19T15:01:00Z
39,045,337
<p>Here's a vectorized approach -</p> <pre><code>def slicer_vectorized(a,start,end): b = a.view('S1').reshape(len(a),-1)[:,start:end] return np.fromstring(b.tostring(),dtype='S'+str(end-start)) </code></pre> <p>Sample run -</p> <pre><code>In [68]: a = np.array(['hello', 'how', 'are', 'you']) In [69]: slicer...
6
2016-08-19T18:09:01Z
[ "python", "arrays", "string", "numpy", "slice" ]
How can I slice each element of a numpy array of strings?
39,042,214
<p>Numpy has some very useful <a href="http://docs.scipy.org/doc/numpy/reference/routines.char.html" rel="nofollow">string operations</a>, which vectorize the usual Python string operations.</p> <p>Compared to these operation and to <code>pandas.str</code>, the numpy strings module seems to be missing a very important...
11
2016-08-19T15:01:00Z
39,045,428
<p>To solve this, so far I've been transforming the numpy <code>array</code> to a pandas <code>Series</code> and back. It is not a pretty solution, but it works and it works relatively fast.</p> <pre><code>a = numpy.array(['hello', 'how', 'are', 'you']) pandas.Series(a).str[1:3].values array(['el', 'ow', 're', 'ou'], ...
1
2016-08-19T18:15:38Z
[ "python", "arrays", "string", "numpy", "slice" ]
Return True/False - when to use it over just return
39,042,320
<p>I have searched over internet why i should use return False/True over just return but can not find the answer.</p> <p>Why would i want to have statement return True/False inseatd of just return ? Can you please show me an example ?</p> <pre><code>def test(var): if var &gt; 5: return True else: ...
-7
2016-08-19T15:06:03Z
39,042,386
<p>One major problem is that your second function will return <code>None</code> either way. Returning a boolean value is a way to have the return value of your function be meaningful/useful elsewhere.</p> <p>If it returns a value like <code>True</code> or <code>False</code>, you can in turn use the return value of you...
1
2016-08-19T15:08:38Z
[ "python", "python-2.7" ]
Return True/False - when to use it over just return
39,042,320
<p>I have searched over internet why i should use return False/True over just return but can not find the answer.</p> <p>Why would i want to have statement return True/False inseatd of just return ? Can you please show me an example ?</p> <pre><code>def test(var): if var &gt; 5: return True else: ...
-7
2016-08-19T15:06:03Z
39,043,750
<p>Analogy: A function is a cloneable assistant ready to perform a task, and give you an answer. The task is defined by the <em>parameters</em> of the function (the stuff inside the parentheses). Let's rewrite the names to give them semantic meaning (i.e. names which illustrate what we expect).</p> <pre><code>def isXG...
1
2016-08-19T16:24:18Z
[ "python", "python-2.7" ]
Calling Twisted recator.run() Inside flask app
39,042,399
<p>I am writing a web service in python flask for Jasmin SMS Gateway to create and delete user from the gateway. In case of POST request I am calling runScenario() and after that I am starting reactor.run() which will create user in the gateway. this code runs perfectly for the first web service call but on second call...
0
2016-08-19T15:09:22Z
39,046,221
<p>Reactor is not restartable in Twisted by design, it performs initialization and finalization that isn't easily restartable.</p> <p>In the example provided you're using a development WSGI server (flask's default one, <a href="http://werkzeug.pocoo.org/docs/0.11/serving/" rel="nofollow">http://werkzeug.pocoo.org/docs...
0
2016-08-19T19:12:02Z
[ "python", "python-2.7", "flask", "twisted" ]
Calling Twisted recator.run() Inside flask app
39,042,399
<p>I am writing a web service in python flask for Jasmin SMS Gateway to create and delete user from the gateway. In case of POST request I am calling runScenario() and after that I am starting reactor.run() which will create user in the gateway. this code runs perfectly for the first web service call but on second call...
0
2016-08-19T15:09:22Z
39,049,476
<p>You can't stop the reactor and run it again. The error you're getting is by design. Consider using <code>klein</code> it uses <code>werkzeug</code> like <code>flask</code> and leverages <code>twisted</code> for networking as well. The syntax is even similar. Translating your code into <code>klein</code> would lo...
0
2016-08-20T00:51:29Z
[ "python", "python-2.7", "flask", "twisted" ]
Calling Twisted recator.run() Inside flask app
39,042,399
<p>I am writing a web service in python flask for Jasmin SMS Gateway to create and delete user from the gateway. In case of POST request I am calling runScenario() and after that I am starting reactor.run() which will create user in the gateway. this code runs perfectly for the first web service call but on second call...
0
2016-08-19T15:09:22Z
39,072,729
<p>@ffeast I also tried to do it in twisted but encountered the same problem, as reactor is not restartable.In twisted I have done something like this:</p> <pre><code>#!/usr/bin/env python from pprint import pprint import json from twisted.web import server, resource from twisted.internet import reactor from JasminInt...
0
2016-08-22T06:38:12Z
[ "python", "python-2.7", "flask", "twisted" ]
find_one() return one document give a combination of fields
39,042,409
<p>I am trying to return a document from my mongodb (using pymongo). I want the query to return a document given an id and a tag. </p> <pre><code>ids = ['123', '456', '234', '534'] rows = [] for i in ids: for b in ["Tag1", "Tag2", "Tag3"]: temp = pb_db.db.collection.find_one({"ID": i, "Tag": b}, {'ID': 1,...
0
2016-08-19T15:10:00Z
39,042,951
<p>You could do it in a single pass by using the <a href="https://docs.mongodb.com/manual/reference/operator/query/in/#op._S_in" rel="nofollow">$in operator</a> to compare the items in the "ID" array in the database with the items in the "ids" array variable, and similarly for the tags.</p> <blockquote> <p>Use the $...
-1
2016-08-19T15:37:46Z
[ "python", "mongodb", "mongodb-query", "pymongo" ]
find_one() return one document give a combination of fields
39,042,409
<p>I am trying to return a document from my mongodb (using pymongo). I want the query to return a document given an id and a tag. </p> <pre><code>ids = ['123', '456', '234', '534'] rows = [] for i in ids: for b in ["Tag1", "Tag2", "Tag3"]: temp = pb_db.db.collection.find_one({"ID": i, "Tag": b}, {'ID': 1,...
0
2016-08-19T15:10:00Z
39,044,810
<p>You need to use <a href="https://docs.mongodb.com/manual/reference/operator/query/in/" rel="nofollow"><code>$in</code></a> and the <a href="https://docs.mongodb.com/manual/reference/operator/query/elemMatch/" rel="nofollow"><code>$elemMatch</code></a> query operator.</p> <pre><code>ids = ['123', '456', '234', '534'...
0
2016-08-19T17:35:28Z
[ "python", "mongodb", "mongodb-query", "pymongo" ]
iterate over list of dicts to create different strings
39,042,532
<p>I have a pandas file with 3 different columns that I turn into a dictionary with to_dict, the result is a list of dictionaries:</p> <pre><code>df = [ {'HEADER1': 'col1-row1', 'HEADER2: 'col2-row1', 'HEADER3': 'col3-row1'}, {'HEADER1': 'col1-row2', 'HEADER2: 'col2-row2', 'HEADER3': 'col3-row2'} ] </code></pre> <p>N...
-1
2016-08-19T15:15:53Z
39,042,737
<p>You only ever iterate twice, and <em>short-circuit</em> out of the nested <code>for</code> loop every time it is executed by having a <code>return</code> statement there. Looking up the necessary information from the dictionary will allow you to build up your url's. One possible example:</p> <pre><code>def get_urls...
2
2016-08-19T15:26:24Z
[ "python", "for-loop", "dictionary" ]
Place backslash between words in string
39,042,637
<p>I Want to convert com to newcom </p> <pre><code>com = R.E.M. - Losing My Religion.mp3 newcom = R.E.M.\ -\ Losing\ My\ Religion.mp3 </code></pre> <p>I am doing this because Ubuntu terminal needs backslashes to specify spaces in paths.</p> <p>This is just a string manipulation, what do I need to do?</p>
-3
2016-08-19T15:21:10Z
39,042,726
<p>Look into the replace() method in python: <a href="http://www.tutorialspoint.com/python/string_replace.htm" rel="nofollow">http://www.tutorialspoint.com/python/string_replace.htm</a></p>
-1
2016-08-19T15:25:39Z
[ "python" ]
Place backslash between words in string
39,042,637
<p>I Want to convert com to newcom </p> <pre><code>com = R.E.M. - Losing My Religion.mp3 newcom = R.E.M.\ -\ Losing\ My\ Religion.mp3 </code></pre> <p>I am doing this because Ubuntu terminal needs backslashes to specify spaces in paths.</p> <p>This is just a string manipulation, what do I need to do?</p>
-3
2016-08-19T15:21:10Z
39,042,744
<pre><code>newcom = com.replace(' ', '\\ ') </code></pre> <p>You need to replace a space with an (escaped) backslash and another space - that's exactly what Python's replace method is for.</p> <p>Alternatively, an ubuntu terminal is fine with directories in quotes, e.g.</p> <pre><code>cd "hello world" </code></pre> ...
0
2016-08-19T15:26:47Z
[ "python" ]
Trying to subtract two dates to find number of days inbetween
39,042,774
<p>Within Zapier, I have two dates and am trying to find the number of days between them in a Code Step. I run a Formatter Step on each date to output a datetime object in YYYY-MM-DD then run the following code below:</p> <pre><code>submit = input['submit_date'] event = input['event_date'] delta = event-submit numdays...
0
2016-08-19T15:28:11Z
39,042,902
<p>The formatter steps aren't included, but in general you are wanting time or datetime objects (<code>import time</code> or <code>import datetime</code>)</p> <p>You should probably be looking at something like <code>datetime.strptime(date_string, format)</code> from the datetime option to take your text string and c...
3
2016-08-19T15:35:11Z
[ "python", "datetime", "zapier" ]
Trying to subtract two dates to find number of days inbetween
39,042,774
<p>Within Zapier, I have two dates and am trying to find the number of days between them in a Code Step. I run a Formatter Step on each date to output a datetime object in YYYY-MM-DD then run the following code below:</p> <pre><code>submit = input['submit_date'] event = input['event_date'] delta = event-submit numdays...
0
2016-08-19T15:28:11Z
39,043,029
<p>I have 2 methods <code>get_days(start_date, end_date)</code> and <code>increment_da_day(str_date)</code></p> <p>invoke <code>get_days()</code> it returns you a list of days(format is yyyymmdd), you can provide your start date and end date and print the <code>get_days(start_date, end_date) - 1</code></p> <p>For exa...
0
2016-08-19T15:41:44Z
[ "python", "datetime", "zapier" ]
Trying to subtract two dates to find number of days inbetween
39,042,774
<p>Within Zapier, I have two dates and am trying to find the number of days between them in a Code Step. I run a Formatter Step on each date to output a datetime object in YYYY-MM-DD then run the following code below:</p> <pre><code>submit = input['submit_date'] event = input['event_date'] delta = event-submit numdays...
0
2016-08-19T15:28:11Z
39,043,104
<p>if they are strings the you can either pass input or take the input right there, the following code will return the days </p> <pre><code>def h(): from datetime import datetime date_format = "%m/%d/%Y" a = datetime.strptime(input('Enter first date in MM/DD/YY format '), date_format) b = datetime.strp...
0
2016-08-19T15:46:30Z
[ "python", "datetime", "zapier" ]
Is there a random letter generator with a range?
39,042,775
<p>I was wondering if there is a random letter generator in Python that takes a range as parameter? For example, if I wanted a range between A and D? I know you can use this as a generator:</p> <pre><code>import random import string random.choice(string.ascii_letters) </code></pre> <p>But it doesn't allow you to sup...
5
2016-08-19T15:28:15Z
39,042,805
<p>Ascii is represented with numbers, so you can random a number in the range that you prefer and then cast it to char.</p>
4
2016-08-19T15:29:59Z
[ "python" ]
Is there a random letter generator with a range?
39,042,775
<p>I was wondering if there is a random letter generator in Python that takes a range as parameter? For example, if I wanted a range between A and D? I know you can use this as a generator:</p> <pre><code>import random import string random.choice(string.ascii_letters) </code></pre> <p>But it doesn't allow you to sup...
5
2016-08-19T15:28:15Z
39,042,831
<p>The function <code>choice</code> takes a general sequence.</p> <blockquote> <p>Return a random element from the non-empty sequence seq.</p> </blockquote> <p>In particular</p> <pre><code>random.choice(['A', 'B', 'C', 'D']) </code></pre> <p>will do what you want.</p> <p>You can easily generate the range program...
3
2016-08-19T15:31:44Z
[ "python" ]
Is there a random letter generator with a range?
39,042,775
<p>I was wondering if there is a random letter generator in Python that takes a range as parameter? For example, if I wanted a range between A and D? I know you can use this as a generator:</p> <pre><code>import random import string random.choice(string.ascii_letters) </code></pre> <p>But it doesn't allow you to sup...
5
2016-08-19T15:28:15Z
39,042,834
<p>You can slice <code>string.ascii_letters</code>:</p> <pre><code>random.choice(string.ascii_letters[0:4]) </code></pre>
6
2016-08-19T15:31:52Z
[ "python" ]
Is there a random letter generator with a range?
39,042,775
<p>I was wondering if there is a random letter generator in Python that takes a range as parameter? For example, if I wanted a range between A and D? I know you can use this as a generator:</p> <pre><code>import random import string random.choice(string.ascii_letters) </code></pre> <p>But it doesn't allow you to sup...
5
2016-08-19T15:28:15Z
39,042,843
<p>String slicing would be my solution to this</p> <pre><code>random.choice(string.ascii_letters[:4]) </code></pre> <p>This would randomly choose one of the first 4 letters of the alphabet. Obviously 4 could be any value.</p>
3
2016-08-19T15:32:10Z
[ "python" ]
Is there a random letter generator with a range?
39,042,775
<p>I was wondering if there is a random letter generator in Python that takes a range as parameter? For example, if I wanted a range between A and D? I know you can use this as a generator:</p> <pre><code>import random import string random.choice(string.ascii_letters) </code></pre> <p>But it doesn't allow you to sup...
5
2016-08-19T15:28:15Z
39,042,919
<p>You can trivially define such a thing:</p> <pre><code>def letters_in_range(start_letter, end_letter): start_index = string.ascii_letters.find(start_letter) end_index = string.ascii_letters.find(end_letter) assert start_index != -1 assert end_index != -1 assert start_letter &lt; end_letter return s...
1
2016-08-19T15:35:57Z
[ "python" ]
Is there a random letter generator with a range?
39,042,775
<p>I was wondering if there is a random letter generator in Python that takes a range as parameter? For example, if I wanted a range between A and D? I know you can use this as a generator:</p> <pre><code>import random import string random.choice(string.ascii_letters) </code></pre> <p>But it doesn't allow you to sup...
5
2016-08-19T15:28:15Z
39,042,937
<pre><code>&gt;&gt;&gt; random.choice('ABCD') 'C' </code></pre> <p>Or if it's a larger range so you don't want to type them all out:</p> <pre><code>&gt;&gt;&gt; chr(random.randint(ord('I'), ord('Q'))) 'O' </code></pre>
2
2016-08-19T15:36:55Z
[ "python" ]
Is there a random letter generator with a range?
39,042,775
<p>I was wondering if there is a random letter generator in Python that takes a range as parameter? For example, if I wanted a range between A and D? I know you can use this as a generator:</p> <pre><code>import random import string random.choice(string.ascii_letters) </code></pre> <p>But it doesn't allow you to sup...
5
2016-08-19T15:28:15Z
39,043,070
<p>Using your original way of getting a random letter you can simply make a function as such.</p> <pre><code>def getLetter(start, stop): letter = random.choice(string.ascii_letters) while letter &lt; start and letter &gt; stop: letter = random.choice(string.ascii_letters) return letter </code></pre...
1
2016-08-19T15:44:19Z
[ "python" ]
How to sum within a groupby over with both numeric and non-numeric data types
39,042,785
<p>Consider the following <code>df</code></p> <pre><code>df = pd.DataFrame([ ['X', 'a', 0, 1], ['X', 'b', 2, 3], ['X', 'c', 4, 5], ['Y', 'a', 6, 7], ['Y', 'b', 8, 9], ['Y', 'c', 10, 11], ], columns=['One', 'Two', 'Three', 'Four']) df </code></pre> <p><a href="http:/...
4
2016-08-19T15:29:07Z
39,042,867
<p>It's possible to achieve your desired result by using <code>agg</code> with a <code>lambda</code>:</p> <pre><code>In [6]: df.groupby('One').agg(lambda x: x.sum()) Out[6]: Two Three Four One X abc 6 9 Y abc 24 27 </code></pre>
4
2016-08-19T15:33:14Z
[ "python", "pandas", "group-by" ]
pandas fillna with multiple columns
39,042,872
<p>I used <code>pandas.concat</code> to join several <code>Dataframe</code> together and would like to fill the <code>NaN</code> values in one column with the <code>value</code> of several other columns.</p> <p>To get the below table, I did: <code>z = pandas.concat([df1, df2, df3], axis=0, join='outer')</code></p> <p...
1
2016-08-19T15:33:46Z
39,045,739
<p>If you make sure that your <code>df1</code>, <code>df2</code> and <code>df3</code> have the same columns, the concatenation is done as desired.</p> <p>In this case, you could do:</p> <pre><code>df2.columns = df1.columns df3.columns = df1.columns # at this point concat will give you the desired result pandas.conca...
-1
2016-08-19T18:36:12Z
[ "python", "pandas" ]
PIL in Python complains that there are no 'size' attributes to a PixelAccess, what am I doing wrong?
39,042,950
<p>I am trying to program an application that will loop through every pixel of a given image, get the rgb value for each, add it to a dictionary (along with amount of occurences) and then give me rundown of the most used rgb values.</p> <p>However, to be able to loop through images, I need to be able to fetch their si...
2
2016-08-19T15:37:46Z
39,043,060
<p><code>image.load</code> returns a pixel access object that does not have a <code>size</code> attribute</p> <pre><code>def load_image(path=sys.argv[1]): image = Image.open(path) im = image.load() SIZE = image.size return im </code></pre> <p>is what you want</p> <p><a href="http://effbot.org/imaging...
2
2016-08-19T15:43:57Z
[ "python", "image", "python-imaging-library" ]
PIL in Python complains that there are no 'size' attributes to a PixelAccess, what am I doing wrong?
39,042,950
<p>I am trying to program an application that will loop through every pixel of a given image, get the rgb value for each, add it to a dictionary (along with amount of occurences) and then give me rundown of the most used rgb values.</p> <p>However, to be able to loop through images, I need to be able to fetch their si...
2
2016-08-19T15:37:46Z
39,043,091
<p>Note that <a href="https://pypi.python.org/pypi/PIL" rel="nofollow">PIL (Python Imaging Library)</a> is deprecated and replaced by <a href="https://pillow.readthedocs.io" rel="nofollow">Pillow</a>.</p> <p>The problem is about the <a href="http://pillow.readthedocs.io/en/3.3.x/reference/PixelAccess.html" rel="nofoll...
1
2016-08-19T15:45:43Z
[ "python", "image", "python-imaging-library" ]
regular expression to match phone number but not zipcodes
39,042,969
<p>I have written below regex</p> <pre><code>phone_regex = re.compile(r'(\+?\(?\+?\d{1,}\)?[-\s\.]?\d{1,}[-\s\.]?\d{1,}[-\s\.]?\d{1,}[-\s\.]?\d{1,}[-s\.]?)') </code></pre> <p>It matches &amp; identifies phone numbers along with country codes eg <code>+91 9561217616</code>,<code>(+91) 9561 217 616</code>,<code>+(91) ...
-3
2016-08-19T15:38:54Z
39,043,430
<p>You need to specify number of matches, e.g. <code>{m, n}</code> or <code>{m}</code> like:</p> <pre><code>regexp = r''' # matches phones, but not zipcodes. Use with VERBOSE regexps ^ # start of the string \s*? # whitespaces, etc \+? # + char (optional) \s*? # whitespaces, etc \(? # ( char (optional) ([0-9]...
1
2016-08-19T16:03:28Z
[ "python", "regex" ]
regular expression to match phone number but not zipcodes
39,042,969
<p>I have written below regex</p> <pre><code>phone_regex = re.compile(r'(\+?\(?\+?\d{1,}\)?[-\s\.]?\d{1,}[-\s\.]?\d{1,}[-\s\.]?\d{1,}[-\s\.]?\d{1,}[-s\.]?)') </code></pre> <p>It matches &amp; identifies phone numbers along with country codes eg <code>+91 9561217616</code>,<code>(+91) 9561 217 616</code>,<code>+(91) ...
-3
2016-08-19T15:38:54Z
39,043,478
<p><code>(?:\+\d\d|\(\+\d\d\)|\+\(\d\d\))(?:\s+|-)\d{4}(?:\s+|-)?\d{3}(?:\s+|-)?\d{3}$</code></p> <ul> <li><code>(?:\+\d\d|\(\+\d\d\)|\+\(\d\d\))</code> +00 or (+00) or +(00)</li> <li><code>(?:\s+|-)</code> a gap (at least one space or a single dash)</li> <li><code>\d{4}</code> 4 numbers (0000)</li> <li><code>(?:\s+|-...
1
2016-08-19T16:06:43Z
[ "python", "regex" ]
Pandas: Type conversion using `df.loc` from datetime64 to int
39,042,997
<p>When trying to re-assign certain values in a column using <code>df.loc[]</code> I am getting a strange type conversion error converting datetimes to integers.</p> <p><strong>Minimal Example:</strong></p> <pre><code>import numpy as np import pandas as pd import datetime d = pd.DataFrame(zip(['12/6/2015', np.nan], [...
3
2016-08-19T15:40:00Z
39,044,349
<p>We'll start with the first question: <strong>how to avoid this behavior?</strong></p> <p>My understanding is that you want to convert the <code>prior_eta_date</code> column to datetime objects. The Pandas style approach is to use <code>to_datetime</code>:</p> <pre><code>df.prior_ea_date = pd.to_datetime(df.prior_e...
3
2016-08-19T17:02:43Z
[ "python", "datetime", "pandas", "type-conversion" ]
How do I write a python dictionary to an excel file?
39,043,010
<p>I'm trying to write a dictionary with randomly generated strings and numbers to an excel file. I've almost succeeded but with one minor problem. The structure of my dictionary is as follows:</p> <pre><code>Age: 11, Names Count: 3, Names: nizbh,xyovj,clier </code></pre> <p>This dictionary was generated from data ob...
4
2016-08-19T15:40:51Z
39,043,950
<p>The problem was indeed in the two for loops there. I meddled and played around with them until I arrived at the answer. They're working fine. Thank you guys!</p> <p>Replace the for loops in the end with this:</p> <pre><code>for key in sorted(age_and_names):#.keys(): row+=1 worksheet.write(row, col, key) ...
2
2016-08-19T16:37:25Z
[ "python", "excel", "dictionary" ]
How to solve a pep8 Error thrown during a Maven build
39,043,035
<p>I've been trying to build a work project using maven and it's failing with the following error - </p> <pre><code>"[ERROR] Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.4.0:exec (pep8) on project xxx_1234: Command execution failed. Cannot run program "pep8" (in directory "C:\workspace\ projects\xxx\x...
0
2016-08-19T15:42:01Z
39,043,261
<p>So this probably means that <code>pep8</code> isn't installed. The easiest way to do fix this is install it with <code>pip</code>.</p> <pre><code>$ pip install pep8 </code></pre> <p>Try running that in a terminal, then your maven build should work just fine.</p>
0
2016-08-19T15:54:36Z
[ "java", "python", "maven-3" ]
ImportError: No module named _backend_gdk on Jupyter notebook with Conda
39,043,041
<p>Hello guys getting the following error on my jupyter notebook -</p> <p>Running a codeblock with <code>%matplotlib gtk</code> results in the exception</p> <pre><code>/usr/local/lib/python2.7/site-packages/matplotlib/backends/backend_gdk.py in &lt;module&gt;() 31 from matplotlib.mathtext import MathTextParser 32 f...
0
2016-08-19T15:42:39Z
39,620,224
<p>Take a look at this thread:</p> <p><a href="http://stackoverflow.com/questions/14346090/importerror-no-module-named-backend-gdk">ImportError: No module named _backend_gdk</a></p> <p>There, installing python-gtk2-dev is recommended.</p> <pre><code>sudo apt-get install python-gtk2-dev </code></pre>
0
2016-09-21T15:05:25Z
[ "python", "matplotlib", "jupyter" ]
Packages from private pypi don't find requirements
39,043,046
<p>I'm building a private pypi server and it's working, but the packages that I put there has some requirements from official pypi, but when I try to install my private package, the <code>install_requires</code> breaks trying to find the external dependencies in my private repository (I saw this in the log).</p> <p>Wh...
0
2016-08-19T15:42:58Z
39,044,483
<p>Add <code>--extra-index-url https://pypi.python.org/pypi</code> to your <code>pip install</code> command. See the documentation <a href="https://pip.pypa.io/en/stable/reference/pip_wheel/#cmdoption--extra-index-url" rel="nofollow">here</a>.</p>
1
2016-08-19T17:11:09Z
[ "python", "python-2.7", "pip", "setuptools" ]
Folder picker in HTML with Flask for Uploads
39,043,087
<p>I am running a Flask app where the user uploads a file and must select the root folder path of where to upload the file on a network drive. This path is an IIS available network path and is also a network drive on all user's computers.</p> <p>I know this can't be done with pure HTML due to security but wanted to k...
0
2016-08-19T15:45:28Z
39,044,636
<p><strong>Python</strong> runs on your server, therefoere it will not be possible to use that to move the files on the client side. If you think about it, let's assume you manage to somehow (magically) send python commands to the clients to move files, do you know if they even have python installed to be able to inter...
1
2016-08-19T17:22:13Z
[ "python", "html", "flask" ]
Folder picker in HTML with Flask for Uploads
39,043,087
<p>I am running a Flask app where the user uploads a file and must select the root folder path of where to upload the file on a network drive. This path is an IIS available network path and is also a network drive on all user's computers.</p> <p>I know this can't be done with pure HTML due to security but wanted to k...
0
2016-08-19T15:45:28Z
39,578,792
<p>Due to modern browser limitations I decided to use JSTree as a solution. And it is working very well. It features a tree structure browser. The structure is the result of outputting the folders as JSON. You can add a search bar as well so the user can just type in a folder name to search.<br> Please see <a href=...
0
2016-09-19T17:24:39Z
[ "python", "html", "flask" ]
Python package installation via yum
39,043,095
<p>What could be the difference of installing python packages via <code>yum</code> vs. via <code>pip</code>on <code>Centos</code> in terms of security? Is it even possible to install a python package only via <code>yum</code>?</p>
1
2016-08-19T15:46:09Z
39,043,207
<p><code>yum</code> can be used to install Python on CentOS.</p> <p><code>pip</code> is used to install Python libraries (packages). Not Python itself.</p> <p>No "security" issue. But with <code>yum</code> you could overwrite your native Python installation, which can be a problem.</p> <p>Instead of that, it is reco...
0
2016-08-19T15:51:36Z
[ "python", "security", "pip", "centos7", "yum" ]
Bokeh proof-of-concept efficient dynamic plot update?
39,043,115
<p>As a demonstration piece for proof-of-concept I've created a Bokeh plot of four OHLC candles.</p> <p>I would like to extend the demo to animate the plot so that the current candlestick would be made to move and update in response to changes to its OHLC data. An important point is that only the components (glyphs?)...
3
2016-08-19T15:47:02Z
39,708,864
<p>I created <a href="https://github.com/Formulator/candlestickmaker" rel="nofollow">candlestickmaker</a> which goes beyond the brief of this question to fulfil the intent; a demonstration Bokeh patching &amp; streaming OHLC chart.</p>
0
2016-09-26T17:25:57Z
[ "python", "animation", "plot", "bokeh", "candlestick-chart" ]
dictionary transformation
39,043,213
<p>How to map the elements of the lists in the dictionary below to their basic keys (i.e. basic keys are the ones that map to empty lists)</p> <pre><code>{ '1':[], '2':[], '3':['1','2'], '4':[], '5':[], '6':['4','5'], '7':['3','6'] } </code></pre> <p>which would result in</p> <pre><code>{ '1':[], '2':[], '3':{'1':[]...
-5
2016-08-19T15:51:59Z
39,043,337
<p>My understanding is that you want to convert values like <code>['1', '2']</code> to <code>dict</code> like <code>{'1': [], '2': []}</code>.</p> <p>Don't know why:</p> <pre><code>'6':['4','5'], '7':['3','6'] </code></pre> <p>Gives:</p> <pre><code>'6':{'4':[],'5':[]}, '7':{'3':{'1':[],'2':[]},'6':{'4':[],'5':[]}} ...
-1
2016-08-19T15:58:20Z
[ "python", "dictionary" ]
dictionary transformation
39,043,213
<p>How to map the elements of the lists in the dictionary below to their basic keys (i.e. basic keys are the ones that map to empty lists)</p> <pre><code>{ '1':[], '2':[], '3':['1','2'], '4':[], '5':[], '6':['4','5'], '7':['3','6'] } </code></pre> <p>which would result in</p> <pre><code>{ '1':[], '2':[], '3':{'1':[]...
-5
2016-08-19T15:51:59Z
39,043,634
<p>To get you started I would suggest something along this line.</p> <pre><code>def recursiveChange(object): if type(object) == type({}): #Whats happens when its a dictionary recursiveChange(NEWOBJECT) if type(object) == type([]): #What happens when its a list recursiveChange(NE...
0
2016-08-19T16:18:08Z
[ "python", "dictionary" ]
Read a file in Python and replace certain strings on the go
39,043,256
<p>I want to read a multiple files in Python in order to do some mapping between them. </p> <p>I'm pretty new at these things, so I got the code from someone else. But now I want to edit it. And I can't fully understand the python macros.</p> <p>So here's the code</p> <pre><code>def getDataFromFile(infile): ''' ...
0
2016-08-19T15:54:25Z
39,043,327
<p>Just add another test in your listcomp:</p> <pre><code>list = [[x if (x and x not in ["NA","whatever"]) else 'n/a' for x in line] for line in reader] </code></pre> <p>Which can be clearer like that with inverted logic and integrating empty string in checklist.</p> <pre><code>list = [['n/a' if (x in ["", "NA","wha...
1
2016-08-19T15:57:49Z
[ "python", "file" ]
Python: Merge two CSV files to multilevel JSON
39,043,323
<p>I am very new to Python/JSON so please bear with me on this. I could do this in R but we need to use Python so as to transform this to Python/Spark/MongoDB. Also, I am just posting a minimal subset - I have a couple more file types and so if anyone can help me with this, I can build upon that to integrate more files...
1
2016-08-19T15:57:36Z
39,044,587
<p>This looks like a problem for <code>pandas</code>! Unfortunately pandas only takes us so far and we then have to do some manipulation on our own. This is neither fast nor particularly efficient code, but it will get the job done.</p> <pre><code>import pandas as pd import json from collections import defaultdict # ...
2
2016-08-19T17:18:22Z
[ "python", "json", "csv" ]
Python: Merge two CSV files to multilevel JSON
39,043,323
<p>I am very new to Python/JSON so please bear with me on this. I could do this in R but we need to use Python so as to transform this to Python/Spark/MongoDB. Also, I am just posting a minimal subset - I have a couple more file types and so if anyone can help me with this, I can build upon that to integrate more files...
1
2016-08-19T15:57:36Z
39,045,101
<p>Here's another option. I tried to make it easy to manage when you start adding more files. You can run on the command line and provide arguments, one for each file you want to add in. Gene/sample names are stored in dictionaries to improve efficiency. The formatting of your desired JSON object is done in each cl...
2
2016-08-19T17:53:44Z
[ "python", "json", "csv" ]
Python: Merge two CSV files to multilevel JSON
39,043,323
<p>I am very new to Python/JSON so please bear with me on this. I could do this in R but we need to use Python so as to transform this to Python/Spark/MongoDB. Also, I am just posting a minimal subset - I have a couple more file types and so if anyone can help me with this, I can build upon that to integrate more files...
1
2016-08-19T15:57:36Z
39,045,203
<p>Do it in steps:</p> <ol> <li>Read the incoming <code>tsv</code> files and aggregate the information from different genes into a dictionary.</li> <li>Process said dictionary to match your desired format.</li> <li>Write the result to a JSON file.</li> </ol> <p>Here is the code:</p> <pre><code>import csv import json...
1
2016-08-19T18:01:09Z
[ "python", "json", "csv" ]
traceback shows only one line of a multiline command
39,043,353
<p>I have added a small debugging aid to my server. It logs a stack trace obtained from <code>traceback.format_stack()</code></p> <p>It contains few incomplete lines like this:</p> <pre><code>File "/home/...../base/loop.py", line 361, in run self.outputs.fd_list, (), sleep) </code></pre> <p>which is not that muc...
2
2016-08-19T15:59:34Z
39,043,529
<p>The <code>traceback.format_exception_only</code> function format only one line, except in case of <strong>SyntaxError</strong>, so…</p>
0
2016-08-19T16:10:23Z
[ "python", "traceback" ]
traceback shows only one line of a multiline command
39,043,353
<p>I have added a small debugging aid to my server. It logs a stack trace obtained from <code>traceback.format_stack()</code></p> <p>It contains few incomplete lines like this:</p> <pre><code>File "/home/...../base/loop.py", line 361, in run self.outputs.fd_list, (), sleep) </code></pre> <p>which is not that muc...
2
2016-08-19T15:59:34Z
39,043,790
<p>"just with adequate effort" this can be done. But it's hack-like</p> <p>check this example:</p> <pre><code>import traceback,re,os,sys r = re.compile(r'File\s"(.*)",\sline\s(\d+)') def print_trace(): # discard the 2 deepest entries since they're a call to print_trace() lines = [str.split(x,"\n")[0] for x ...
1
2016-08-19T16:26:42Z
[ "python", "traceback" ]
A Python package using caching
39,043,417
<p>It is possible to use the built-in <code>pkgutil</code> package to use its <code>pkgutil.get_data</code> to get data packaged with the package.</p> <p>My case is a bit different.</p> <p>I would like to allow a platform-independent way to allow storing of data done by my package, but not actually distribute anythin...
0
2016-08-19T16:03:06Z
39,043,797
<p>The built in <code>tempfile</code> module will help you here. </p> <pre><code>import tempfile with tempfile.NamedTemporaryFile(delete=False) as cache_path_fh: &lt;do stuff&gt; </code></pre> <p>Deletion/cleanup will have to be done manually with <code>delete=False</code> since you want the file to persist beyon...
0
2016-08-19T16:27:12Z
[ "python", "caching", "package" ]
Parse JSON from HTML responseText
39,043,468
<p>Python's webob module by default returns text/html responses, specifically ServerErorr's and these end up embedding the error JSON Paylod within the body of the HTML responseText contains the following:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;503 Service Unavailable&lt;/title&gt; &lt;/head&gt; &lt;b...
0
2016-08-19T16:06:17Z
39,043,765
<p>Using a RegEx to parse (not really reliable but efficient)  import re import json</p> <pre><code>content = """\ &lt;html&gt; &lt;head&gt; &lt;title&gt;503 Service Unavailable&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;503 Service Unavailable&lt;/h1&gt; { "status": "object-specific error", "pa...
-1
2016-08-19T16:24:54Z
[ "javascript", "python", "html", "json", "parsing" ]
Parse JSON from HTML responseText
39,043,468
<p>Python's webob module by default returns text/html responses, specifically ServerErorr's and these end up embedding the error JSON Paylod within the body of the HTML responseText contains the following:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;503 Service Unavailable&lt;/title&gt; &lt;/head&gt; &lt;b...
0
2016-08-19T16:06:17Z
39,229,423
<p>So I agree in general that, the better solution is to ensure the server returns only JSON, however a quick means of achieving this via Javascript on the client side as @Barmer suggested, Parse the html to the DOM, get the text childNode inside body and run JSONParse on it.</p> <pre><code>var responseStr = '&lt;html...
0
2016-08-30T13:52:57Z
[ "javascript", "python", "html", "json", "parsing" ]
Python, regex dynamic count
39,043,494
<p>So far I have this code: </p> <pre><code>def find_words(m_count, m_string): m_list = re.findall(r'\w{6,}', m_string) return m_list </code></pre> <p>is there a way to use <code>m_count</code> instead of using the count number (6) explicitly??</p>
1
2016-08-19T16:07:48Z
39,043,542
<p>You can build a regex by concatenating your count variable and static part like this:</p> <pre><code>&gt;&gt;&gt; m_count = 6 &gt;&gt;&gt; re.findall(r'\w{' + str(m_count) + ',}', 'abcdefg 1234 124xyz') ['abcdefg', '124xyz'] </code></pre>
1
2016-08-19T16:11:09Z
[ "python", "regex" ]
Python, regex dynamic count
39,043,494
<p>So far I have this code: </p> <pre><code>def find_words(m_count, m_string): m_list = re.findall(r'\w{6,}', m_string) return m_list </code></pre> <p>is there a way to use <code>m_count</code> instead of using the count number (6) explicitly??</p>
1
2016-08-19T16:07:48Z
39,043,594
<p>You can use <a href="https://docs.python.org/3/library/stdtypes.html#str.format" rel="nofollow"><code>format()</code></a>, and <a href="https://docs.python.org/3/library/string.html#format-string-syntax" rel="nofollow"><em>escape</em></a> the curly braces.</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; m_count ...
1
2016-08-19T16:15:09Z
[ "python", "regex" ]
Python, regex dynamic count
39,043,494
<p>So far I have this code: </p> <pre><code>def find_words(m_count, m_string): m_list = re.findall(r'\w{6,}', m_string) return m_list </code></pre> <p>is there a way to use <code>m_count</code> instead of using the count number (6) explicitly??</p>
1
2016-08-19T16:07:48Z
39,043,615
<p>Convert the int to string and added to you reg exp like this:</p> <pre><code>def find_words(m_count, m_string): m_list = re.findall(r'\w{'+str(m_count)+',}', m_string) return m_list </code></pre>
2
2016-08-19T16:16:36Z
[ "python", "regex" ]
Pyserial - Python creating byte array
39,043,536
<p>I have the following data</p> <p>a1 = 0x5A -- hex</p> <p>a2 = 0x01 -- hex</p> <p>a3 = 12 -- decimal</p> <p>a4 = 28 -- decimal</p> <p>a5 = sum of (a1 to a4)</p> <p>I should be able to send all this information in a byte array and send using ser.write command in one go. </p> <p>Currently I am manually convert...
0
2016-08-19T16:10:53Z
39,043,632
<p>Do you want a string of hex values? Not sure to understand.</p> <pre><code>a1 = 0x5A # hex a2 = 0x01 # hex a3 = 12 # decimal a4 = 28 # decimal a5 = sum((a1, a2, a3, a4)) int_array = [a1, a2, a3, a4, a5] print(int_array) hex_array = "".join(map(hex, int_array)) print(hex_array) </code></pre> <p>You'll get:</p> <...
2
2016-08-19T16:17:52Z
[ "python", "pyserial" ]
Combinations of restricted set of integers
39,043,552
<p>How to generate the list of combinations with <code>allowed_ints</code> that sums to <code>goal</code> ?</p> <p>Examples: </p> <pre><code>allowed_ints=[1,2], goal=4 combinations = [[1,1,1,1],[1,1,2],[2,1,1],[2,2],[1,2,1]] allowed_ints=[5, 6], goal=13 combinations = [] </code></pre> <p>What I've made so far don'...
-1
2016-08-19T16:11:43Z
39,043,732
<p>You should include 3 conditions like</p> <p>goal == 0 then recursion worked</p> <p>goal &lt; 0 then recursion failed</p> <p>goal >= 0 and list elements end then recursion failed</p> <p>By the way you can do it all using recursion. No need of loop, recursion can also do loop</p>
-1
2016-08-19T16:23:01Z
[ "python", "combinations" ]
Combinations of restricted set of integers
39,043,552
<p>How to generate the list of combinations with <code>allowed_ints</code> that sums to <code>goal</code> ?</p> <p>Examples: </p> <pre><code>allowed_ints=[1,2], goal=4 combinations = [[1,1,1,1],[1,1,2],[2,1,1],[2,2],[1,2,1]] allowed_ints=[5, 6], goal=13 combinations = [] </code></pre> <p>What I've made so far don'...
-1
2016-08-19T16:11:43Z
39,044,129
<p>Using you function try this:</p> <pre><code>def combinations(allowed_ints, goal): if goal &gt; 0: for i in allowed_ints: for p in combinations(allowed_ints, goal-i): if sum([i] + p) == goal: yield [i] + p else: yield [] print list(combinations...
1
2016-08-19T16:47:41Z
[ "python", "combinations" ]
Combinations of restricted set of integers
39,043,552
<p>How to generate the list of combinations with <code>allowed_ints</code> that sums to <code>goal</code> ?</p> <p>Examples: </p> <pre><code>allowed_ints=[1,2], goal=4 combinations = [[1,1,1,1],[1,1,2],[2,1,1],[2,2],[1,2,1]] allowed_ints=[5, 6], goal=13 combinations = [] </code></pre> <p>What I've made so far don'...
-1
2016-08-19T16:11:43Z
39,044,588
<p>I know you've already selected an answer, but I wanted to offer an alternative that's not as similar to your code. If you wanted to use recursion, I would suggest something like this:</p> <pre><code>def combinations(allowed_ints, list, goal): # base case: you're done if sum(list) == goal: print list...
0
2016-08-19T17:18:29Z
[ "python", "combinations" ]
Tweepy twitter bot replies to new requests
39,043,601
<p>I'm looking for a way to stop my Twitter bot, <a href="https://twitter.com/1happybot" rel="nofollow">HappyBot</a>, from replying to each user who has tweeted at it, and instead to only reply to new tweets since the last time the code was run. For example, if I tweeted the bot at 13:00 it would reply at 13:00 but if ...
0
2016-08-19T16:15:39Z
39,043,956
<p>Which library are you using? My best guess is that whatever it is you are using will expose the JSON response that twitter returns. In this case you could try retrieving the creation date of the tweet. See <a href="https://dev.twitter.com/rest/reference/get/search/tweets" rel="nofollow">https://dev.twitter.com/rest/...
0
2016-08-19T16:37:44Z
[ "python", "twitter", "tweepy" ]
Tweepy twitter bot replies to new requests
39,043,601
<p>I'm looking for a way to stop my Twitter bot, <a href="https://twitter.com/1happybot" rel="nofollow">HappyBot</a>, from replying to each user who has tweeted at it, and instead to only reply to new tweets since the last time the code was run. For example, if I tweeted the bot at 13:00 it would reply at 13:00 but if ...
0
2016-08-19T16:15:39Z
39,046,814
<p>The solution I offer here is quick &amp; dirty, but it should work. Basically, it stores the value of the last tweet you replied to in a text file to ensure persistence when your code stops, and reloads it when your code is called. With the "since" option, it will only look for tweets older than those you have alrea...
0
2016-08-19T19:56:35Z
[ "python", "twitter", "tweepy" ]
python - different array length along interpolation axis?
39,043,621
<p>I am trying to use the Python interpolation function to get the value y for a given x but I am getting the error "raise ValueError("x and y arrays must be equal in length along along interpolation axis" even though my arrays have both equal size and shape (according to what I get when I use .shape in my code). I am ...
0
2016-08-19T16:17:02Z
39,043,841
<p>After adding in the required imports, I've been unable to duplicate your error with version 2.7.12. What python version are you running? </p> <pre><code>import numpy as np from scipy.interpolate import interp1d s = [] def slowroll(y, t): phi, dphi, a = y h = np.sqrt(1/3. * (1/2. * dphi**2 + 1/2.*phi**2))...
0
2016-08-19T16:30:24Z
[ "python", "arrays", "scipy", "interpolation", "odeint" ]
python - different array length along interpolation axis?
39,043,621
<p>I am trying to use the Python interpolation function to get the value y for a given x but I am getting the error "raise ValueError("x and y arrays must be equal in length along along interpolation axis" even though my arrays have both equal size and shape (according to what I get when I use .shape in my code). I am ...
0
2016-08-19T16:17:02Z
39,046,554
<p>It's Friday, I'm about to leave work, and I can't figure it out</p> <p><a href="http://i.stack.imgur.com/MvwWw.png" rel="nofollow"><img src="http://i.stack.imgur.com/MvwWw.png" alt="enter image description here"></a></p> <p>mods feel free to flag/delete post, I know it's not that productive...</p>
0
2016-08-19T19:39:21Z
[ "python", "arrays", "scipy", "interpolation", "odeint" ]