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
Python regex is having problems finding a special unicode character
37,491,414
<p>I am currently parsing through some old exams to determine the frequency of the questions (because many questions would resurface at this years exam). I am using pyperclip to get the input for the re.findall.</p> <p>This is the regex I am using: <code>pattern = re.compile(ur'\d.[a-zA-Z .,\']+\?', re.UNICODE)</code>...
1
2016-05-27T20:00:55Z
37,491,629
<p>You can use the <code>\u</code> representation of the apostrophe, which is <code>\u2019</code>.</p> <p>Also, the dot should be escaped to match a literal dot symbol.</p> <p>Use</p> <pre><code>ur'\d\.[a-zA-Z .,\'\u2019]+\?' ^^ ^^^^^^ </code></pre> <p>When in doubt what the hex representation a s...
1
2016-05-27T20:18:16Z
[ "python", "regex", "python-2.7", "python-unicode" ]
saving the column names of a sql table as a list using pyodbc
37,491,416
<p>I need the names of columns of the sql table in a list to be used in another complex python code Tried some of the hacks show in some older SO posts:</p> <pre><code>db_columns = cursor.columns(table='result', schema='dbo').fetchall() [(u'Basis', u'dbo', u'result', u'TXN_KEY', -5, u'bigint identity', 19, 8, 0, 10...
1
2016-05-27T20:00:56Z
37,491,799
<p><code>SELECT</code> like this?</p> <pre><code>SELECT COLUMN_NAME,* FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA='dbo' and TABLE_NAME = 'YourTableName' </code></pre>
2
2016-05-27T20:31:45Z
[ "python", "sql-server", "pyodbc" ]
How to determine type from type aliasing?
37,491,421
<p>After I declare an alias <code>t1 = typing.List[int]</code> or <code>t2=typing.List[double]</code>, how do I determine from<code>t1</code> that it is a <code>List[int]</code> and from <code>t2</code> that it is a <code>List[double]</code>? Are there some hidden attributes or functions of <code>t1</code> and <code>t2...
2
2016-05-27T20:01:09Z
37,491,559
<p>Interactively, your most useful option is probably</p> <pre><code>&gt;&gt;&gt; t1 typing.List[int] </code></pre> <p>If you want to inspect it in a program, you can look at things like <code>__name__</code>, <code>__parameters__</code>, or whether <code>issubclass</code> reports it as a subclass of <code>typing.Lis...
3
2016-05-27T20:12:35Z
[ "python", "python-3.x", "type-hinting" ]
python: Replace/substitute all whole-word match in a string
37,491,439
<p>Let's suppose that my string is <code>"#big and #small, #big-red, #big-red-car and #big"</code></p> <p>How can I use <code>re.sub(), re.match(), etc.</code> to replace one tag with a word?</p> <p>For example, all <code>#big</code>s must be changed to BIG, but <code>#big-red</code> and <code>#big-red-car</code> sho...
3
2016-05-27T20:02:39Z
37,491,653
<p>Let's define your string:</p> <pre><code>&gt;&gt;&gt; s = "#big and #small, #big-red, #big-red-car and #big" </code></pre> <p>Now, let's do your replacements:</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; re.sub(r'#big([.,\s]|$)', r'#BIG\1', s) '#BIG and #small, #big-red, #big-red-car and #BIG' </code></pre>...
6
2016-05-27T20:20:27Z
[ "python", "regex", "django", "string" ]
python: Replace/substitute all whole-word match in a string
37,491,439
<p>Let's suppose that my string is <code>"#big and #small, #big-red, #big-red-car and #big"</code></p> <p>How can I use <code>re.sub(), re.match(), etc.</code> to replace one tag with a word?</p> <p>For example, all <code>#big</code>s must be changed to BIG, but <code>#big-red</code> and <code>#big-red-car</code> sho...
3
2016-05-27T20:02:39Z
37,491,740
<p>This info is a category of one-directional boundary tricks. </p> <p>Using a <em>Negative</em> look behind/ahead assertion(s),<br> within the particular direction, it will let BEGIN/END of string match,<br> yet not allow others to match. </p> <p>This leads to some interesting scenarios of combining<br> negative c...
3
2016-05-27T20:27:19Z
[ "python", "regex", "django", "string" ]
Multiprocessing in pandas
37,491,486
<p>Is it possible to partition a pandas dataframe to do multiprocessing?</p> <p>Specifically, my DataFrames are simply too big and take several minutes to run even one transformation on a single processor.</p> <p>I know, I could do this in Spark but a lot of code has already been written, so preferably I would like t...
2
2016-05-27T20:06:31Z
38,886,113
<p>Slightly modifying <a href="http://stackoverflow.com/a/29281494/5351271">http://stackoverflow.com/a/29281494/5351271</a> I could get a solution to work over rows.</p> <pre><code>from multiprocessing import Pool, cpu_count def applyParallel(dfGrouped, func): with Pool(cpu_count()) as p: ret_list = p.map...
0
2016-08-11T01:55:35Z
[ "python", "pandas", "dataframe", "parallel-processing", "multiprocessing" ]
Python regex to match and remove the indels in pileup format
37,491,704
<p>My question is similar to the following post but I need this python:</p> <p><a href="http://stackoverflow.com/questions/37206608/mpileup-regex-command-to-remove-indels#new-answer">Mpileup regex command to remove indels</a></p> <p>INPUT: chr8 30 T 6 ...,$.$.$A,..A...,,,.,,...+5AGGC...-8GTCGG......,a,^F,...
1
2016-05-27T20:24:14Z
37,492,127
<p>This one worked finally</p> <p>sequence = re.sub("+\d+[ACGT]+", "", sequence)</p> <p>sequence = re.sub("-\d+[ACGT]+", "", sequence)</p> <p>Might be helpful for someone who is looking for regex to remove indels from their pileup file.</p>
1
2016-05-27T20:56:13Z
[ "python", "regex" ]
Converting a numpy.ndarray value from bytes to float
37,491,830
<p>I'm using numpy and Python 3.4 to read data from a .csv file.</p> <p>Here is a sample of the CSV file:</p> <pre><code>"05/27/2016 09:45:37.816","187666432","7921470.8554087048","0","95.202655176457412","82.717061054954783","1.4626657999999999","158","5" "05/27/2016 09:45:38.819","206884864","10692185.668858336","0...
1
2016-05-27T20:33:48Z
37,491,929
<p>To answer the first question:</p> <p>I strongly recommend using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow">pandas to read in csv files</a>:</p> <pre><code>In [11]: pd.read_csv(path, header=None) Out[11]: 0 1 2 3...
2
2016-05-27T20:41:21Z
[ "python", "python-3.x", "numpy", "python-3.4" ]
Passing a list of arguments into a class
37,491,838
<p>I am creating a class called <code>Triangle</code>. Within <code>Triangle</code>, it is passed <code>three_points</code> list and <code>two_angles</code> list (i.e. <code>self.triangle0 = Triangle([1, 2, 3], [20, 30])</code>)</p> <p>I am defining </p> <pre><code>class Triangle(object): def __init__(self, thre...
-1
2016-05-27T20:34:13Z
37,491,922
<p>This will work how you have it mocked up. At runtime self.points will be a list containing whatever values you passed in. Same with self.angels. Note that if your list contains objects and not just primitives you may be passing in a pointer in your list and not the actual object.</p>
0
2016-05-27T20:40:45Z
[ "python", "list", "class", "init" ]
BeautifulSoup, what order does .descendants go in?
37,491,970
<p>When using the beautifulsoup <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#descendants" rel="nofollow">soup.descendants</a> iterator, are the tags yielded guaranteed to come back in any particular order? Since the documentation mentions that things are iterated over recursively, I'd guess that thin...
1
2016-05-27T20:44:20Z
37,492,084
<p><a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#descendants" rel="nofollow">The documentation</a> does not promise anything, but <a href="http://bazaar.launchpad.net/~leonardr/beautifulsoup/bs4/view/head:/bs4/element.py#L1269" rel="nofollow">the source</a> reveals all. <code>.descendants</code> yield...
2
2016-05-27T20:53:02Z
[ "python", "beautifulsoup" ]
Ansible ec2_fact documentation
37,491,985
<p>I have searched far and wide to try and find some decent documentation relating to Ansible's <code>ec2_facts</code> module, specifically related to the variables which are created by this module. However, I can't seem to find anything. It looks like there is are variables called <code>ansible_ec2_instance_id</code> ...
1
2016-05-27T20:45:31Z
37,492,527
<p>Have a look at <a href="http://docs.ansible.com/ansible/ec2_module.html" rel="nofollow">this documentaion</a> and bear in mind that all variables will be created with the <code>ansible_ec2_</code> prefix.</p> <p>I.e.:</p> <p><code>instance_id</code> --> <code>ansible_ec2_instance_id</code></p>
1
2016-05-27T21:31:41Z
[ "python", "amazon-ec2", "ansible" ]
Ansible ec2_fact documentation
37,491,985
<p>I have searched far and wide to try and find some decent documentation relating to Ansible's <code>ec2_facts</code> module, specifically related to the variables which are created by this module. However, I can't seem to find anything. It looks like there is are variables called <code>ansible_ec2_instance_id</code> ...
1
2016-05-27T20:45:31Z
37,498,727
<p>That might help you.</p> <pre><code>- hosts: ec2 gather_facts: yes connection: local vars: - region: 'us-west-2' tasks: - name: Gather EC2 facts local_action: ec2_facts register: ec2facts - debug: msg: "{{ ec2facts }} </code></pre>
0
2016-05-28T12:01:10Z
[ "python", "amazon-ec2", "ansible" ]
mutliple entry widgets and one button widget in tkinter
37,491,992
<p>I am trying to make two entry boxes and an 'OK' button that processes both entries: I don't understand the <strong>init</strong>() function or the reason 'self' has to be include in doing this. I want to access the entries outside this class and mainloop. The entries should be string type. </p> <pre><code>from ...
-1
2016-05-27T20:45:51Z
37,492,107
<p>Your approach is fundamentally flawed. <code>mainloop()</code> does what it says: starts a loop. The lines that follow it will not be executed until that loop is over - meaning, until your application has closed. Since you already have a class with Tkinter stuff in it, just finish the move to an OO approach:</p> <p...
0
2016-05-27T20:54:16Z
[ "python", "class", "tkinter", "init", "self" ]
mutliple entry widgets and one button widget in tkinter
37,491,992
<p>I am trying to make two entry boxes and an 'OK' button that processes both entries: I don't understand the <strong>init</strong>() function or the reason 'self' has to be include in doing this. I want to access the entries outside this class and mainloop. The entries should be string type. </p> <pre><code>from ...
-1
2016-05-27T20:45:51Z
37,492,807
<p>Here's a quick fix. </p> <p>The problem with both your version and TigerhawkT3's modified version is that when you close the window the <code>Entry</code> widgets are no longer valid, so you need to save the data before closing the window. One way to do that is to attach Tkinter <code>StringVar</code>s to the <code...
0
2016-05-27T21:55:33Z
[ "python", "class", "tkinter", "init", "self" ]
mutliple entry widgets and one button widget in tkinter
37,491,992
<p>I am trying to make two entry boxes and an 'OK' button that processes both entries: I don't understand the <strong>init</strong>() function or the reason 'self' has to be include in doing this. I want to access the entries outside this class and mainloop. The entries should be string type. </p> <pre><code>from ...
-1
2016-05-27T20:45:51Z
37,492,813
<p>The problem is that <code>mainloop</code> doesn't exit until the root window is destroyed. Once the root window is destroyed you can no longer access the widgets inside the root window. You can, however, access non-widget attributes of the object.</p> <p>If that is what you want -- to destroy the window and have ac...
1
2016-05-27T21:56:02Z
[ "python", "class", "tkinter", "init", "self" ]
Python Matplotlib Specific Figure Generation Works on One PC but Not Other
37,492,006
<p>I have the following code:</p> <pre><code>x = Firstyr_df['FIRST_YEAR_TOTAL'][Firstyr_df['FIRST_YEAR_TOTAL'] &gt; 0] y = Secondyr_df['SECOND_YEAR_TOTAL'][Secondyr_df['SECOND_YEAR_TOTAL'] &gt; 0] z = Thirdyr_df['THIRD_YEAR_TOTAL'][Thirdyr_df['THIRD_YEAR_TOTAL'] &gt; 0] bins = np.linspace(0, 10000, 1000) plt.hist(x, ...
0
2016-05-27T20:46:27Z
37,494,268
<p>Yes. It was a version problem. The machine not rendering the histograms was an older version. Sorry to waste your time.</p>
0
2016-05-28T01:08:41Z
[ "python", "python-2.7", "matplotlib" ]
PyQt: Widget constantly moving to position (0, 0)
37,492,029
<p>I have made a PyQt app with event filter that makes a widget follow mouse movement, It follows the mouse movement and sometimes goes back to position <code>0, 0</code>...</p> <pre><code>import sys from PyQt4 import QtGui, QtCore import resources class Window(QtGui.QMainWindow): def __init__(self): Qt...
0
2016-05-27T20:48:13Z
37,497,745
<p>A few things</p> <p>You shouldn't have to call <code>timer.start()</code> more than once. Once the timer begins, it's going to continue triggering every 5 milliseconds until you call <code>timer.stop()</code>.</p> <p>The coordinate system for the <code>Window</code> and the button aren't the same. Coordinates ar...
0
2016-05-28T10:13:30Z
[ "python", "pyqt", "pyqt4" ]
How to match elements of two arrays and return a value
37,492,032
<p>I'm looking for help to improve my code. I have two arrays of different sizes and I'm assigning a value from one array to the index of another. eg</p> <pre><code>a = np.array([[1,5],[2,8],[3,2],[4,6]]) b = np.array([[1],[1],[2],[4],[4],[2],[3],[2],[3]]) </code></pre> <p>i'm mathching the items in the first columns...
2
2016-05-27T20:48:19Z
37,492,313
<p>Is <code>a</code> always of the format <code>[[1, ...], [2, ...], [3, ...], ...]</code>?</p> <p>If it is, then you can save time by not iterating through <code>a</code> but instead just indexing into it. For example:</p> <pre><code>a = np.array([[1,5],[2,8],[3,2],[4,6]]) b = np.array([[1],[1],[2],[4],[4],[2],[3],[...
1
2016-05-27T21:10:45Z
[ "python", "arrays" ]
Multiple possible options with an if statement in .split()
37,492,074
<p>Sorry for the poor explanation in the question, but here's my code:</p> <pre><code>import csv file = open("problems_solutions.csv","a+") name = input("What is your name?") file.write(name+",") problem = input("Enter the problem that you have with your mobile phone.").lower() file.write(problem+"\n") file.close() <...
1
2016-05-27T20:52:19Z
37,492,148
<p>I believe the problem is that you are looking for an array in an array... but I think you want to look for a string in the array?</p> <p>This seemed to work for me:</p> <pre><code>problem = "My sound isn't working" for i in ["sound","speaker","volume","audio","earphone","earphones","headphones","headphone"]: if ...
0
2016-05-27T20:57:57Z
[ "python", "python-3.x" ]
Multiple possible options with an if statement in .split()
37,492,074
<p>Sorry for the poor explanation in the question, but here's my code:</p> <pre><code>import csv file = open("problems_solutions.csv","a+") name = input("What is your name?") file.write(name+",") problem = input("Enter the problem that you have with your mobile phone.").lower() file.write(problem+"\n") file.close() <...
1
2016-05-27T20:52:19Z
37,492,155
<p>As currently stated, you ask if whole list is found in another list. Check would be true if <code>problem.split()</code> would be equal to something like <code>[["battery","charge","charged","low"], 'some', 'other', 1, 'values']</code> (obviously it'll never be).</p> <p>To do check you want, you may use <a href="ht...
0
2016-05-27T20:58:29Z
[ "python", "python-3.x" ]
Multiple possible options with an if statement in .split()
37,492,074
<p>Sorry for the poor explanation in the question, but here's my code:</p> <pre><code>import csv file = open("problems_solutions.csv","a+") name = input("What is your name?") file.write(name+",") problem = input("Enter the problem that you have with your mobile phone.").lower() file.write(problem+"\n") file.close() <...
1
2016-05-27T20:52:19Z
37,492,168
<p>You are currently looking for a <code>list</code> within a <code>list</code>. This only looks for literal objects. <code>[1, 2]</code> would be in <code>[3, [1, 2], 9]</code>, but not in <code>[1, 2, 3]</code>. The actual concept you are looking for is a set intersection:</p> <pre><code>&gt;&gt;&gt; problems = {"ba...
1
2016-05-27T20:59:14Z
[ "python", "python-3.x" ]
Multiple possible options with an if statement in .split()
37,492,074
<p>Sorry for the poor explanation in the question, but here's my code:</p> <pre><code>import csv file = open("problems_solutions.csv","a+") name = input("What is your name?") file.write(name+",") problem = input("Enter the problem that you have with your mobile phone.").lower() file.write(problem+"\n") file.close() <...
1
2016-05-27T20:52:19Z
37,492,171
<p>Your syntax is incorrect. Try this -</p> <pre><code>arr1 = ["sound", "speaker", "volume", "audio", "earphone", "earphones", "headphones", "headphone"] arr2 = ["battery", "charge", "charged", "low"] problem = "my battery is not working" if any(keyword in problem.split() for keyword in arr1): print('Pr...
0
2016-05-27T20:59:26Z
[ "python", "python-3.x" ]
Multiple possible options with an if statement in .split()
37,492,074
<p>Sorry for the poor explanation in the question, but here's my code:</p> <pre><code>import csv file = open("problems_solutions.csv","a+") name = input("What is your name?") file.write(name+",") problem = input("Enter the problem that you have with your mobile phone.").lower() file.write(problem+"\n") file.close() <...
1
2016-05-27T20:52:19Z
37,492,208
<p>So you have 2 arrays here, the one with the list of words and the one with the words in the user's problem. You're asking python if your first array is in the second array, which it isn't. Instead, you should iterate through the words and check each to see if it's in the problem.</p> <pre><code>matching_words = ["s...
0
2016-05-27T21:03:01Z
[ "python", "python-3.x" ]
Multiple possible options with an if statement in .split()
37,492,074
<p>Sorry for the poor explanation in the question, but here's my code:</p> <pre><code>import csv file = open("problems_solutions.csv","a+") name = input("What is your name?") file.write(name+",") problem = input("Enter the problem that you have with your mobile phone.").lower() file.write(problem+"\n") file.close() <...
1
2016-05-27T20:52:19Z
37,492,306
<p>Like TigerhawkT3 already wrote, you can work with sets. In my opinion this is a very smart way to solve your issue.</p> <p>Here some example operations:</p> <pre><code>a = set(["sound","speaker","volume","audio","earphone","earphones","headphones","headphone"]) b = set("My sound isn't working".split()) &gt;&gt;&...
-2
2016-05-27T21:09:52Z
[ "python", "python-3.x" ]
loss of precision when using pandas to read excel
37,492,173
<p>I tried to use pandas to read an excel sheet into a dataframe but for floating point columns, the data is read incorrectly. I use the function read_excel() to do the task</p> <p>In excel, the value is 225789.479905466 while in the dataframe, the value is 225789.47990546614 which creates discrepancy for me to import...
1
2016-05-27T20:59:31Z
37,493,209
<p>I believe this is just floating point error and/or the default Excel view not showing you the full precision of the number.</p> <p>Also consider the following:</p> <pre><code>from decimal import Decimal x = Decimal(225789.479905466) y = Decimal(225789.47990546614) print(abs(x - y)/y) 6.44490400281690193351256365...
0
2016-05-27T22:36:29Z
[ "python", "excel", "pandas", "dataframe", "precision" ]
loss of precision when using pandas to read excel
37,492,173
<p>I tried to use pandas to read an excel sheet into a dataframe but for floating point columns, the data is read incorrectly. I use the function read_excel() to do the task</p> <p>In excel, the value is 225789.479905466 while in the dataframe, the value is 225789.47990546614 which creates discrepancy for me to import...
1
2016-05-27T20:59:31Z
37,596,921
<p>Excel might be truncating your values, not pandas. If you export to .csv from Excel and are careful about how you do it, you should then be able to read with <code>pandas.read_csv</code> and maintain all of your data. <code>pandas.read_csv</code> also has an undocumented <code>float_precision</code> kwarg, that migh...
0
2016-06-02T16:05:40Z
[ "python", "excel", "pandas", "dataframe", "precision" ]
Regex into variables
37,492,177
<p>I use a <a href="http://regex101.com#python" rel="nofollow">regex101.com#python</a> and here are my strings:</p> <p>Regular Expression:</p> <pre><code>.* src=.(?&lt;Pvar1&gt;\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}).* dst=.(?&lt;Pvar2&gt;\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}) </code></pre> <p>Test String:</p> <pre><code>k=5782...
0
2016-05-27T21:00:10Z
37,492,274
<p>Capture groups are accessed using the <code>group()</code> method of the <code>Match</code> object that <code>re.match</code> returns. If you use normal capture groups, the argument is the group number; if you use named capture groups the argument is the name.</p> <pre><code>str = 'k=57829.57892gfjhfg.tur90eunn 453...
4
2016-05-27T21:08:00Z
[ "python", "regex" ]
Regex into variables
37,492,177
<p>I use a <a href="http://regex101.com#python" rel="nofollow">regex101.com#python</a> and here are my strings:</p> <p>Regular Expression:</p> <pre><code>.* src=.(?&lt;Pvar1&gt;\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}).* dst=.(?&lt;Pvar2&gt;\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}) </code></pre> <p>Test String:</p> <pre><code>k=5782...
0
2016-05-27T21:00:10Z
37,492,278
<p>I would do something like this.</p> <pre><code>import re string = 'k=57829.57892gfjhfg.tur90eunn 4538.333.3 user="JHenry" src="10.10.1.21" dst="10.10.20.42" ttubbies="yellow"]' results = re.match(".* src=.(\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}).* dst=.(\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3})", string) print results.group(1) pri...
0
2016-05-27T21:08:21Z
[ "python", "regex" ]
python plot distribution across mean
37,492,239
<p>I have 500 simulation for each day in 2015. So, my data looks as:</p> <pre><code>from datetime import date, timedelta as td, datetime d1 = datetime.strptime('1/1/2015', "%m/%d/%Y") d2 = datetime.strptime('12/31/2015', "%m/%d/%Y") AllDays = [] while(d1&lt;=d2): AllDays.append(d1) d1 = d1 + td(days=1) </code...
1
2016-05-27T21:04:55Z
37,492,464
<p>As Andy Hayden already suggested, pandas could be a very good option here:</p> <pre><code>from datetime import date, timedelta as td, datetime d1 = datetime.strptime('1/1/2015', "%m/%d/%Y") d2 = datetime.strptime('12/31/2015', "%m/%d/%Y") AllDays = [] while(d1&lt;=d2): AllDays.append(d1) d1 = d1 + td(days=...
2
2016-05-27T21:26:27Z
[ "python", "datetime", "numpy", "plot" ]
python plot distribution across mean
37,492,239
<p>I have 500 simulation for each day in 2015. So, my data looks as:</p> <pre><code>from datetime import date, timedelta as td, datetime d1 = datetime.strptime('1/1/2015', "%m/%d/%Y") d2 = datetime.strptime('12/31/2015', "%m/%d/%Y") AllDays = [] while(d1&lt;=d2): AllDays.append(d1) d1 = d1 + td(days=1) </code...
1
2016-05-27T21:04:55Z
37,492,475
<p>using <code>matplotlib.pyplot</code> you can chart the mean, mean + 1 std, and mean - 1 std.</p> <pre><code>my_array = np.random.rand(500, len(AllDays)) import matplotlib.pyplot as plt fig, ax = plt.subplots(1, 1) ax.plot(AllDays, my_array.mean(axis=0)) ax.plot(AllDays, my_array.mean(axis=0) + my_array.std(axis=0...
1
2016-05-27T21:27:04Z
[ "python", "datetime", "numpy", "plot" ]
python plot distribution across mean
37,492,239
<p>I have 500 simulation for each day in 2015. So, my data looks as:</p> <pre><code>from datetime import date, timedelta as td, datetime d1 = datetime.strptime('1/1/2015', "%m/%d/%Y") d2 = datetime.strptime('12/31/2015', "%m/%d/%Y") AllDays = [] while(d1&lt;=d2): AllDays.append(d1) d1 = d1 + td(days=1) </code...
1
2016-05-27T21:04:55Z
37,492,611
<p>Two already good posts above, but here is a pandas example.</p> <pre><code>import numpy as np import matplotlib.pyplot as plt plt.style.use("ggplot") import pandas as pd cols = pd.date_range(start = '2015-01-01', end = '2015-12-31') df = pd.DataFrame(data = np.random.randn(500, 365), columns = cols) means = ...
2
2016-05-27T21:38:58Z
[ "python", "datetime", "numpy", "plot" ]
python plot distribution across mean
37,492,239
<p>I have 500 simulation for each day in 2015. So, my data looks as:</p> <pre><code>from datetime import date, timedelta as td, datetime d1 = datetime.strptime('1/1/2015', "%m/%d/%Y") d2 = datetime.strptime('12/31/2015', "%m/%d/%Y") AllDays = [] while(d1&lt;=d2): AllDays.append(d1) d1 = d1 + td(days=1) </code...
1
2016-05-27T21:04:55Z
37,493,051
<p>I was fascinated by this question. Here's what I came up with. It's a work in progress.</p> <pre><code>from datetime import date, timedelta as td, datetime import matplotlib.pyplot as plt import scipy as sp import numpy as np d1 = datetime.strptime('1/1/2015', "%m/%d/%Y") d2 = datetime.strptime('12/31/2015', "%m...
1
2016-05-27T22:18:56Z
[ "python", "datetime", "numpy", "plot" ]
Python: SerialException: Attempting to use a port that is not open
37,492,319
<p>I am using below python code to communicate with XBee+Arduino from my MAC+XBee coordinator. But I am getting port not open error while trying to send the packet through serial. </p> <p>Error message</p> <pre><code>Sending LOAD Traceback (most recent call last):   File "xbeeTxRx.py", line 139, in &lt;module&gt;  ...
0
2016-05-27T21:10:56Z
37,635,661
<p>Dude you should put <code>zb.halt()</code> and <code>see.close()</code> after the last if statement where you call your main.</p>
0
2016-06-04T22:31:30Z
[ "python", "serial-port", "xbee" ]
using foreachRDD and foreach to iterate over an rdd in pyspark
37,492,402
<p>Questions for Spark 1.6.1, pyspark</p> <p>I have streaming data coming in as like</p> <pre><code>{"event":4,"Userid":12345,"time":123456789,"device_model":"iPhone OS", "some_other_property": "value", "row_key": 555} </code></pre> <p>I have a function that writes to HBase called writeToHBase(rdd), expecting an rdd...
0
2016-05-27T21:19:31Z
37,495,794
<p>why do you want to iterate over rdd while your writeToHBase function expects a rdd as arguement. Simply call <code>writeToHBase(rdd)</code> in your process function, that's it.</p> <p>If you need to fetch every record from the rdd you can call </p> <pre><code>def processRecord(record): print(record) rdd...
1
2016-05-28T06:05:02Z
[ "python", "apache-spark", "pyspark" ]
Non-canonical ordering on a Python list comprehension output array
37,492,440
<p>I'm trying to get an array in Python 3.5.x to sort some objects by the order a key attribute appears in another array. This is to say: I have an array X of objects x0, ... , xN with key attribute name. I also have an array of names Y with names n0, ... , nk with k&lt;= N. I wish to do the list comprehension</p> <p...
0
2016-05-27T21:23:52Z
37,492,480
<p>So ... I'm not sure that I completely understand the problem, but it looks like <code>Y</code> is a list of names. You'll do better if you turn it into a dict which maps the name to the index:</p> <pre><code>Y_map = {name: ix for ix, name in enumerate(Y)} </code></pre> <p>Now we can use <code>Y_map</code> to filt...
2
2016-05-27T21:28:05Z
[ "python", "list-comprehension" ]
How to use WeasyPrint PDF Builder on Password Protected Pages?
37,492,485
<p>I'm trying to download a page from my Flask app using WeasyPrint but when downloading the PDF, I'm getting the login page as the PDF rather than the expected page.</p> <p>I'm using the following code:</p> <pre><code>@app.route('/report.pdf') def hello_pdf(): # Make a PDF from another view return render_pdf...
0
2016-05-27T21:28:28Z
37,496,337
<p>Turns out <code>render_template</code> just returns a html string, so I can do the following at the end of a route:</p> <pre><code>html = render_template('myprojects.html', projects=projects) return render_pdf(HTML(string=html)) </code></pre>
0
2016-05-28T07:20:13Z
[ "python", "flask", "weasyprint" ]
Timestamp YYYY-MM-DDThh:mm:ss.sssTZD in Python
37,492,554
<p>I am struggling the current UTC time into this format using Python: <code>YYYY-MM-DDThh:mm:ss.sssTZD</code> (e.g. 1997-07-16T19:20:30.000+00:00)</p>
1
2016-05-27T21:34:08Z
37,492,671
<p>Try some thing like this. With using <code>datetime</code> and <code>dateutil</code></p> <pre><code>In [1]: from dateutil.tz import tzoffset In [2]: from datetime import datetime In [3]: now = datetime.now(tzoffset('EDT', +4*60*60)) In [4]: print now.isoformat() 2016-05-28T01:43:14.702253+04:00 </code></pre> <p>Fo...
1
2016-05-27T21:44:12Z
[ "python", "python-2.7", "datetime", "datetime-format" ]
How to apply math operations to a row of a csv in python?
37,492,650
<p>I've been successful creating functions in python and reading/writing files. However, I really need to apply certain functions to whole <strong>rows</strong> of data (<strong>not columns</strong>) and can't find out anything about how to do this. The goals are:</p> <ul> <li>Read a csv or txt file into python (can...
0
2016-05-27T21:42:25Z
37,492,773
<p>you can transpose your matrix or data frame (if using pandas) and work with columns.</p> <p>Example (pandas):</p> <p>Original DF</p> <pre><code>In [162]: df Out[162]: a b c 0 0 2 1 1 0 2 2 2 0 2 3 3 0 1 0 4 0 2 0 5 0 3 0 6 1 0 0 7 2 0 0 8 3 0 0 </code></pre> <p>Transposed DF</p> ...
0
2016-05-27T21:52:42Z
[ "python", "csv", "numpy", "math", "row" ]
Python: how to extract only values from dict?
37,492,705
<p>I created a dictionary <code>d</code>, where <code>A</code> is a list containing data of a <code>class</code></p> <pre><code>class Driver(object): def __init__(self, name, raw_value, Id1): self.name = name self.raw = raw_value self.Indicator1 = Id1 d = {} for i in range(0,len(A)): i...
1
2016-05-27T21:46:47Z
37,492,887
<p>Try this:</p> <pre><code>import pandas as pd pd.concat(d[users[0]]).values </code></pre> <p>this will concatenate your list of pandas Series (or numpy arrays) into a single one and then you can apply <code>values</code> accessor in order to get a numpy array or a <code>.tolist()</code> function in order to get a ...
1
2016-05-27T22:02:51Z
[ "python", "dictionary", "pandas" ]
Python routine to abbreviate sentences?
37,492,787
<p>I am working with CSV data from Survey Monkey. The problem is that the column names they use are way too long for most database CSV data import routines. The column names are, literally, the question you asked on the survey. So it can take some time to be able to narrow that down to, say, 64 characters for a databas...
0
2016-05-27T21:53:48Z
37,493,037
<p>If you just need the headers to be unique and less than 64 (are you using postgres btw?) then just use a hash.</p> <pre><code>from hashlib import md5 columns = ['reallylongcolumname1', 'reallylongcolumname2'] out = {} for c in columns: h = md5(c).hexdigest() # Use 'h' as your new column header! out.upd...
0
2016-05-27T22:17:21Z
[ "python", "python-2.7" ]
How to reverse a single string in python
37,492,876
<p>I don't know how to get a single string to reserve. So say I have '>' but I want to reserve it to make it '&lt;'.</p> <p>I know to reserve a string you would go:</p> <pre><code>arrow = 'arrow' reverse_arrow = arrow[::-1] print(reverse_arrow) </code></pre> <p>But that doesn't seem to work if I want to reserve a si...
2
2016-05-27T22:02:04Z
37,493,467
<p>If you are wanting a reversed display then you need to import a font library with reversed characters (such as Mirror Image). Just not sure what you are wanting or where/how you are wanting to use this function...</p>
0
2016-05-27T23:03:40Z
[ "python" ]
NameError: global name 'DEV_ACCOUNT_NAME' is not defined - Azure Storage Emulator
37,492,955
<p>I'm trying to use the <a href="https://azure.microsoft.com/en-us/documentation/articles/storage-use-emulator/" rel="nofollow">Azure Storage Emulator</a> in my python app but getting the following error:</p> <pre><code>from azure.storage.table import TableService, Entity #Added after error global DEV_ACCOUNT_NAME D...
0
2016-05-27T22:09:49Z
37,493,125
<p>Declaring a variable as global in one module won't magically make it visible to other modules.</p> <p>To address your specific problem, though, it looks like this may be a <a href="https://github.com/Azure/azure-storage-python/issues/58" rel="nofollow" title="known issue">known issue</a> that was fixed some time ag...
1
2016-05-27T22:26:24Z
[ "python", "azure", "windows-azure-storage", "azure-storage-emulator" ]
Correctly calculating the F1 score in Sklearn
37,493,000
<p>I'm working in Python and I'm trying to get my the f1 score from my trained model. The documentation lists the syntax as:</p> <pre><code>f1_score(y_true, y_pred, average='macro') </code></pre> <p>but I cannot figure out what y_true and y_pred are supposed to be. Logically y_true should be the true value of y and y...
1
2016-05-27T22:14:13Z
37,493,177
<p>The F-score is a weight average of the precision and recall of your dataset. i.e. What portion of your predictions were true and what portion of trues did you predict: <a href="https://en.wikipedia.org/wiki/F1_score" rel="nofollow">https://en.wikipedia.org/wiki/F1_score</a></p> <p>I believe that Sklearn's function ...
1
2016-05-27T22:32:14Z
[ "python", "cross-validation" ]
Python 3 urllib: 530 too many connections, in loop
37,493,028
<p>I am retrieving data files from a FTP server in a loop with the following code:</p> <pre><code> response = urllib.request.urlopen(url) data = response.read() response.close() compressed_file = io.BytesIO(data) gin = gzip.GzipFile(fileobj=compressed_file) </code></pre> <p>Retrieving and processing...
0
2016-05-27T22:16:40Z
37,503,197
<p>Probably a pretty nasty workaround, but this worked for me. I made a script (here called test.py) which does the request (see code above). The code below is used in the loop I mentioned and calls test.py </p> <p>from subprocess import call<br> with open('log.txt', 'a') as f: call(['python', 'test.py', ar...
0
2016-05-28T19:47:11Z
[ "python", "python-3.x", "urllib2", "urllib" ]
Matplotlib: Overplot a line above another axes panel
37,493,052
<p>There are two axes panels, with a small one (in gray color) inside a big one (white color).</p> <p>With the following code, I am expecting the blue line to be on top of the gray small axes panel, because the blue line is set to have a ridiculously high <code>zorder</code>. But it turns out not to be the case.</p> ...
4
2016-05-27T22:19:00Z
37,494,306
<p>It would appear that (if the zorder is reversed from your example) then the "opaque" white background from your first (larger) axes is overlapping the second (smaller) axes, so one way is to simply set the face color of the larger axes to transparent. Also be sure to set the face color of the entire figure to white....
2
2016-05-28T01:17:21Z
[ "python", "python-2.7", "matplotlib", "data-visualization" ]
Matplotlib: Overplot a line above another axes panel
37,493,052
<p>There are two axes panels, with a small one (in gray color) inside a big one (white color).</p> <p>With the following code, I am expecting the blue line to be on top of the gray small axes panel, because the blue line is set to have a ridiculously high <code>zorder</code>. But it turns out not to be the case.</p> ...
4
2016-05-27T22:19:00Z
37,494,491
<p>I think we just have to compromise, so the solution I come up with is to add a third layer of axes, which is transparent and it is the one who really draws the blue line.</p> <p>Of course, we need to further fine-tune the first layer (<code>ax1</code>) a bit to suppress redundant elements (for example, by default <...
2
2016-05-28T02:01:02Z
[ "python", "python-2.7", "matplotlib", "data-visualization" ]
Image Failure in Django Blog
37,493,102
<p>I've created a simple django blog, and I'm having trouble getting images to consistently show up in my posts. Specifically, my images appear in the "list" view (the home page for the site), but not in the "detail" view (when viewing one individual post). The website is here if you want to see the issue live: endi...
1
2016-05-27T22:23:59Z
37,494,006
<p>Your problem is that the <code>src=</code> is understood as a relative URL (just like <code>saq7</code> pointed). You want the image to have its <code>src=</code> pointing to an absolute URL (starting with <code>http://</code>) since the image sits at an absolute location from the website root (from the domain).</p...
1
2016-05-28T00:20:12Z
[ "python", "html", "django" ]
Using custom classifier for mutilabel classification with GridSearchCV and OneVsRestClassifier
37,493,118
<p>I am trying to use the OneVsRestClassifier to do multilabel classification on a set of comments. My objective is to tag each comment to a possible list of topics. My custom classifier uses a manually curated list of words and their corresponding tags in a csv to tag each comment. I am trying to combine the results o...
1
2016-05-27T22:25:30Z
37,734,338
<p>I think you are looking for the <code>classes_</code> attribute : <a href="http://scikit-learn.org/dev/modules/generated/sklearn.multiclass.OneVsRestClassifier.html#sklearn.multiclass.OneVsRestClassifier" rel="nofollow">http://scikit-learn.org/dev/modules/generated/sklearn.multiclass.OneVsRestClassifier.html#sklearn...
0
2016-06-09T19:10:41Z
[ "python", "machine-learning", "scikit-learn", "supervised-learning", "multilabel-classification" ]
Memory Error while pickling a data frame to disk
37,493,165
<p>I have a 51K X 8.5K data frame with just binary (1 or 0) values. </p> <p>I wrote the following code: </p> <h1>Pickling the data to the disk</h1> <pre><code>outfile=open("df_preference.p", "wb") pickle.dump(df_preference,outfile) outfile.close() </code></pre> <p>It throws me Memory Error as below: </p> <pre><cod...
1
2016-05-27T22:30:36Z
37,493,275
<p><strong>UPDATE:</strong></p> <p>for <code>1</code> and <code>0</code> values you can use <code>int8</code> (1-byte) dtype, which will reduce your memory usage by at least 4 times.</p> <pre><code>(df_recommender &gt; 0).astype(np.int8).to_pickle('/path/to/file.pickle') </code></pre> <p>Here is an example with 51K ...
2
2016-05-27T22:43:01Z
[ "python", "numpy", "pandas" ]
How to not make a loop close when giving an empty input
37,493,306
<p>In my current Python project I utilize a loop via a while loop and have an input function inside of it. Thus far I've defined three different things that happen based on the use input using IF, and I've managed to use an ELSE to print a message when said input doesn't do anything.</p> <p>However, when the input rem...
-1
2016-05-27T22:46:04Z
37,493,411
<p>Try to use this condition at the beginning of your loop:</p> <pre><code>if not action: print("Please try again.") continue </code></pre>
1
2016-05-27T22:56:57Z
[ "python", "python-3.x" ]
How to not make a loop close when giving an empty input
37,493,306
<p>In my current Python project I utilize a loop via a while loop and have an input function inside of it. Thus far I've defined three different things that happen based on the use input using IF, and I've managed to use an ELSE to print a message when said input doesn't do anything.</p> <p>However, when the input rem...
-1
2016-05-27T22:46:04Z
37,493,415
<p>If you input nothing, <code>split</code> is giving you an empty list, so it throws an index error when you try to index it. The solution is just to check if the input is empty, and if so, skip the other conditions and continue iterating. <code>if action == []: break</code> accomplishes this task.</p> <pre><code>whi...
2
2016-05-27T22:57:13Z
[ "python", "python-3.x" ]
Why does an generic "try / except" block not apply to a Python TkInter callback?
37,493,309
<p>I have determined that in a Python TkInter GUI program, it is best practice to enclose the entire thing in a try / except block in order to catch all exceptions and present them to the end user (as opposed to something going wrong silently or the program exiting for seemingly no reason).</p> <p>However, this approa...
0
2016-05-27T22:46:12Z
37,493,588
<p>The following StackOverflow post was helpful: <a href="http://stackoverflow.com/questions/4770993/should-i-make-silent-exceptions-louder-in-tkinter">Should I make silent exceptions louder in tkinter?</a></p> <p>Basically, I need to use <code>report_callback_exception</code>. I've modified the code snippet according...
2
2016-05-27T23:19:46Z
[ "python", "tkinter" ]
Python: Opening a program in a new terminal [Linux]
37,493,341
<p>I am writing a bootstrap program that runs several individual programs simultaneously. Thus, I require each sub-program to have its own terminal window, in a manner that gives me the ability to start/stop each sub-program individually within the bootstrap.</p> <p>I was able to do this on Windows using Popen and CRE...
0
2016-05-27T22:49:39Z
37,493,446
<p>How about this?</p> <pre><code>os.system("gnome-terminal --disable-factory") </code></pre> <p>It forces it to open a new process. </p>
0
2016-05-27T23:01:15Z
[ "python", "linux", "raspberry-pi" ]
Python: Opening a program in a new terminal [Linux]
37,493,341
<p>I am writing a bootstrap program that runs several individual programs simultaneously. Thus, I require each sub-program to have its own terminal window, in a manner that gives me the ability to start/stop each sub-program individually within the bootstrap.</p> <p>I was able to do this on Windows using Popen and CRE...
0
2016-05-27T22:49:39Z
37,494,585
<p>I finally figured it out, but wanted to post the solution so others can find it in the future.</p> <p><code>Subprogram = Popen(['lxterminal', '-e', 'python ./Foo.py'], stdout=PIPE)</code></p> <p>The <code>lxterminal</code> is the Raspberry Pi's terminal name, <code>-e</code> is required, <code>python ./Foo.py</cod...
1
2016-05-28T02:23:08Z
[ "python", "linux", "raspberry-pi" ]
scikit-learn RFECV array with 0 samples
37,493,375
<p>I was trying to follow the tutorial as given <a href="http://scikit-learn.org/stable/auto_examples/feature_selection/plot_rfe_with_cross_validation.html#example-feature-selection-plot-rfe-with-cross-validation-py" rel="nofollow">here</a> for using the Recursive feature elimination with cross-validation (RFECV) funct...
0
2016-05-27T22:53:06Z
37,494,210
<p>I created dummy data and it worked for me:</p> <pre><code>import pandas as pd import numpy as np from sklearn import svm from sklearn.cross_validation import StratifiedKFold from sklearn.feature_selection import RFECV data = np.random.randn(50,9) # training on the first 50 rows training_y = np.random.random(50)....
0
2016-05-28T00:54:49Z
[ "python", "scikit-learn" ]
Python function not working a second time
37,493,429
<pre><code>def equip(item): x = True while x == True: if len(bag_sword) &gt; 1: print "You can't have 2 weapons equipped!" break if len(bag_chest) &gt; 1: print "You can't have 2 chestplates equipped!" break if len(bag_gloves) &gt; 1: ...
0
2016-05-27T22:59:17Z
37,493,455
<p>Once you added a sword to the bag, none of your conditions are true. Your <code>len(bag_sword)</code> is exactly 1, (so <code>if len(bag_sword) &gt; 1:</code> won't be matched), and <code>'iron sword' in bag</code> is false.</p> <p>Because none of your <code>if</code> statements match, no <code>break</code> is exec...
3
2016-05-27T23:02:02Z
[ "python", "python-2.7" ]
Python function not working a second time
37,493,429
<pre><code>def equip(item): x = True while x == True: if len(bag_sword) &gt; 1: print "You can't have 2 weapons equipped!" break if len(bag_chest) &gt; 1: print "You can't have 2 chestplates equipped!" break if len(bag_gloves) &gt; 1: ...
0
2016-05-27T22:59:17Z
37,493,765
<p>The entire code is nonsense. First of all, you are dealing with lists and not dictionaries.</p> <p>You DON'T have in Python "break" keyword. In Python exist if, elif and else keywords.</p> <p>item is the parameter you pass in the function.</p> <p>the keyword len(['item','two']) gives as a resultset 2, lists have...
0
2016-05-27T23:45:11Z
[ "python", "python-2.7" ]
Why i get null value here?
37,493,459
<p>i use $http.posts in angular like these:</p> <pre><code>$scope.postComment = function(comment, post) { var json = JSON.stringify({ 'comments_post': post, 'comments_text':comment}); alert(json); $http.post("/api/v1/comments/", json).success(function(json, status) { $scope....
-4
2016-05-27T23:02:46Z
37,493,526
<p>Basically what the error looks like to be, your database has a <code>NOT NULL</code> constraint on the <code>comments_post_id</code> and you are trying to insert something with a value of null to that column.</p> <p>Well, your problem is here:</p> <pre><code>$scope.postComment = function(comment, post) { var json ...
3
2016-05-27T23:11:15Z
[ "javascript", "python", "angularjs", "django", "django-rest-framework" ]
Specify subplot size instead of figsize in matplotlib
37,493,498
<p>I am using matplotlib to draw some graphs. Usually, standard practice is to start with a Figure's dimensions and specify the axes' dimensions so that the graph is then scaled to the available space.</p> <p>However I have a request to extend the height of a graph to accommodate outlying data on the y axis.</p> <p>I...
2
2016-05-27T23:08:02Z
37,493,540
<p>You mean something like this? You need to calculate margins.</p> <pre><code>import matplotlib.pyplot as plt subplotsize=[5.,5.] figuresize=[10.,10.] left = 0.5*(1.-subplotsize[0]/figuresize[0]) right = 1.-left bottom = 0.5*(1.-subplotsize[1]/figuresize[1]) top = 1.-bottom fig=plt.figure(figsize=(figuresize[0],...
2
2016-05-27T23:13:32Z
[ "python", "matplotlib" ]
Problems with recieving letter input in Pygame
37,493,525
<p>For a game i'm coding, there's one part during the main menu where you're required to press 'P' to play. I started using this code:</p> <pre><code>import pygame, sys, time DISPLAY = pygame.display.set_mode((1023, 647)) WHITE = (255, 255, 255) mainscreendisplayimg = pygame.image.load('mainScreen.png') def mainscree...
0
2016-05-27T23:11:15Z
37,493,602
<p>Ok so I figured this out on my own thanks for the help anyway! It turns out that I was using keydown incorrectly and accidentally had some syntax errors making it malfunction.</p> <p>For reference and to help others, here's the updated code:</p> <pre><code>active = true while active: for event in pygame.event...
0
2016-05-27T23:21:07Z
[ "python", "pygame", "keydown" ]
Why am I getting an out of index error on my matrix?
37,493,550
<p>I'm currently trying to make code for a game, the game is a lot like checkers. I'm representing my board as a 10 x 10 matrix. There exist two ways of moving in this game, you can do a step where you check all the positions adjacent to you and if any of them is empty you can move into them. Then if the position right...
0
2016-05-27T23:14:14Z
37,493,718
<p>You should print values of <code>x</code> and <code>y</code> in your <code>hopper</code> function. Since <code>chips2</code> contains indices in the matrix with value 2, then the index <code>[9][9]</code> will be contained in <code>chips2</code> implying <code>x = 9</code> or <code>y = 9</code> at some point. </p> ...
0
2016-05-27T23:36:25Z
[ "python", "numpy", "matrix" ]
Why am I getting an out of index error on my matrix?
37,493,550
<p>I'm currently trying to make code for a game, the game is a lot like checkers. I'm representing my board as a 10 x 10 matrix. There exist two ways of moving in this game, you can do a step where you check all the positions adjacent to you and if any of them is empty you can move into them. Then if the position right...
0
2016-05-27T23:14:14Z
37,493,745
<pre><code>if x &lt; 8 and matrix[x+1][y+1] != 0 and matrix[x+2][y-2] == 0: #up + right # ^ typo - that's down, not up </code></pre>
-1
2016-05-27T23:41:51Z
[ "python", "numpy", "matrix" ]
Why does creating a flask.Response object seemingly lose my data?
37,493,645
<p>I have a Python/Flask application that uses <code>flask.jsonify()</code></p> <p>Here is the code from my application: I'm creating a <code>flask.Response</code> object by using <code>jsonify()</code> and I'm printing its values. Note the 3 arguments I'm sending in to <code>jsonify()</code>. I will want to get them ...
1
2016-05-27T23:26:02Z
37,493,682
<p>The keyword arguments to <code>jsonify()</code> are part of the <strong>JSON payload</strong>, not the response metadata. You created a JSON object with <code>message</code>, <code>status_code</code> and <code>status</code> keys, these are entirely <em>separate</em> from the <code>Response</code> object attributes:<...
3
2016-05-27T23:31:10Z
[ "python", "flask" ]
Django - How to authenticate a password with MD5 hash
37,493,665
<p>So I'm trying to use the authentication method in my views, but always return "Does not exist", I'm using MD5 hash for my password field, so I don't know if thats the problem</p> <p><strong>forms.py</strong></p> <pre><code>class LoginForm(forms.Form): email = forms.EmailField() password = forms.CharField(w...
0
2016-05-27T23:28:29Z
37,493,712
<p>You need to get the email and password from the form's cleaned_data, not from the request directly. Read more on the cleaned_data attribute from the docs : <a href="https://docs.djangoproject.com/en/1.9/ref/forms/api/#django.forms.Form.cleaned_data" rel="nofollow">https://docs.djangoproject.com/en/1.9/ref/forms/api/...
0
2016-05-27T23:35:03Z
[ "python", "django", "hash", "django-forms", "django-views" ]
Django - How to authenticate a password with MD5 hash
37,493,665
<p>So I'm trying to use the authentication method in my views, but always return "Does not exist", I'm using MD5 hash for my password field, so I don't know if thats the problem</p> <p><strong>forms.py</strong></p> <pre><code>class LoginForm(forms.Form): email = forms.EmailField() password = forms.CharField(w...
0
2016-05-27T23:28:29Z
37,498,161
<p>You should not be hashing the password value yourself. That is what <code>authenticate</code> already does; so in effect you are hashing twice.</p>
0
2016-05-28T10:58:40Z
[ "python", "django", "hash", "django-forms", "django-views" ]
Working with large (over 2000x2000) images in Dlib, and they don't fit in my screen
37,493,681
<p>So after a few weeks, I finally managed to get Dlib installed, and immediately ran into another problem.</p> <p>I downloaded and ran their face landmark dector: <a href="http://dlib.net/face_landmark_detection.py.html" rel="nofollow">http://dlib.net/face_landmark_detection.py.html</a> and while the actual program w...
0
2016-05-27T23:31:10Z
37,494,676
<p>If you click on the image you can drag it around. Or hold ctrl and scroll the mouse wheel. That lets you zoom just like it does in many other programs.</p>
0
2016-05-28T02:45:25Z
[ "python", "image", "python-2.7", "dlib", "keypoint" ]
Working with large (over 2000x2000) images in Dlib, and they don't fit in my screen
37,493,681
<p>So after a few weeks, I finally managed to get Dlib installed, and immediately ran into another problem.</p> <p>I downloaded and ran their face landmark dector: <a href="http://dlib.net/face_landmark_detection.py.html" rel="nofollow">http://dlib.net/face_landmark_detection.py.html</a> and while the actual program w...
0
2016-05-27T23:31:10Z
37,853,210
<p>There are some methods as in dlib:</p> <pre><code>pyramid_down(); resize_image(); </code></pre> <p>you can resize image and then show to window.</p>
0
2016-06-16T07:59:24Z
[ "python", "image", "python-2.7", "dlib", "keypoint" ]
Screenfilling not working
37,493,704
<p>So I fell against this weird problem where I can't fill the screen. My code is </p> <pre><code>#Import all modules import pygame import random import math import time #Colors BLACK = ( 0, 0, 0) WHITE = ( 255, 255, 255) GREEN = ( 0, 255, 0) RED = ( 255, 0, 0) ORANGe = (255, 115, 0) YELLOW = (242, 255, 0) BROWN = (1...
1
2016-05-27T23:33:23Z
37,501,158
<p>You forgot to put brakets:</p> <pre><code>pygame.display.flip() </code></pre>
1
2016-05-28T16:04:50Z
[ "python", "pygame" ]
How would I run a program while not breaking the bot?
37,493,708
<p>So as the code goes as below, I want to be able to make my bot run a second python program when a certain phrase is said. Such as </p> <blockquote> <p>can you start a webcam bot?</p> </blockquote> <p>etc. etc. I just need something that calls the python file with the script in it, and like I said, not cause the ...
0
2016-05-27T23:34:08Z
37,494,575
<p>This hack will do the what you are looking for</p> <pre><code>os.system("python otherfile.py") </code></pre>
2
2016-05-28T02:20:05Z
[ "python", "artificial-intelligence" ]
How do I create a "not" filter in python for pandas
37,493,723
<p>I have this large dataframe I've imported into pandas and I want to chop it down via a filter. Here is my basic sample code:</p> <pre><code>import pandas as pd import numpy as np from pandas import Series, DataFrame df = DataFrame({'A':[12345,0,3005,0,0,16455,16454,10694,3005],'B':[0,0,0,1,2,4,3,5,6]}) df2= df[d...
0
2016-05-27T23:37:05Z
37,494,936
<p>Try</p> <pre><code>df2 = df[df["A"].map(lambda x: x &lt;= 0) | (df["B"] &lt;= 0)] </code></pre>
0
2016-05-28T03:35:20Z
[ "python", "python-2.7", "pandas" ]
How do I create a "not" filter in python for pandas
37,493,723
<p>I have this large dataframe I've imported into pandas and I want to chop it down via a filter. Here is my basic sample code:</p> <pre><code>import pandas as pd import numpy as np from pandas import Series, DataFrame df = DataFrame({'A':[12345,0,3005,0,0,16455,16454,10694,3005],'B':[0,0,0,1,2,4,3,5,6]}) df2= df[d...
0
2016-05-27T23:37:05Z
37,495,206
<p>No need for map function call on Series "A".</p> <p>Apply <a href="https://en.wikipedia.org/wiki/De_Morgan%27s_laws" rel="nofollow">De Morgan's Law</a>:</p> <p><strong>"not (A and B)" is the same as "(not A) or (not B)"</strong></p> <pre><code>df2 = df[~(df.A &gt; 0) | ~(df.B &gt; 0)] </code></pre>
1
2016-05-28T04:33:42Z
[ "python", "python-2.7", "pandas" ]
How do I create a "not" filter in python for pandas
37,493,723
<p>I have this large dataframe I've imported into pandas and I want to chop it down via a filter. Here is my basic sample code:</p> <pre><code>import pandas as pd import numpy as np from pandas import Series, DataFrame df = DataFrame({'A':[12345,0,3005,0,0,16455,16454,10694,3005],'B':[0,0,0,1,2,4,3,5,6]}) df2= df[d...
0
2016-05-27T23:37:05Z
37,495,256
<p>There is no need for the <code>map</code> implementation. You can just reverse the arguments like ...</p> <pre><code>df.ix[(df.A&lt;=0)|(df.B&lt;=0),:] </code></pre> <p>Or use <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>boolean indexing</code></a> witho...
1
2016-05-28T04:43:49Z
[ "python", "python-2.7", "pandas" ]
Formatting string not working
37,493,750
<p>I have done some research on formatting string but it does not want to work for me. I have this</p> <pre><code>for i in range(0,10): stat = arr[i] highscoreText = GameFont.render('{0:12}{1:&gt;0}'.format(stat["Name"],stat["Score"]),2,(255,255,255)) Screen.blit(highscoreText,[50,50 + (i*30)]) </code></pr...
0
2016-05-27T23:43:01Z
37,493,894
<p>String formatting assumes that you are using a monospace font. Since you have decided to use a proportional font you will need to draw as separate blocks and use the graphics routines to align each block to the right.</p>
1
2016-05-28T00:02:09Z
[ "python", "pygame" ]
Formatting string not working
37,493,750
<p>I have done some research on formatting string but it does not want to work for me. I have this</p> <pre><code>for i in range(0,10): stat = arr[i] highscoreText = GameFont.render('{0:12}{1:&gt;0}'.format(stat["Name"],stat["Score"]),2,(255,255,255)) Screen.blit(highscoreText,[50,50 + (i*30)]) </code></pr...
0
2016-05-27T23:43:01Z
37,493,899
<p>The string formatting works as expected. Try to print formatted sting in console. The problem with the font you use. See, <code>ll</code> in <code>hello</code> take the same span as <code>k</code> below.<br> To solve this you have to render names and scores separately and then blit them at appropriate positions.<br...
1
2016-05-28T00:03:25Z
[ "python", "pygame" ]
Calculating cumulative averages (How do i do it?)
37,493,754
<p>I have three functions, one to calculate lab average, one for weighted scores, and one for program average. These functions calculate the scores of a particular student that the user selects. (For ex. Will calculate lab avg. for only Ablao not other students) </p> <pre><code>Ablao 3 74 96 72 88 71 80 83 77 90 88 95...
-1
2016-05-27T23:43:18Z
37,493,951
<p>This can be done with a dictionary.</p> <pre><code>students = {} with open("inCSV.txt", "r") as f: for line in f.readlines(): data = line.rstrip().split(" ") student_name = data[0] student_grade = data[1] student_data = [int(x) for x in data[2:]] student_avg = sum(stude...
0
2016-05-28T00:12:59Z
[ "python", "list", "function", "append" ]
Calculating cumulative averages (How do i do it?)
37,493,754
<p>I have three functions, one to calculate lab average, one for weighted scores, and one for program average. These functions calculate the scores of a particular student that the user selects. (For ex. Will calculate lab avg. for only Ablao not other students) </p> <pre><code>Ablao 3 74 96 72 88 71 80 83 77 90 88 95...
-1
2016-05-27T23:43:18Z
37,494,036
<p>I think this does what you want:</p> <pre><code>scores_student = {} scores_grade = [[],[],[],[]] scores_all = [] with open("students.txt", "r") as f: for line in f: # Parse the line toks = line.split() name = toks[0] grade = int(toks[1]) scores = [float(tok) fo...
0
2016-05-28T00:25:09Z
[ "python", "list", "function", "append" ]
Finding all common, non-overlapping substrings
37,493,767
<p>Given two strings, I would like to identify all common sub-strings from longest to shortest.</p> <p>I want to remove any "sub-"sub-strings. As an example, any substrings of '1234' would not be included in the match between '12345' and '51234'.</p> <pre><code>string1 = '51234' string2 = '12345' result = ['1234', ...
3
2016-05-27T23:45:24Z
37,494,435
<p>Let's start with the Tree</p> <pre><code>from collections import defaultdict def identity(x): return x class TreeReprMixin(object): def __repr__(self): base = dict(self) return repr(base) class PrefixTree(TreeReprMixin, defaultdict): ''' A hash-based Prefix or Suffix Tree for tes...
1
2016-05-28T01:47:21Z
[ "python", "string", "substring", "matching", "suffix-tree" ]
Contrib Auth Reset Password Error
37,493,774
<p>I am using contrib auth reset_password in django and I get an error when I click the link it sends me.</p> <pre><code>[27/May/2016 20:23:41] ERROR [django.request:256] Internal Server Error: /reset/MQ/4c9-5eacbebedfa0c1742a1c/ Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/django/...
0
2016-05-27T23:46:13Z
37,494,271
<p>The solution was to set form action in the confirm template to </p> <pre><code>action="" </code></pre> <p>oddly enough.</p>
0
2016-05-28T01:09:37Z
[ "python", "django" ]
'class' object has no attribute 'method'
37,493,789
<p>I'm getting an error "AttributeError: 'Test Employee' object has no attribute 'increment_salary'". Not sure why I'm getting this error because 'increment_salary' is a method, not an attribute and I'm 99% sure I created it correctly. I've searched and the only answers I saw said to check mix of indentation and spaces...
0
2016-05-27T23:47:38Z
37,493,797
<p>You try to call <code>increment_salary()</code> <em>on your <code>TestEmployee</code> testcase</em>:</p> <pre><code>self.assertEqual(110, self.increment_salary(increase)) </code></pre> <p>You forgot to call it on <code>self.employee</code> instead. The following would not throw the exception:</p> <pre><code>self....
2
2016-05-27T23:48:43Z
[ "python", "class", "testing" ]
django urls : optional argument with default value is always None
37,493,855
<p>i have a view for insert / update a table called <code>BankAccounts</code> in my database ... basically if <code>info_id</code> is passed to function its a <code>edit/update</code> if not and it has default value its a <code>insert</code> operation</p> <pre><code>def bankcreate( requset , info_id = 0 ): print...
1
2016-05-27T23:55:34Z
37,493,939
<p>You have an extra slash in your regexp (second one).</p> <p>Change</p> <pre><code>url(r'^bankcreate/(?:/(?P&lt;info_id&gt;[1-9]+)/)?$' </code></pre> <p>to</p> <pre><code>url(r'^bankcreate/(?:(?P&lt;info_id&gt;[1-9]+)/)?$' </code></pre>
1
2016-05-28T00:11:12Z
[ "python", "django", "url-routing" ]
Python permutations of x unique characters repeated y times each
37,493,898
<p>I'm trying to get a list of permutations of x unique characters repeated y times each. So that would look something like this:</p> <pre><code>x = ['0', '1'] y = 2 permutation_list = ['0011','0101','1001','1010','0110','1100'] </code></pre> <p>I don't want extra stuff ('0001', '1110', etc) and I don't want duplic...
3
2016-05-28T00:03:17Z
37,493,931
<p>Use all <em>unique</em> permutations of your list, repeated <code>y</code> times:</p> <pre><code>from itertools import permutations permutation_list = set(permutations(x * y)) </code></pre> <p>Demo:</p> <pre><code>&gt;&gt;&gt; from itertools import permutations &gt;&gt;&gt; x = ['0', '1'] &gt;&gt;&gt; y = 2 &gt;...
5
2016-05-28T00:09:30Z
[ "python", "python-2.7", "math", "permutation" ]
Is it possible to read field names from a compound Dataset in an HDF5 file in Python?
37,493,928
<p>I have an HDF5 file that contains a 2D table with column names. It shows up as such in HDFView when I loot at this object, called <code>results</code>. </p> <p>It turns out that <code>results</code> is a "compound Dataset", a one-dimensional array where each element is a row. Here are its properties as displayed by...
0
2016-05-28T00:08:54Z
37,494,840
<p>This is pretty easy to do in h5py and works just like compound types in Numpy. If res is a handle to your dataset, res.dtype.fields.keys() will return a list of all the field names.</p> <p>If you need to know a specific dtype, something like res.dtype.fields['V2pt'] will give it.</p>
2
2016-05-28T03:18:18Z
[ "python", "hdf5", "h5py" ]
Assignment through chained indexers
37,493,960
<p>I would like to be able to assign to a DataFrame through chained indexers. Notionally like this:</p> <pre><code>subset = df.loc[mask] ... # much later subset.loc[mask2, 'column'] += value </code></pre> <p>This does not work because, as I understand it, the second .loc triggers a copy-on-write. Is there a way to do...
1
2016-05-28T00:14:00Z
37,496,115
<p>When you get to:</p> <pre><code>subset.loc[mask2, 'column'] </code></pre> <p>assign this to another subset so you can access its index and columns attributes.</p> <pre><code>subsubset = subset.loc[mask2, 'column'] </code></pre> <p>Then you can access <code>df</code> with subsubset's index and columns</p> <pre><...
0
2016-05-28T06:52:10Z
[ "python", "pandas" ]
How do I work with "end of options" in docopt?
37,494,013
<p>I'm using <a href="http://docopt.org/" rel="nofollow">docopt</a> and python 2.7. I want to implement something similar to <code>--</code> in vim. From <code>man vim</code>:</p> <pre><code>-- Denotes the end of the options. Arguments after this will be handled as a file name. This can be used to edit a...
0
2016-05-28T00:21:16Z
37,505,952
<p>I am no expert, but try making the <code>--</code> optional for all usages.</p> <pre><code>doc.py FILE [options] [--] [ARGUMENTS ... ] </code></pre> <p>You can either enter options, or not and start with arguments. It will look for the first <code>--</code> if its exists.</p> <p>Let me know if this works.</p>
0
2016-05-29T03:44:57Z
[ "python", "command-line-arguments", "docopt" ]
Where does a Python list hold its values?
37,494,021
<p>From introspection perspective, where list values are located in the class object. If list object is class in python:</p> <pre><code>&gt;&gt;&gt; a = ['one', 'two'] &gt;&gt;&gt; type(a) &lt;class 'list'&gt; </code></pre> <p>So it is stored somewhere in the class, but where?</p> <p>For example: If we define a clas...
2
2016-05-28T00:23:17Z
37,494,086
<p>This is really up to the implementation detail. In cpython, the container object only hold references (pointers) to the stored values. Any operation involving the list internals only manipulates the pointers, not the objects. </p> <p>Memory is over-allocated so that there are always some free slots available, wh...
3
2016-05-28T00:33:08Z
[ "python", "list", "oop", "dictionary", "python-internals" ]
Where does a Python list hold its values?
37,494,021
<p>From introspection perspective, where list values are located in the class object. If list object is class in python:</p> <pre><code>&gt;&gt;&gt; a = ['one', 'two'] &gt;&gt;&gt; type(a) &lt;class 'list'&gt; </code></pre> <p>So it is stored somewhere in the class, but where?</p> <p>For example: If we define a clas...
2
2016-05-28T00:23:17Z
37,494,088
<p>Not really. The list items aren't stored under any accessible property of the list object. It's all just low-level implementation details of the language.</p> <p>However, if you want to subclass <code>list</code> and add or remove an item, you can just run list operations on <code>self</code>.</p> <pre><code>In [6...
2
2016-05-28T00:33:39Z
[ "python", "list", "oop", "dictionary", "python-internals" ]
Where does a Python list hold its values?
37,494,021
<p>From introspection perspective, where list values are located in the class object. If list object is class in python:</p> <pre><code>&gt;&gt;&gt; a = ['one', 'two'] &gt;&gt;&gt; type(a) &lt;class 'list'&gt; </code></pre> <p>So it is stored somewhere in the class, but where?</p> <p>For example: If we define a clas...
2
2016-05-28T00:23:17Z
37,494,097
<blockquote> <p>Is there similar option to reach those values in the list class object?</p> </blockquote> <p>Yes. It's the list itself. For example, if you define <code>a</code>:</p> <pre><code>a = ['one', 'two'] </code></pre> <p>Then the list values are in <code>a</code>.</p>
0
2016-05-28T00:34:10Z
[ "python", "list", "oop", "dictionary", "python-internals" ]
Publish data to RabbitMQ server via Mqtt
37,494,035
<p>I wrote a simple python program to connect <code>RabbitMqtt</code> server and hope to generate a queue and publish messages. However, after building the connection and creating a queue, the message was not published successfully (when I check the information of message, I cannot find any records and data). I wonder ...
0
2016-05-28T00:25:06Z
37,496,309
<p>The problem is that you are calling client.publish() before the connection is complete. Move the client.publish into the on_connect function, AFTER client.subscribe('SEEDQ') and it will work.</p> <pre><code># The callback for when the client receives a CONNACK response from the server. def on_connect(client, userda...
0
2016-05-28T07:16:28Z
[ "python", "mqtt", "paho" ]
Flask View Testing General and with Subdomains
37,494,083
<p>I'm working on testing the views that I have for a Flask application and I'm having some issues. I use a csrf token for my form submissions and I also use subdomains for logging in and I was wondering how to test for that as well. If anyone has any experience or could give me an example or some direction, I would ap...
0
2016-05-28T00:32:12Z
37,814,312
<p>In order to be able to create unittests for a flask app using subdomain routing, the <code>test_client()</code> function can be used. For this to work, you will need to set the <code>allow_subdomain_redirects</code> attribute on the <code>test_client</code> object to <code>True</code>.</p> <p>Here is an example t...
0
2016-06-14T14:05:02Z
[ "python", "flask" ]
No /kivy drectory in SD card using Kivy Laucnher
37,494,104
<p>I am trying to run a Kivy app using the Kivy Launcher, however, when I connect my phone to the computer and try to put the file containing the app there is no kivy directory in which to put my app. </p>
0
2016-05-28T00:35:16Z
37,496,191
<p>Kivy Launcher does not create that directory automatically, you have to create it. Launcher only opens that directory and search for <code>android.txt</code> files. If no such file is available, it won't display your project in Launcher's list, therefore you won't be able to run it.</p> <p>Path is usually <code>sdc...
1
2016-05-28T07:01:32Z
[ "android", "python", "kivy" ]
Append sub dictionary to main dictionary
37,494,124
<p>I have a function that collects dictionary values to subdict, how do I append this to my main dictionary as a nested entry?</p> <pre><code>Dict = {} def getDetail(): subdict = {} first_name = input("Enter first name") if first_name.lower() == 'quit': return None else: last_name = inp...
0
2016-05-28T00:38:44Z
37,494,259
<p>You can just do so as you would normally do for any entry.</p> <pre><code>my_dict[key] = value </code></pre> <p>Following this format:</p> <pre><code>my_dict = Dict value = getDetail() key = "Up to you" my_dict[key] = value </code></pre>
1
2016-05-28T01:05:28Z
[ "python", "python-3.x", "dictionary" ]
Append sub dictionary to main dictionary
37,494,124
<p>I have a function that collects dictionary values to subdict, how do I append this to my main dictionary as a nested entry?</p> <pre><code>Dict = {} def getDetail(): subdict = {} first_name = input("Enter first name") if first_name.lower() == 'quit': return None else: last_name = inp...
0
2016-05-28T00:38:44Z
37,494,398
<p>So, you could:</p> <pre><code>Dict = {} def getDetail(): subdict = {} first_name = input("Enter first name") if first_name.lower() != 'quit': last_name = input("Enter last name") nick_name = input("Enter nickname") address = input("Enter address") number = input("Enter ph...
1
2016-05-28T01:37:38Z
[ "python", "python-3.x", "dictionary" ]
Append sub dictionary to main dictionary
37,494,124
<p>I have a function that collects dictionary values to subdict, how do I append this to my main dictionary as a nested entry?</p> <pre><code>Dict = {} def getDetail(): subdict = {} first_name = input("Enter first name") if first_name.lower() == 'quit': return None else: last_name = inp...
0
2016-05-28T00:38:44Z
37,494,662
<p>Alternatively written, simple and dirty:</p> <pre><code>MyDict = {} def GetDetail(): first_name = raw_input("Enter first name: ") if first_name.lower() == 'quit': return None else: last_name = raw_input("Enter last name: ") nick_name = raw_input("Enter nickname: ") a...
1
2016-05-28T02:42:38Z
[ "python", "python-3.x", "dictionary" ]
How do I replace bytes in multiple files in one directory recursively with Python 3.5.1?
37,494,162
<p>I'm looking to achieve the following with multiple files in the same directory from one run of a script:</p> <pre><code>fh = open("*.bin", "r+b") fh.seek(0) fh.write(bytes([0x4F, 0x67])) fh.close() </code></pre> <p>My end goal is to have, say, myByteReplacement.py that, when ran (from within the same directo...
1
2016-05-28T00:45:12Z
37,494,185
<p>you need to do </p> <pre><code>os.listdir("your directory") </code></pre> <p>which will give you a list of files. Then do your code on each file</p>
1
2016-05-28T00:49:26Z
[ "python", "recursion", "replace", "byte" ]
Is there a reason to avoid unix style relative paths in python?
37,494,165
<p>I have written this:</p> <pre><code>ancestor_dir = os.path.join(os.path.dirname(__file__), *([os.pardir]*5 + [ancestor_name])) </code></pre> <p>I'm thinking, why don't I just say</p> <pre><code>ancestor_dir = os.path.join(os.path.dirname(__file__), "../../../../../", ancestor_name])) </code></pre> <p>It seems to...
3
2016-05-28T00:45:20Z
37,494,189
<p>Using <code>os.pardir</code> makes the code portable to non-POSIX systems. If compatibility isn't an issue, then it doesn't matter much. But one could argue that using <code>os.pardir</code> can be more readable; but that's too subjective to quantify.</p>
0
2016-05-28T00:51:00Z
[ "python", "path" ]
Is there a reason to avoid unix style relative paths in python?
37,494,165
<p>I have written this:</p> <pre><code>ancestor_dir = os.path.join(os.path.dirname(__file__), *([os.pardir]*5 + [ancestor_name])) </code></pre> <p>I'm thinking, why don't I just say</p> <pre><code>ancestor_dir = os.path.join(os.path.dirname(__file__), "../../../../../", ancestor_name])) </code></pre> <p>It seems to...
3
2016-05-28T00:45:20Z
37,497,038
<p>Using <code>".."</code> instead of <code>os.pardir</code> not an issue unless you want to maintain compatibility with the <em>classic Mac OS</em> ( predecessor of OS X ) in which</p> <ol> <li>Parent directory is denoted by <code>::</code> </li> <li>Directory separator is denoted by <code>:</code></li> <li>Current d...
3
2016-05-28T08:48:58Z
[ "python", "path" ]
music21 - Transpose streams to a given key
37,494,229
<p>Is there a function or easy way to transpose a stream to a given key?</p> <p>I want to use it in a loop, e.g, take a set of major streams and transpose all of then to C major (so then I can do some statistical work with them).</p> <p>All the transpose tools I saw work with intervals or number of tones, not fixed k...
1
2016-05-28T00:58:34Z
37,513,103
<p>If <code>s</code> is a <code>Stream</code> (such as a <code>Score</code> or <code>Part</code>), then <code>s.transpose('P4')</code> will move it up a Perfect Fourth, etc. If you know the key of <code>s</code> as <code>k</code> major, then <code>i = interval.Interval(k, 'C')</code> will let you do <code>s.transpose(...
1
2016-05-29T17:54:48Z
[ "python", "music21" ]
Checking a series of binary states
37,494,738
<p>I suppose the easiest way to explain this is to use the analogy of tictactoe. A board of tictactoe can be expressed as a 2D array of binary states.</p> <p>So the board # can be shown as [[1,2,3],[1,2,3],[1,2,3]] And each index of this array has a binary value (X or O) So to check if a polayer has won, you check if ...
1
2016-05-28T02:57:26Z
37,495,012
<p>One way to do it is to scan the grid row by row and for every position keep track of track of pattern length in all possible directions. In this case directions would be top left -> down right, top right -> down left, left -> right and along the 'line'. When processing each position increment the value of previous p...
1
2016-05-28T03:53:29Z
[ "python", "arrays", "math" ]
Date Time Object Error: string indices must be integers, not str
37,494,798
<p>I m trying to convert a date in excel file into python date time object and I am running into the following error</p> <p><img src="http://i.stack.imgur.com/0p41c.jpg" alt="My Code &amp; Error"></p>
-1
2016-05-28T03:09:21Z
37,494,827
<p>Change that line to:</p> <pre><code>enrollment['cancel_date'] = parse_date(enrollment['cancel_date']) </code></pre> <p>By the way, next time please copy and paste the code and the error message into your question as text, not as a screenshot.</p>
0
2016-05-28T03:15:39Z
[ "python", "datetime" ]
Find the column names which have top 3 largest values for each row
37,494,844
<p>For example the data look like:</p> <pre><code>df={'a1':[5,6,3,2,5],'a2':[23,43,56,2,6], 'a3':[4,2,3,6,7], 'a4':[1,2,1,3,2],'a5':[4,98,23,5,7],'a6':[5,43,3,2,5]} x=pd.DataFrame(df) Out[260]: a1 a2 a3 a4 a5 a6 0 5 23 4 1 4 5 1 6 43 2 2 98 43 2 3 56 3 1 23 3 3 2 2 6 3...
3
2016-05-28T03:18:34Z
37,495,533
<p>What you need is <a href="http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.DataFrame.nlargest.html">pandas.DataFrame.nlargest</a>. </p> <pre><code>import pandas as pd import numpy as np df={'a1':[5,6,3,2,5],'a2':[23,43,56,2,6], 'a3':[4,2,3,6,7], 'a4':[1,2,1,3,2],'a5':[4,98,23,5,7],'a6':[5,43,3,...
2
2016-05-28T05:27:40Z
[ "python" ]