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 Top Level JSON Index
39,797,618
<p>I have the following JSON file from an API I am calling:</p> <pre><code>{ "14500": [ { "5": { "versionName": "VersionOne", "expand": "executionSummaries", "name": "Regression", "projectId": 15006, "startDate": "", "executionSummaries": { "executi...
0
2016-09-30T18:13:47Z
39,797,828
<pre><code>def find_in_dicts(d, key, value): #This finds all dictionaries that has the given key and value for k, v in d.items(): if k == key: if v == value: yield d else: if isinstance(v, dict): for i in find_in_dicts(v, key, value): ...
0
2016-09-30T18:26:04Z
[ "python", "json" ]
Python Top Level JSON Index
39,797,618
<p>I have the following JSON file from an API I am calling:</p> <pre><code>{ "14500": [ { "5": { "versionName": "VersionOne", "expand": "executionSummaries", "name": "Regression", "projectId": 15006, "startDate": "", "executionSummaries": { "executi...
0
2016-09-30T18:13:47Z
39,797,925
<p>Here is a partial script tailored to your exact input. If it finds <code>name: regression</code> at the appropriate level, it prints a few of the related values.</p> <pre><code>for k, list_of_dicts in requestData.items(): for d in list_of_dicts: for k, v in d.items(): if isinstance(v, dict) ...
0
2016-09-30T18:31:33Z
[ "python", "json" ]
Python Top Level JSON Index
39,797,618
<p>I have the following JSON file from an API I am calling:</p> <pre><code>{ "14500": [ { "5": { "versionName": "VersionOne", "expand": "executionSummaries", "name": "Regression", "projectId": 15006, "startDate": "", "executionSummaries": { "executi...
0
2016-09-30T18:13:47Z
39,798,282
<p>Check out amazing <a href="http://boltons.readthedocs.io/en/latest/" rel="nofollow"><code>boltons</code></a> library! It has a <a href="http://sedimental.org/remap.html" rel="nofollow"><code>remap</code></a> function that may be an overkill in your case, but is a good thing to know about. Here's an elegant way to ex...
0
2016-09-30T18:53:49Z
[ "python", "json" ]
Trouble setting up linprog in Python
39,797,663
<p>I am using the following code but I have not been able to set up the problem to run.</p> <pre><code>import numpy as np from scipy.optimize import linprog c = np.asarray([-0.098782540360068297, -0.072316526358138802, 0.004, 0.004, 0.004, 0.004]) A_ub = np.asarray([[1.0, 0, 0, 0, 0, 0], [-1.0, 0, 0, 0, 0, 0], [0, -1...
0
2016-09-30T18:16:47Z
39,803,389
<p>The bounds parameter wants a list of pairs. Use something like:</p> <pre><code>lb = np.zeros(6) #lower bound for x array ub = np.ones(6)*2 #upper bound for x array res2 = linprog(c, A_ub, b_ub, bounds=list(zip(lb, ub))) </code></pre>
1
2016-10-01T05:37:00Z
[ "python", "optimization", "scipy" ]
Pip is installed, but command not found
39,797,671
<p>Pip has been on my machine for years, but recently I could not get it to work. To fix this I ran:</p> <pre><code>$ sudo python get-pip.py The directory '/Users/tomeldridge/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions...
0
2016-09-30T18:17:12Z
39,798,218
<p>Your problem is <code>usr/local/bin</code> in your path, it has to be <code>/usr/local/bin</code>.</p> <p>That should do it.</p> <p>You should be able to change that in the file <code>~/.bash_profile</code>.</p>
1
2016-09-30T18:49:42Z
[ "python", "pip" ]
Matplotlib3D color based points on their Z axis value
39,797,672
<p>I am currently scattering points in a 3D graph. My X,Y and Z are lists (len(Z)=R). However, I would like to give them a color based on their Z value. For example if Z>1 the color would be red, Z>2 blue Z>3 pink and so on. My current code is:</p> <pre><code>from mpl_toolkits.mplot3d import axes3d import matplotlib.p...
0
2016-09-30T18:17:13Z
39,799,461
<p>If you see the gallery, you will find the answer. You need to pass an array to <code>c=colors</code>. See these: <a href="http://matplotlib.org/examples/mplot3d/scatter3d_demo.html" rel="nofollow">1</a>, <a href="http://matplotlib.org/examples/pie_and_polar_charts/polar_scatter_demo.html" rel="nofollow">2</a>.</p> ...
0
2016-09-30T20:18:09Z
[ "python", "matplotlib" ]
How to run a python script with arguments via the click of a button in javascript
39,797,807
<p>So I've written a program in JavaScript that outputs a JSON. What I want to do is, with the click of a button, I want to pass in that JSON as an argument to a python script.</p> <p>I am not entirely sure how to proceed with this:</p> <pre><code>$.ajax({ url: "/path/to/your/scriptPython", success: function(response...
2
2016-09-30T18:25:12Z
39,798,133
<p>This depends on one important consideration: where is your Python code?</p> <p>If you want the Python to run on the user's machine, that gets complicated due to security measures: websites generally aren't allowed to execute arbitrary code on viewers' machines. (Imagine if that Python code wiped their hard drive, f...
0
2016-09-30T18:44:02Z
[ "javascript", "python", "ajax" ]
SettingWithCopyWarning on Column Creation
39,797,819
<p>I'm trying to create a moving average column for my data called 'mv_avg'. I'm getting a SettingWithCopyWarning that I have been unable to fix. I could suppress the warning, but I cannot figure out where in my code I am creating a copy, and I want to utilize best practices. I've created a generalizable example below ...
2
2016-09-30T18:25:38Z
39,798,005
<p>you can create a copy using .copy()</p> <pre><code>import pandas as pd data = {'category' : ['a', 'a', 'a', 'b', 'b', 'b'], 'value' : [1,2,3,4,5,6]} df = pd.DataFrame(data) df_a = df.loc[df['category'] == 'a'].copy() df_a['mv_avg'] = df_a['value'].rolling(window=2).mean() </code></pre> <p>or you can use an indexer...
3
2016-09-30T18:35:32Z
[ "python", "pandas" ]
SettingWithCopyWarning on Column Creation
39,797,819
<p>I'm trying to create a moving average column for my data called 'mv_avg'. I'm getting a SettingWithCopyWarning that I have been unable to fix. I could suppress the warning, but I cannot figure out where in my code I am creating a copy, and I want to utilize best practices. I've created a generalizable example below ...
2
2016-09-30T18:25:38Z
39,798,051
<p>Here are three options</p> <ol> <li><p>Ignore/filter the warning; in this case it is spurious as you are deliberately assigning to a filtered DataFrame.</p></li> <li><p>If you are done with <code>df</code>, you could <code>del</code> it, which will prevent the warning, because <code>df_a</code>will no longer hold a...
2
2016-09-30T18:39:06Z
[ "python", "pandas" ]
Wedge Patch Position Not Updating
39,797,843
<p>I am attempting to shift the position of a <code>matplotlib.patches.Wedge</code> by modifying its <code>center</code> property, but it does not seem to have any effect.</p> <p>For example:</p> <pre><code>import matplotlib.pyplot as plt import matplotlib.patches as patches fig = plt.figure() ax = fig.add_subplot(1...
2
2016-09-30T18:26:50Z
39,798,332
<p>You probably have to <code>update</code> the properties of your <code>Wedge</code>:</p> <pre><code>tmp.update({'center': [4,4]}) </code></pre> <p>As you see, the method accepts a dict that specifies the properties to update.</p> <p><a href="http://i.stack.imgur.com/cppA9.png" rel="nofollow"><img src="http://i.sta...
1
2016-09-30T18:56:09Z
[ "python", "python-3.x", "matplotlib" ]
Working with time series in Pandas/Python
39,798,002
<p>I have the following data:</p> <pre><code> AdjClose Chg RM Target date 2014-01-16 41.733862 0.002045 0 NaN 2014-01-17 41.695141 -0.000928 1 NaN 2014-01-21 42.144309 0.010773 1 NaN 2014-01-22 41.803561 -0.008085 1 NaN 2014-01-...
2
2016-09-30T18:35:22Z
39,798,914
<p>I would do a <code>rolling_sum()</code> exactly as you have done, though I think the up/down and down/up are easily measured as <em>when the sign changes</em>:</p> <pre><code>dd['RM'] = np.int64(np.sign(dd['Chg']) != np.sign(dd['Chg'].shift(1))) dd['RM'].values[0] = 0 </code></pre>
2
2016-09-30T19:36:10Z
[ "python", "pandas" ]
How do I insert a space after and before a dash that is not already surrounded by spaces?
39,798,023
<p>Let's say I have these strings:</p> <pre><code>string1= "Queen -Bohemian Rhapsody" string2= "Queen-Bohemian Rhapsody" string3= "Queen- Bohemian Rhapsody" </code></pre> <p>I want all of them to become to be like this:</p> <pre><code> string1= "Queen - Bohemian Rhapsody" string2= "Queen - Bohemian Rhapsody" ...
2
2016-09-30T18:37:23Z
39,798,065
<p>You can regexp:</p> <pre><code>import re pat = re.compile(r"\s?-\s?") # \s? matches 0 or 1 occurenece of white space # re.sub replaces the pattern in string string1 = re.sub(pat, " - ", string1) string2 = re.sub(pat, " - ", string2) string3 = re.sub(pat, " - ", string3) </code></pre>
6
2016-09-30T18:39:51Z
[ "python", "regex", "string" ]
Printing columns in a DB2 database
39,798,026
<p>I want to print all the columns of a table in a database in db2. This is the current code I have now for doing that.</p> <pre><code>#!/usr/bin/python import ibm_db from ibm_db import tables, fetch_assoc, exec_immediate conn = ibm_db.connect("DATABASE=DB;HOSTNAME=9.6.24.89;PORT=50000;PROTOCOL=TCPIP;UID=R1990;PWD=se...
0
2016-09-30T18:37:36Z
39,803,514
<p>I think you have a problem of encodage format (Unicode possible)</p> <p>->And if you try this query, have you the same result?:</p> <pre><code> SELECT cast(TABLE_NAME as varchar(255) ccsid 1147) TABLE_NAME FROM SYSIBM.SYSTABLES WHERE type = 'T' AND name= 'Tables' </code></pre> <p>->May be can you try this...
0
2016-10-01T05:58:16Z
[ "python", "database", "python-2.7", "db2" ]
Can't connect to compose.io mongoDB on bluemix
39,798,088
<p>I'm trying connect to mongoDB but it seems that I can't reach the host.</p> <p>This problem occurs in mongoshell and pymongo. On shell I use</p> <pre><code>mongo --ssl --sslAllowInvalidCertificates host:port/db -u user -p pass --sslCAFile ca.pem </code></pre> <p>and I get the error message bellow.</p> <pre><code...
0
2016-09-30T18:41:23Z
39,798,536
<p>I've just connected to a mongoDB instance I've deployed to bluemix using mongo shell with similar syntax to what you've used, and it works fine.</p> <p>There might be a problem with your deployment. In the bluemix ui, when you open your mongo service, does the "Status" indicator appear green?</p> <p>The other thin...
2
2016-09-30T19:10:18Z
[ "python", "mongodb", "ibm-bluemix", "pymongo", "compose" ]
Matching pairs game in Python tkinter
39,798,141
<p>I am trying to create a matching card game in Python 3 tkinter. The player is presented with a 4x4 grid of buttons, each button with an image. There are eight pairs of images. The player clicks on a button, and the button shows the image; the player clicks on another button to show its image. If the two buttons show...
-1
2016-09-30T18:44:24Z
39,798,189
<p>you need to create an ifelse statement that checks for the legality of the move, if it is legal, continue with script, if else give the user a message but loop it back to the user guess. </p>
0
2016-09-30T18:47:18Z
[ "python", "python-3.x", "tkinter" ]
Pretty Printing (2D Arrays, Box)
39,798,149
<p>I have written the following code:</p> <pre><code>for row in range(len(listOfLists)): print('+' + '-+'*len(listOfLists)) print('|', end='') for col in range(len(listOfLists[row])): print(listOfLists[row][col], end='|') print(' ') #To change lines print('+' + '-+'*len(listOfLists)) </code></...
2
2016-09-30T18:44:49Z
39,798,299
<p>Your problem was that <code>len(listOfLists)</code> was used for the size of the printed table in both directions. <code>len(listOfLists)</code> defaults to number of rows, by doing <code>len(listOfLists[1])</code> you get the number of columns.</p> <pre><code> listOfLists = [['a', 'b', 'c'], ['d', 'e', 'f'], ...
2
2016-09-30T18:54:27Z
[ "python", "arrays", "multidimensional-array" ]
Pretty Printing (2D Arrays, Box)
39,798,149
<p>I have written the following code:</p> <pre><code>for row in range(len(listOfLists)): print('+' + '-+'*len(listOfLists)) print('|', end='') for col in range(len(listOfLists[row])): print(listOfLists[row][col], end='|') print(' ') #To change lines print('+' + '-+'*len(listOfLists)) </code></...
2
2016-09-30T18:44:49Z
39,798,301
<pre><code>def awesome_print(listOfLists): for row in range(len(listOfLists)): print('+' + '-+'*len(listOfLists[row])) print('|', end='') for col in range(len(listOfLists[row])): print(listOfLists[row][col], end='|') print(' ') #To change lines print('+' + '-+'*len(l...
1
2016-09-30T18:54:39Z
[ "python", "arrays", "multidimensional-array" ]
Pretty Printing (2D Arrays, Box)
39,798,149
<p>I have written the following code:</p> <pre><code>for row in range(len(listOfLists)): print('+' + '-+'*len(listOfLists)) print('|', end='') for col in range(len(listOfLists[row])): print(listOfLists[row][col], end='|') print(' ') #To change lines print('+' + '-+'*len(listOfLists)) </code></...
2
2016-09-30T18:44:49Z
39,798,347
<p>You are printing this separator based on number of rows, not number of columns. Using additional test cases helps with debugging immediately.</p> <pre><code>def printListOfLists(listOfLists): for row in range(len(listOfLists)): print('+' + '-+' * len(listOfLists[0])) print('|', end='') f...
2
2016-09-30T18:57:22Z
[ "python", "arrays", "multidimensional-array" ]
LINE RESTful Messaging API - Error with wrong IP address
39,798,152
<p>I am using LINE Messaging API trying to push a message via bot. I've followed the configuration/setup detailed in <a href="https://business.line.me/en/" rel="nofollow">https://business.line.me/en/</a> and encountered this error - Access to this API denied due to the following reason: Your ip address [23.3.104.4] is ...
0
2016-09-30T18:44:59Z
39,864,043
<p>I think that might be a bug and caused of "Server IP Whitelist" in your bot settings. Try to remove the ip address you assigned.</p>
0
2016-10-05T01:20:54Z
[ "python", "line" ]
Reading 24-Bit WAV with wavio Python 3.5
39,798,259
<p>I am using <a href="https://github.com/WarrenWeckesser/wavio/blob/master/wavio.py" rel="nofollow">wavio</a> by WarrenWeckesser as I need to read 24-bit wav files in python. The wav files I have are produced by some instrumentation and I am trying to get the raw values without any normalisation or scaling.</p> <p>In...
0
2016-09-30T18:52:49Z
39,799,109
<p>The shape of <code>a</code> is <code>(num_samples, nchannels, 4)</code> and <code>sampwidth == 3</code>, so that line is the same as</p> <pre><code>a[:, :, 3:] = (a[:, :, 2:3] &gt;&gt; 7) * 255 </code></pre> <p>which is the same as</p> <pre><code>a[:, :, 3] = (a[:, :, 2] &gt;&gt; 7) * 255 </code></pre> <p>we cou...
1
2016-09-30T19:50:06Z
[ "python", "numpy", "wav" ]
Python NIM game: how do i add new game (y) or (n)
39,798,278
<p>I have a question: How do i put New Game in code or PlayAgain (y) or (n) This is for my school project. I have been trying to find myself a solution but it will only repeat question "play again" or error. </p> <pre><code> import random player1 = input("Enter your real name: ") player2 = "Computer" ...
0
2016-09-30T18:53:44Z
39,799,347
<p>Your loop condition is always <code>True</code>. This is what needs adjusting. Instead you only want to loop while the user wants to continue</p> <pre><code>choice = 'y' # so that we run at least once while choice == 'y': ... choice = input("Play again? (y/n):") </code></pre> <p>You will have to make sur...
0
2016-09-30T20:07:59Z
[ "python", "python-3.x" ]
Override django model save function that extends AbstractBaseUser
39,798,306
<p>Im using restframework for user signup i need generate random password before save, i override save method in model but this never run and throw message password field is required. ¿How i can override this? Thanks.</p> <pre><code># ViewSet. class AgentViewSet(viewsets.ModelViewSet): queryset = Agents.objects.a...
0
2016-09-30T18:54:51Z
39,798,451
<p>Try overriding the <code>create_user</code> method in your <code>MyUserManager</code>. Something like:</p> <pre><code>def create_user(self, **kwargs): kwargs['password'] = # Generate random password return super().create_user(**kwargs) </code></pre>
0
2016-09-30T19:03:20Z
[ "python", "django", "python-2.7", "login", "django-rest-framework" ]
Override django model save function that extends AbstractBaseUser
39,798,306
<p>Im using restframework for user signup i need generate random password before save, i override save method in model but this never run and throw message password field is required. ¿How i can override this? Thanks.</p> <pre><code># ViewSet. class AgentViewSet(viewsets.ModelViewSet): queryset = Agents.objects.a...
0
2016-09-30T18:54:51Z
39,799,199
<p>Add or update in your code</p> <p>AgentSerializer(serializers.py)</p> <pre><code>class AgentSerializer(serializers.ModelSerializer): class Meta: model = Agents def create(self, validated_data): return Agents.objects.create(**validated_data) </code></pre> <p>In views.py</p> <pre><code>cla...
1
2016-09-30T19:57:14Z
[ "python", "django", "python-2.7", "login", "django-rest-framework" ]
GeoPoint equivalent for a Cartesian coordinate system
39,798,328
<p>I have fields <code>x</code> and <code>y</code> on some search documents that correspond to Cartesian coordinates, and I'd like to perform a radial search like:</p> <pre><code>query = '(x * x) + (y * y) &lt; 100' </code></pre> <p>which would equate to "find all the things less than 10m away from (0,0)"</p> <p>Try...
2
2016-09-30T18:56:01Z
39,849,952
<p><strong>No, there isn't.</strong></p> <p>The search API doesn't support arbitrarily computed expressions on fields (like <code>x * x</code> in your example). What it does support is enumerated <a href="https://cloud.google.com/appengine/docs/python/search/query_strings" rel="nofollow">here</a>. Your mapping from Ca...
1
2016-10-04T10:29:08Z
[ "python", "google-app-engine", "google-cloud-platform" ]
Executing related os commands in python
39,798,453
<p>I'm trying to create a simple script in python which is essentially a shell terminal. It will repeatedly ask for input commands and will attempt to execute the given os commands. What I cannot figure out, is how to make Python 'remember' the commands that were executed.</p> <p>Example of what I mean:</p> <ol> <li>...
0
2016-09-30T19:03:46Z
39,798,507
<p>you cant <code>cd</code> out with the <code>subprocess</code> module, the function will run but the path wont change for the python script that is running,<br> what you can do instead is something like:</p> <pre><code>import os if # condition where cd command used: os.chdir("path/to/new/dir") </code></pre> <p>th...
1
2016-09-30T19:08:02Z
[ "python", "linux", "shell", "command", "subprocess" ]
Executing related os commands in python
39,798,453
<p>I'm trying to create a simple script in python which is essentially a shell terminal. It will repeatedly ask for input commands and will attempt to execute the given os commands. What I cannot figure out, is how to make Python 'remember' the commands that were executed.</p> <p>Example of what I mean:</p> <ol> <li>...
0
2016-09-30T19:03:46Z
39,798,917
<p>The thing that you have to understand is: you want to write a <strong>full</strong> interpreter of shell commands. That means: any command that alters the <strong>state</strong> of your <strong>shell</strong> ... needs to well, change some internal state. </p> <p>Meaning: your python "interpreter" starts within a c...
0
2016-09-30T19:36:22Z
[ "python", "linux", "shell", "command", "subprocess" ]
Data Validation Using Functions
39,798,473
<p>How do I create a function that validates the following?</p> <pre><code>def get_order(): order=int(input("Select an item number: ")) return order </code></pre> <p>I tried this:</p> <pre><code>def validate_order(order_choice): order_choice=get_order() return order_choice while order_choice &lt;...
2
2016-09-30T19:05:13Z
39,798,954
<p>I'm going to assume you want to validate that the order number is indeed an integer.</p> <p>To do this we will use the <code>isinstance()</code> function. Which accepts a variable and a type and returns <code>True</code> or <code>False</code> depending on whether or not it matches the second argument.</p> <p>In yo...
0
2016-09-30T19:39:05Z
[ "python", "function", "validation" ]
Data Validation Using Functions
39,798,473
<p>How do I create a function that validates the following?</p> <pre><code>def get_order(): order=int(input("Select an item number: ")) return order </code></pre> <p>I tried this:</p> <pre><code>def validate_order(order_choice): order_choice=get_order() return order_choice while order_choice &lt;...
2
2016-09-30T19:05:13Z
39,799,176
<pre><code>def get_order(): order=int(input("Select an item number: ")) return order </code></pre> <p>The validation:</p> <pre><code>def validate_order(order_choice): order_choice=get_order() while order_choice &lt; 1 or order_choice &gt; 8: order_choice=int(input("Invalid value. Re-enter item...
0
2016-09-30T19:55:14Z
[ "python", "function", "validation" ]
Set string in 'A' python script from 'B' python script
39,798,530
<p>I have two scripts: </p> <p>A.py (is TK window)</p> <pre><code>def function(): string = StringVar() string.set("Hello I'm A.py") </code></pre> <p>From B.py I wish change string that appear in Tk window.</p> <pre><code>def changestring(): string.set("Hello I'm B.py") </code></pre> <p>Obviously don't ...
-1
2016-09-30T19:09:45Z
39,799,903
<p>Variables have scopes. You cannot access variables which are in the scope of one function from another function.</p> <p>There has to be some common point in the code which "knows" about A and about B. That code should pass the variables from one to the other.</p> <p>Based on this comment:</p> <blockquote> <p>A....
2
2016-09-30T20:51:19Z
[ "python", "function", "variables", "tk" ]
Python dict key with max value
39,798,560
<p>I have a dictionary with IP addresses and their free memory space. I'm trying to save an IP to one variable and the next highest one to another variable. </p> <pre><code>masterdict: {'192.168.100.102': '1620', '192.168.100.103': '470', '192.168.100.101': '1615'} print masterdict rmip = max(masterdict, key=master...
0
2016-09-30T19:12:21Z
39,798,598
<p>The values in your dictionary are strings so <code>max</code> is comparing them as strings. If you want to compare them as integers, then you need to use the key function to convert the strings to integers...:</p> <pre><code>rmip = max(masterdict, key=lambda key: int(masterdict[key]) </code></pre> <p>Or change th...
4
2016-09-30T19:15:20Z
[ "python", "dictionary" ]
Take union of two columns, Python + Pandas
39,798,594
<p>I have a df arranged like follows:</p> <pre><code> x y z 0 a jj Nan 1 b ii mm 2 c kk nn 3 d ii NaN 4 e Nan oo 5 f jj mm 6 g Nan nn </code></pre> <p>The desired output is:</p> <pre><code> x y z w 0 a jj Nan a 1 b ii mm a 2 c kk nn c 3 d ii Na...
4
2016-09-30T19:14:56Z
39,799,676
<p>This one is tricky!</p> <p>I first evaluate which elements share the same <code>'y'</code> values as it's neighbor.<br> Then I check who has the same <code>'z'</code> as their neighbor.<br> A new group is when neither of these things are true.</p> <pre><code>y_chk = df.y.eq(df.y.shift()) z_chk = df.z.eq(df.z.shift...
3
2016-09-30T20:33:57Z
[ "python", "pandas" ]
Take union of two columns, Python + Pandas
39,798,594
<p>I have a df arranged like follows:</p> <pre><code> x y z 0 a jj Nan 1 b ii mm 2 c kk nn 3 d ii NaN 4 e Nan oo 5 f jj mm 6 g Nan nn </code></pre> <p>The desired output is:</p> <pre><code> x y z w 0 a jj Nan a 1 b ii mm a 2 c kk nn c 3 d ii Na...
4
2016-09-30T19:14:56Z
39,804,570
<p>Make all null strings as <code>NaN</code> values by replacing them. Next, group them according to 'y' and fill all the missing values with the value corresponding to it's first valid index present in 'z'. </p> <p>Then, perform groupby operation on 'z', by applying sum which aggregates all the values present in 'x' ...
1
2016-10-01T08:34:30Z
[ "python", "pandas" ]
Take union of two columns, Python + Pandas
39,798,594
<p>I have a df arranged like follows:</p> <pre><code> x y z 0 a jj Nan 1 b ii mm 2 c kk nn 3 d ii NaN 4 e Nan oo 5 f jj mm 6 g Nan nn </code></pre> <p>The desired output is:</p> <pre><code> x y z w 0 a jj Nan a 1 b ii mm a 2 c kk nn c 3 d ii Na...
4
2016-09-30T19:14:56Z
39,809,512
<p>In the general case this is a set consolidation/connected components problem. While if we assume certain things about your data we can solve a reduced case, it's just a bit of bookkeeping to do the whole thing.</p> <p>scipy has a connected components function we can use if we do some preparation:</p> <pre><code>i...
2
2016-10-01T17:26:12Z
[ "python", "pandas" ]
UTF-8 characters usage in python3.4 script is throwing SyntaxError. How to use it?
39,798,615
<p>I am trying execute following lines of code in python3.4:</p> <pre><code>user ="ŠŒŽ‡†ƒ€‰" print(user) </code></pre> <p>But the above user initialization line is resulting in following error:</p> <pre><code>SyntaxError: (unicode error) 'utf-8' codec can't decode byte 0x8a in position 0: invalid start ...
0
2016-09-30T19:16:22Z
39,799,151
<p>Your file is not actually saved in UTF-8. Assuming that the syntax error is occurring on the first non-ASCII character (<code>Å </code>), the file is most likely encoded in <a href="https://en.wikipedia.org/wiki/Windows-1252" rel="nofollow">Windows 1252</a>, which encodes that character as 0x8A. If you wish to con...
4
2016-09-30T19:53:17Z
[ "python", "python-3.x", "utf-8" ]
BeautifulSoup - Misspelled Class
39,798,712
<p>I am attempting to scrape location data from <a href="https://www.wellstar.org/locations/pages/default.aspx" rel="nofollow">https://www.wellstar.org/locations/pages/default.aspx</a> and while I was inspecting the source, I noticed that the class for the hospital's address is sometimes spelled with an extra 'd' - 'ad...
2
2016-09-30T19:23:58Z
39,798,775
<p><code>BeautifulSoup</code> is great at adapting, you can use a regular expression:</p> <pre><code>for address in table.find_all("div", class_=re.compile(r"WS_Location_Ad{2,}ress")): </code></pre> <p>where <code>d{2,}</code> would match <code>d</code> 2 or more times.</p> <hr> <p>Or, you can just specify a <em>li...
2
2016-09-30T19:27:42Z
[ "python", "web-scraping", "beautifulsoup" ]
flask-sockets and ZeroMQ
39,798,788
<p>I'm playing around with getting <code>zeromq</code> pub/sub messages sent up to a browser with a websocket. The following "works", in that messages do get sent up through a websocket. However, trying to reload the page just hangs, as I'm guessing the <code>while True</code> loop is blocking. I thought that the <code...
0
2016-09-30T19:28:22Z
39,798,888
<p>Nevermind, just realized need to do </p> <pre><code>import zmq.green as zmq </code></pre> <p>in order to use with gevent compatibility. <a href="https://pyzmq.readthedocs.io/en/latest/api/zmq.green.html" rel="nofollow">Here's a link to pyZeormq docs.</a></p>
0
2016-09-30T19:34:34Z
[ "python", "zeromq", "flask-sockets" ]
Django - filter model
39,798,840
<p>I have a model with a field that is a list. For example:</p> <pre><code>mymodel.sessions = [session1, session2] </code></pre> <p>I need a query to get all <code>mymodels</code> that <code>session1</code> is exist their sessions.</p> <p>The model`s field looks like that</p> <pre><code>sessions = models.ForeignKey...
2
2016-09-30T19:31:24Z
39,799,018
<p>You can use reverse lookups that go back along the foreign key to query for values in the related model.</p> <pre><code>MyModel.objects.filter(sessions__id=1) </code></pre> <p>That will filter all <code>MyModel</code>s that have a foreign key to a session with an <code>id</code> of 1.</p> <p>For more information ...
0
2016-09-30T19:43:28Z
[ "python", "django", "django-models" ]
Django - filter model
39,798,840
<p>I have a model with a field that is a list. For example:</p> <pre><code>mymodel.sessions = [session1, session2] </code></pre> <p>I need a query to get all <code>mymodels</code> that <code>session1</code> is exist their sessions.</p> <p>The model`s field looks like that</p> <pre><code>sessions = models.ForeignKey...
2
2016-09-30T19:31:24Z
39,799,086
<p>From the <a href="https://docs.djangoproject.com/en/1.10/ref/models/querysets/#django.db.models.query.QuerySet.filter" rel="nofollow">Django docs for <code>filter</code></a>:</p> <blockquote> <p><code>filter(**kwargs)</code></p> <p>Returns a new QuerySet containing objects that match the given lookup paramet...
0
2016-09-30T19:48:30Z
[ "python", "django", "django-models" ]
Breaking out of while True loop
39,798,918
<p>I have a python script which will parse xml file for serial numbers and will write them to a text file. The problem with the below code is, It is going on infinite loop. If I am adding a break statement some where after logging to a file, It is writing only one serial number. How do I increase the counter, so that t...
1
2016-09-30T19:36:25Z
39,799,085
<p>I would normally create a flag so that the while would be</p> <pre><code>while working == True: </code></pre> <p>Then reset the flag at the appropriate time.</p> <p>This allows you to use the <code>else</code> statement to close the text file and output the final results after the while loop is complete. <a href=...
1
2016-09-30T19:48:28Z
[ "python", "xml", "while-loop", "break" ]
Breaking out of while True loop
39,798,918
<p>I have a python script which will parse xml file for serial numbers and will write them to a text file. The problem with the below code is, It is going on infinite loop. If I am adding a break statement some where after logging to a file, It is writing only one serial number. How do I increase the counter, so that t...
1
2016-09-30T19:36:25Z
39,799,426
<p>If your s.recvfrom(65507) is working correctly it should be an easy fix. Write this code just below your <code>data, addr = s.recvfrom(65507)</code></p> <pre><code>if not data: break </code></pre>
0
2016-09-30T20:15:22Z
[ "python", "xml", "while-loop", "break" ]
Breaking out of while True loop
39,798,918
<p>I have a python script which will parse xml file for serial numbers and will write them to a text file. The problem with the below code is, It is going on infinite loop. If I am adding a break statement some where after logging to a file, It is writing only one serial number. How do I increase the counter, so that t...
1
2016-09-30T19:36:25Z
39,800,539
<p>You open a <code>UDP</code> socket and you use <code>recvfrom</code> to get data from the socket.<br> You set a high <code>timeout</code> which makes this function a <code>blocking function</code>. It means when you start listening on the socket, if no data have been sent from the sender your program will be blocked...
0
2016-09-30T21:48:16Z
[ "python", "xml", "while-loop", "break" ]
Cumulative Sum List
39,798,962
<p>I'm trying to create a cumulative list, but my output clearly isn't cumulative. Does anyone know what I'm doing wrong? Thanks</p> <pre><code>import numpy as np import math import random l=[] for i in range (50): def nextTime(rateParameter): return -math.log(1.0 - random.random()) / rateParameter a ...
0
2016-09-30T19:39:33Z
39,799,016
<p>The cumulative sum is not taken <em>in place</em>, you have to assign the return value:</p> <pre><code>cum_l = np.cumsum(l) print(cum_l) </code></pre> <p>You don't need to place that function in the <code>for</code> loop. Putting it outside will avoid defining a new function at every iteration and your code will s...
1
2016-09-30T19:43:27Z
[ "python", "numpy", "cumsum" ]
Cumulative Sum List
39,798,962
<p>I'm trying to create a cumulative list, but my output clearly isn't cumulative. Does anyone know what I'm doing wrong? Thanks</p> <pre><code>import numpy as np import math import random l=[] for i in range (50): def nextTime(rateParameter): return -math.log(1.0 - random.random()) / rateParameter a ...
0
2016-09-30T19:39:33Z
39,799,192
<p>If you are using <code>numpy</code> then <code>numpy</code> is the way to go, however, if all you need to do is provide a cumulative sum then Python3 comes with <code>itertools.accumulate</code>:</p> <pre><code>def nextTime(rateParameter): while True: yield -math.log(1.0 - random.random()) / rateParamet...
0
2016-09-30T19:56:42Z
[ "python", "numpy", "cumsum" ]
Creating bytesIO object
39,799,009
<p>I am working on a <a href="https://en.wikipedia.org/wiki/Scrapy" rel="nofollow">Scrapy</a> spider, trying to extract the text from multiple PDF files in a directory, using <a href="https://pypi.python.org/pypi/slate" rel="nofollow">slate</a>. I have no interest in saving the actual PDF to disk, and so I've been advi...
0
2016-09-30T19:43:08Z
39,799,090
<p>When you do <code>in_memory_pdf.read(response.body)</code> you are supposed to pass the number of bytes to read. You want to initialize the buffer, not read into it.</p> <p>In python 2, just initialize <code>BytesIO</code> as:</p> <pre><code> in_memory_pdf = BytesIO(response.body) </code></pre> <p>In Python 3, yo...
1
2016-09-30T19:48:49Z
[ "python", "pdf" ]
Run python commands in parallel in Linux shell scripting
39,799,057
<p>I have a script which gets input from the user through command line arguments. It processes the arguments and starts running python commands. For Example:</p> <pre><code>./run.sh p1 p2 p3 p4 python abc.py p1 p4 python xyz.py p2 p3 </code></pre> <p>where <code>p1</code>, <code>p2</code>, <code>p3</code> and <code>...
1
2016-09-30T19:46:19Z
39,799,144
<p>Try running each process in the background by adding <code>&amp;</code> to the end of the command.</p> <pre><code>python abc.py p1 p4 &amp; python xyz.py p2 p3 &amp; </code></pre> <p><a href="http://www.hacktux.com/bash/ampersand" rel="nofollow">Some Info</a></p>
1
2016-09-30T19:52:49Z
[ "python", "linux", "shell" ]
Run python commands in parallel in Linux shell scripting
39,799,057
<p>I have a script which gets input from the user through command line arguments. It processes the arguments and starts running python commands. For Example:</p> <pre><code>./run.sh p1 p2 p3 p4 python abc.py p1 p4 python xyz.py p2 p3 </code></pre> <p>where <code>p1</code>, <code>p2</code>, <code>p3</code> and <code>...
1
2016-09-30T19:46:19Z
39,804,333
<p>Your task is not where GNU Parallel excels, but it can be done:</p> <pre><code>parallel ::: "python abc.py p1 p4" "python xyz.py p2 p3" </code></pre>
0
2016-10-01T08:02:32Z
[ "python", "linux", "shell" ]
Form data is storing in database when using jQuery
39,799,074
<p>i was trying to use jquery to load form when value of drop down change .it loading the form but after submitting data is not storing in database . it just refreshes the page.</p> <blockquote> <p>forms.py</p> </blockquote> <pre><code>class accountForm(forms.ModelForm): choice = ( ('payment type','paym...
0
2016-09-30T19:47:49Z
39,799,213
<p>Where is the implementation for your forms.save()? Describe how save() is implemented in forms model. It could be somewhere there or If you are using any service like Amazon AWS and botto as interface, the issue could be in these two places also.</p> <p>Obviously you have only printed the form and you are using Htt...
0
2016-09-30T19:58:07Z
[ "jquery", "python", "django", "django-forms", "django-views" ]
Python regex find all substrings between two character pairs
39,799,096
<p>I have tried previous answers here on SO. I was able to find only one subset of several. </p> <p>here is the code and sample that I am working on.</p> <pre><code>s = "{| mySting0 |} The {| mySting1 |} The {| mySting2 |} The {| mySting3 |} make it work " result = re.findall('{\|(.*)|}', s) </code></pre> <p>th...
0
2016-09-30T19:49:22Z
39,799,123
<p>You can use this regex:</p> <pre><code>&gt;&gt;&gt; s = "{| mySting0 |} The {| mySting1 |} The {| mySting2 |} The {| mySting3 |} make it work " &gt;&gt;&gt; re.findall(r'{\|(.*?)\|}', s) [' mySting0 ', ' mySting1 ', ' mySting2 ', ' mySting3 '] </code></pre> <p><strong>Changes are:</strong></p> <ol> <li>Use la...
3
2016-09-30T19:50:58Z
[ "python", "regex" ]
Python simple email validity check
39,799,159
<p>In Python, if i wanted to write something that returns a boolean True as long as the @ symbol appears after the . symbol, how would I write this? </p> <p>I have tried writing something like:</p> <pre><code>if myString[x] == "@" &gt; myString[x] == ".": return True </code></pre> <p>but, I assume that this won...
-1
2016-09-30T19:53:47Z
39,799,193
<pre><code>if str.index('@') &gt; str.index('.'): return True; </code></pre>
1
2016-09-30T19:56:48Z
[ "python" ]
Python simple email validity check
39,799,159
<p>In Python, if i wanted to write something that returns a boolean True as long as the @ symbol appears after the . symbol, how would I write this? </p> <p>I have tried writing something like:</p> <pre><code>if myString[x] == "@" &gt; myString[x] == ".": return True </code></pre> <p>but, I assume that this won...
-1
2016-09-30T19:53:47Z
39,799,203
<p>You could use a simple regular expression:</p> <pre><code>import re rx = re.compile(r'\S+@\S+') string = """This text contains an email@address.com somewhere""" if rx.search(string): print("Somewhere in there is an email address") </code></pre> <p>See <a href="http://ideone.com/7FpfgH" rel="nofollow"><stron...
1
2016-09-30T19:57:31Z
[ "python" ]
Python simple email validity check
39,799,159
<p>In Python, if i wanted to write something that returns a boolean True as long as the @ symbol appears after the . symbol, how would I write this? </p> <p>I have tried writing something like:</p> <pre><code>if myString[x] == "@" &gt; myString[x] == ".": return True </code></pre> <p>but, I assume that this won...
-1
2016-09-30T19:53:47Z
39,799,341
<p><code>return str.find('@') &gt; str.find('.') and str.find('.') &gt; -1</code></p> <p>This will check that <code>@</code> is after <code>.</code>, and that both symbols are present in the string. This is however a <strong>very</strong> bad way to check for email validity.</p>
1
2016-09-30T20:07:19Z
[ "python" ]
concatenate next to string if string found
39,799,240
<p>I'm trying to search through my strings then concatenate the string.</p> <pre><code>string = ' &lt;html&gt;&lt;body&gt;&lt;svg style="background: #40484b;" version="1.1" viewbox="0 0 400 150" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"&gt; &lt;defs&gt; &lt;!-- if you use...
0
2016-09-30T20:00:20Z
39,799,305
<p>You can concatenate strings with the <code>+</code> symbol.</p> <pre><code>&gt;&gt;&gt; 'foo' + 'bar' 'foobar' </code></pre>
0
2016-09-30T20:04:24Z
[ "python", "string", "parsing", "concatenation" ]
concatenate next to string if string found
39,799,240
<p>I'm trying to search through my strings then concatenate the string.</p> <pre><code>string = ' &lt;html&gt;&lt;body&gt;&lt;svg style="background: #40484b;" version="1.1" viewbox="0 0 400 150" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"&gt; &lt;defs&gt; &lt;!-- if you use...
0
2016-09-30T20:00:20Z
39,799,403
<p>To insert additional string in your string variable <code>html</code>, you can do something like this:</p> <pre><code>import re html = '&lt;html&gt; ... &lt;defs&gt;&lt;-- inserts will go here --&gt; ... &lt;/html&gt;' insert = 'this line gets inserted' html = re.sub(r'(.*?&lt;defs&gt;)(.*)', r'\g&lt;1&gt;' + inser...
0
2016-09-30T20:12:53Z
[ "python", "string", "parsing", "concatenation" ]
concatenate next to string if string found
39,799,240
<p>I'm trying to search through my strings then concatenate the string.</p> <pre><code>string = ' &lt;html&gt;&lt;body&gt;&lt;svg style="background: #40484b;" version="1.1" viewbox="0 0 400 150" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"&gt; &lt;defs&gt; &lt;!-- if you use...
0
2016-09-30T20:00:20Z
39,799,511
<p>For a string with multiple lines you should use triple single quotes or triple double quotes. And instead of "if" statement you better use a "for" loop.</p>
1
2016-09-30T20:20:57Z
[ "python", "string", "parsing", "concatenation" ]
Jinja2 Specify Route REST Type
39,799,290
<p>My question is can I specify the type of REST route in Jinja2, for example if I have the route:</p> <pre><code>RedirectRoute('/&lt;id&gt;/somthing/&lt;key&gt;', myFile.Handler, name='name', strict_slash=True), </code></pre> <hr> <pre><code>class Handler(JSONHandler): def get(): ... def delete(): ... def pos...
0
2016-09-30T20:03:21Z
39,800,067
<p>If I understand what you're asking, you have an endpoint which respond to the methods GET, POST, and DELETE and you want to know if you can make the HTML resulting from Jinja send a DELETE request your endpoint.</p> <p>The short answer is no. DELETE must always be performed by JavaScript and AJAX. The only methods ...
1
2016-09-30T21:03:45Z
[ "python", "html", "jinja2" ]
Deprecation warning on 13 dimentional array
39,799,325
<p>I have my sample data arranged in a matrix of dimension 216,13 where 216 are number of samples and 13 are features. I am fitting that in K-NN algorithm and when I predict this with 1,13 matrix I keep in getting a warning</p> <blockquote> <p><em>DeprecationWarning: Passing 1d arrays as data is deprecated in 0.17 ...
0
2016-09-30T20:06:07Z
39,800,533
<p>Ans1: use <code>x[0]</code> and <code>y[0]</code> instead of x,y.</p> <p>Your question asks to know why. You are not looking for any answer as your solution already works. Thus here is the explanation:</p> <p>You are using a 1D array not a 13D array. You have posted question in totally confusing manner too.</p> ...
0
2016-09-30T21:48:06Z
[ "python", "scikit-learn" ]
Deprecation warning on 13 dimentional array
39,799,325
<p>I have my sample data arranged in a matrix of dimension 216,13 where 216 are number of samples and 13 are features. I am fitting that in K-NN algorithm and when I predict this with 1,13 matrix I keep in getting a warning</p> <blockquote> <p><em>DeprecationWarning: Passing 1d arrays as data is deprecated in 0.17 ...
0
2016-09-30T20:06:07Z
39,800,681
<p>The problem is that you are passing a 1d array to <code>clf.kneighbors(test)</code>. Actually, you are using a list, which will implicitly get converted to a numpy array. Anyway, the following should solve the issue, as per the warning:</p> <pre><code>In [14]: arr = np.array(test) In [15]: arr.shape Out[15]: (13,)...
0
2016-09-30T22:01:39Z
[ "python", "scikit-learn" ]
Accessing bytesIO object after creation
39,799,427
<p>I am working on a scrapy spider, trying to extract text multiple pdfs in a directory, using slate (<a href="https://pypi.python.org/pypi/slate" rel="nofollow">https://pypi.python.org/pypi/slate</a>). I have no interest in saving the actual PDF to disk , and so I've been advised to look into the io.bytesIO subclass a...
0
2016-09-30T20:15:26Z
39,799,545
<p>You already know the answer. It is clearly mentioned in the Python TypeError message and clear from the documentation:</p> <pre><code>class io.BytesIO([initial_bytes]) </code></pre> <p>BytesIO accepts bytes. And you are passing it contents. i.e: response.body which is a string.</p>
1
2016-09-30T20:24:04Z
[ "python", "pdf" ]
Padding zeros into list at specific positions
39,799,455
<p>Given two lists of different length, but with mostly similar (or overlapping) values such as:</p> <pre><code>ls_1 = [7, 26, 26, 55, 69, 71, 73, 80, 121, 124, 126, 127, 131, 133, 144, 153, 153, 159, 160, 210, 219, 221, 235, 235, 241, 243, 289, 299, 300, 309, 327, 327, 328, 391, 419, 421, 4...
0
2016-09-30T20:17:32Z
39,799,527
<pre><code>ls_2.insert(ls_2.index(81), 0) </code></pre> <p>will insert a zero before the value <code>81</code>, just repeat and you have your two zeros. Cache the result of <code>ls_2.index(81)</code> in a variable to speed things up little.</p>
0
2016-09-30T20:22:25Z
[ "python", "sorting", "padding" ]
Padding zeros into list at specific positions
39,799,455
<p>Given two lists of different length, but with mostly similar (or overlapping) values such as:</p> <pre><code>ls_1 = [7, 26, 26, 55, 69, 71, 73, 80, 121, 124, 126, 127, 131, 133, 144, 153, 153, 159, 160, 210, 219, 221, 235, 235, 241, 243, 289, 299, 300, 309, 327, 327, 328, 391, 419, 421, 4...
0
2016-09-30T20:17:32Z
39,800,099
<p>Go about it by adding 0s at the end of your <code>ls_2</code>. Not in between as you have pointed out. This reduces a lot of complexity.</p> <p>Something like:</p> <pre><code>ls_1_length = len(ls_1) ls_2_length = len(ls_2) length_diff = ls_1_length - ls_2_length for index in length_diff: ls_2.append(0) </code>...
0
2016-09-30T21:05:59Z
[ "python", "sorting", "padding" ]
Defining Multivariate Gaussian Function for Quadrature with Scipy
39,799,523
<p>I'm having some trouble defining a multivariate gaussian pdf for quadrature using scipy. I write a function that takes a mean vector and covariance matrix as input and returns a gaussian function.</p> <pre><code>def make_mvn_pdf(mu, sigma): def f(x): return sp.stats.multivariate_normal.pdf(x, mu, sigma)...
0
2016-09-30T20:22:17Z
39,800,551
<p>The value that you give as the mean is <code>np.dot(B, Obs)</code> (taking into account the change you suggested in a comment), where <code>B</code> has shape (2, 2) and <code>Obs</code> has shape (2, 1). The result of that <code>dot</code> call has shape (2, 1). The problem is that is a <em>two</em>-dimensional a...
1
2016-09-30T21:49:28Z
[ "python", "scipy", "statistics", "gaussian", "numerical-integration" ]
Cython code runs 125x slower when compiled against python 2 vs python 3
39,799,524
<p>I have a big block of Cython code that is parsing <a href="http://ibis.org/interconnect_wip/touchstone_spec2_draft3.pdf" rel="nofollow">Touchstone files</a> that I want to work with Python 2 and Python 3. I'm using very C-style parsing techniques for what I thought would be maximum efficiency, including manually ma...
2
2016-09-30T20:22:17Z
39,838,264
<p>The problem is with <code>strtod</code>, which is not <a href="http://www.ryanjuckett.com/programming/optimizing-atof-and-strtod/" rel="nofollow">optimized in VS2008</a>. Apparently it internally calculates the length of the input string each time its called, and if you call it with a long string this will slow dow...
1
2016-10-03T18:38:18Z
[ "python", "python-2.7", "cython" ]
specifying string types in cython code
39,799,571
<p>I'm doing some experimentation with cython and I came across some unexpected behavior: </p> <pre><code>In [1]: %load_ext cython In [2]: %%cython ...: cdef class foo(object): ...: cdef public char* val ...: def __init__(self, char* val): ...: self.val = val ...: In [3]: f = foo('aaa'...
2
2016-09-30T20:25:50Z
39,800,829
<p>When you convert a Python bytestring to a <code>char *</code> in Cython, Cython gives you a pointer to the contents of the string object. This raw pointer does not affect the string's Python refcount (it'd be infeasible to track which pointers refer to which strings).</p> <p>When the string's refcount hits zero and...
2
2016-09-30T22:15:21Z
[ "python", "cython" ]
SqlAlchemy issues with foreign keys
39,799,616
<p>I am getting the error </p> <blockquote> <p>Could not parse rfc1738 URL from string 'MACHINE_IE'</p> </blockquote> <p>When I attempt to import the following</p> <pre><code>class MACHINE(declarative_base()): __tablename__ = 'MACHINE' MACHINE_UID = Column(Integer, primary_key=True) MACHINE_IP = Column...
0
2016-09-30T20:29:17Z
39,799,806
<p>You are using multiple instances of <code>Base</code>. You should be doing:</p> <pre><code>Base = declarative_base() class MACHINE(Base): ... class IE(Base): ... ... </code></pre>
1
2016-09-30T20:44:23Z
[ "python", "sqlalchemy" ]
Merging two dataframes only at specific times
39,799,712
<p>I have two excel files that I'm trying to merge into one using <code>pandas</code>. The first file is a list of times and dates with a subscriber count for that given time and day. The second file has weather information on an hourly basis. I import both files and the data resembles:</p> <pre><code>df1= Date ...
2
2016-09-30T20:36:41Z
39,799,843
<p>Use a combination of <code>reindex</code> to get <code>df2</code> aligned with <code>df1</code>. Make sure to include parameter <code>method='ffill'</code> to forward fill weather information.</p> <p>Then use <code>join</code></p> <pre><code>df1.join(df2.set_index('Date').reindex(df1.Date, method='ffill'), on='Da...
2
2016-09-30T20:47:11Z
[ "python", "pandas" ]
Using arithmetic equations in Python
39,799,747
<p>is there a way to round the value down to the lowest integer for this?</p> <pre><code>x = 5.5 z = 1 x -= z </code></pre> <p>x is just 4.5 in this case</p> <p>but I want something like this</p> <pre><code>x = int(x - z) </code></pre> <p>which produces x as 4 but i would like to use the '-='</p> <p>is there a w...
-2
2016-09-30T20:40:01Z
39,799,795
<p>No unfortunately there isn't a way to do exactly what you described. Your best option would be to do <code>x=int(x-z)</code> or if you want to round up in the case that <code>x=4.5</code> and preserve the <code>float</code> type, <code>x=round(x-z)</code>. </p>
2
2016-09-30T20:43:14Z
[ "python" ]
Using arithmetic equations in Python
39,799,747
<p>is there a way to round the value down to the lowest integer for this?</p> <pre><code>x = 5.5 z = 1 x -= z </code></pre> <p>x is just 4.5 in this case</p> <p>but I want something like this</p> <pre><code>x = int(x - z) </code></pre> <p>which produces x as 4 but i would like to use the '-='</p> <p>is there a w...
-2
2016-09-30T20:40:01Z
39,799,845
<pre><code>x = 5.5 a = 1 x -= a x = int(x) </code></pre> <p>Try this. It will work</p>
0
2016-09-30T20:47:18Z
[ "python" ]
Using arithmetic equations in Python
39,799,747
<p>is there a way to round the value down to the lowest integer for this?</p> <pre><code>x = 5.5 z = 1 x -= z </code></pre> <p>x is just 4.5 in this case</p> <p>but I want something like this</p> <pre><code>x = int(x - z) </code></pre> <p>which produces x as 4 but i would like to use the '-='</p> <p>is there a w...
-2
2016-09-30T20:40:01Z
39,799,911
<p>You can also use a dedicated solution:</p> <pre><code>import math math.floor(x-z) </code></pre> <p>It will always give you lower integer value (in fact it will be a float type but with an integer value).</p> <p>Note that for <code>round(0.7) == 1.0</code>!!</p>
0
2016-09-30T20:52:08Z
[ "python" ]
How to remove frequency from signal
39,799,821
<p>I want to remove one frequency (one peak) from signal and plot my function without it. After fft I found frequency and amplitude and I am not sure what I need to do now. For example I want to remove my highest peak (marked with red dot on plot).</p> <pre><code>import numpy as np import matplotlib.pyplot as plt # c...
3
2016-09-30T20:45:59Z
39,801,000
<p>You can design a bandstop filter:</p> <pre><code>wc = freq[np.argmax(amplitude)] / (0.5 / dt) wp = [wc * 0.9, wc / 0.9] ws = [wc * 0.95, wc / 0.95] b, a = signal.iirdesign(wp, ws, 1, 40) f = signal.filtfilt(b, a, f) </code></pre>
5
2016-09-30T22:32:49Z
[ "python", "numpy", "math", "fft" ]
How to remove frequency from signal
39,799,821
<p>I want to remove one frequency (one peak) from signal and plot my function without it. After fft I found frequency and amplitude and I am not sure what I need to do now. For example I want to remove my highest peak (marked with red dot on plot).</p> <pre><code>import numpy as np import matplotlib.pyplot as plt # c...
3
2016-09-30T20:45:59Z
39,801,665
<p>I wanted something like this. I know that there is better solution but my hacked works. :) Second peak is removed.</p> <pre><code>import numpy as np import matplotlib.pyplot as plt from scipy.fftpack import rfft, irfft, fftfreq, fft import scipy.fftpack # Number of samplepoints N = 500 # sample spacing T = 0.1 x ...
1
2016-10-01T00:06:53Z
[ "python", "numpy", "math", "fft" ]
converting an object to float in pandas along with replacing a $ sign
39,799,859
<p>I am fairly new to Pandas and I am working on project where I have a column that looks like the following:</p> <pre><code>AverageTotalPayments $7064.38 $7455.75 $6921.90 ETC </code></pre> <p>I am trying to get the cost factor out of it where the cost could be anything above 7000. First, this colum...
2
2016-09-30T20:48:18Z
39,799,920
<p>Consider the <code>pd.Series</code> <code>s</code></p> <pre><code>s 0 $7064.38 1 $7455.75 2 $6921.90 Name: AverageTotalPayments, dtype: object </code></pre> <p>This gets the float values</p> <pre><code>pd.to_numeric(s.str.replace('$', ''), 'ignore') 0 7064.38 1 7455.75 2 6921.90 Name: AverageT...
2
2016-09-30T20:52:34Z
[ "python", "pandas", "data-science" ]
converting an object to float in pandas along with replacing a $ sign
39,799,859
<p>I am fairly new to Pandas and I am working on project where I have a column that looks like the following:</p> <pre><code>AverageTotalPayments $7064.38 $7455.75 $6921.90 ETC </code></pre> <p>I am trying to get the cost factor out of it where the cost could be anything above 7000. First, this colum...
2
2016-09-30T20:48:18Z
39,799,927
<p>Try this:</p> <pre><code>In [83]: df Out[83]: AverageTotalPayments 0 $7064.38 1 $7455.75 2 $6921.90 3 aaa In [84]: df.AverageTotalPayments.str.extract(r'.*?(\d+\.*\d*)', expand=False).astype(float) &gt; 7000 Out[84]: 0 True 1 True 2 False 3 False...
2
2016-09-30T20:53:00Z
[ "python", "pandas", "data-science" ]
How can I use x, y coordinate matrices to choose where a character appears in a string with python?
39,799,890
<p>I am attempting to make a simple maze game to test a NNS with genetic algorithms. the maze for each test would use a matrix to hold the x, y points of things like barriers, the start, the end, and the player's current position. The main thing that I need help with is placing the right character in the right location...
-1
2016-09-30T20:50:36Z
39,800,059
<p>You're probably looking for something along the lines of this:</p> <pre><code>width = 6 height = 6 coords = [(1,1),(3,4),(1,5)] print('\n'.join(['|' + ''.join(['x' if (x,y) in coords else 'o' for x in range(width)]) + '|' for y in range(height)])) </code></pre> <p>Using list comprehension, we can easily construct ...
0
2016-09-30T21:03:26Z
[ "python", "arrays", "string", "matrix", "coordinate" ]
Install Paramiko on my Mac OS X 10.11
39,799,891
<p>I tried to install paramiko on my Mac OS X 10.11</p> <p>sudo pip install paramiko</p> <p>Password:*******</p> <p>then I got </p> <pre><code>The directory '/Users/bheng/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions a...
1
2016-09-30T20:50:39Z
39,806,539
<p>Try <code>sudo chown $(whoami) /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/_markerlib/</code> Then do the same for any directories that Python doesn't have permissions for.</p> <p>Recent versions of OSX and macOS have a system called System Integrity Protection that means that some di...
2
2016-10-01T12:21:11Z
[ "python", "osx", "paramiko" ]
How to serialize a single model instance AND include the primary key
39,799,893
<p>I have a single model instance <code>obj</code>. I want to serialize it, and for the primary key to be included in the serialized data.</p> <ul> <li><p><code>django.core.serializers.serializer</code> wants a queryset (throws an error that <code>ojb</code> isn't iterable).</p></li> <li><p>I simply cannot coerce <cod...
0
2016-09-30T20:50:49Z
39,803,866
<p><code>model_to_dict</code> will not dump fields that have <code>editable=False</code> (so, for example, the primary key). It is possible to manually construct the object serialization by:</p> <pre><code>{field.name: field.value_from_object(obj) for field in obj._meta.fields} </code></pre>
0
2016-10-01T06:57:08Z
[ "python", "django", "serialization" ]
Dynamic method binding with inheritance in Python
39,799,973
<p>I am new to python (~ a month), and I wish I had switched to it sooner (after years of perl). </p> <p><strong>Problem</strong>: I want objects to have different functionality to the same method call based on their type. The methods are assigned at runtime, based on the module loaded (which composes all objects).</...
0
2016-09-30T20:56:49Z
39,800,961
<h2>Problem Summary</h2> <p>Ignoring the irrelevant details, the problems here can be summed up as follows:</p> <p>There is one base class and many derived classes. There is a certain functionality which should apply to all of the derived classes, but depends on some external switch (in the question: choice of <em>"<...
0
2016-09-30T22:28:08Z
[ "python", "design-patterns", "visitor" ]
How is a page instance's slug defined in Mezzanine CMS?
39,800,065
<p>From the <a href="https://github.com/stephenmcd/mezzanine/blob/master/docs/content-architecture.rst" rel="nofollow">Mezzanine docs</a>:</p> <blockquote> <p>By default the template pages/page.html is used, but if a custom template exists it will be used instead. The check for a custom template will first check for...
2
2016-09-30T21:03:38Z
39,800,201
<p>The slug is automatically generated from the title attribute by default, but it can also be set manually from the "URL" option in the meta data section of the page admin.</p>
1
2016-09-30T21:14:15Z
[ "python", "django", "mezzanine" ]
Extending a C++ application with python
39,800,120
<p>I have a legacy (but still internally maintained) application written in C++ which handles some hardware, interacts with databases, receives commands via serial line or socket... in short it does a non-trivial amount of work.</p> <p>This application runs under Linux (ARM/Buildroot).</p> <p>Now the need is to revam...
0
2016-09-30T21:07:39Z
39,812,790
<p>Can you do it the other way around - embed your C++ code in Python program? This way it would be more prepared for moving existing functionality Python like you said.</p> <p>Python makes a lot of things easier (faster to develop, easier to maintain) - communication with databases, libraries (if hey have Python wrap...
0
2016-10-02T00:33:05Z
[ "python", "c++", "extending", "python-embedding" ]
How to test render_to_response in Pyramid Python
39,800,132
<p>I have a piece of code that calls Pyramid's render_to_response. I am not quite sure how to test that piece. In my test, the request object that is sent in is a DummyRequest by Pyramid. How can I capture <code>to_be_rendered</code>.</p> <pre><code>from pyramid.renderers import render_to_response def custom_adapte...
2
2016-09-30T21:08:25Z
39,812,289
<p>I believe <code>render_to_response</code> should return a <a href="http://docs.pylonsproject.org/projects/pyramid/en/latest/narr/webob.html#response" rel="nofollow">response</a> object. You should be able to call <code>custom_adapter</code> directly in your unit test, providing a <code>DummyRequest</code> and make ...
1
2016-10-01T23:05:41Z
[ "python", "unit-testing", "py.test" ]
Trying to use views in django like I use to used in python
39,800,209
<p>why it does not work ? It suppose to work, in python I can use this like this function, can any one explain me please ?</p> <p><strong>views:</strong></p> <pre><code>class MiVista(View): def get(self, request, var): self.var = 'Hello' # &lt;la logica de la vista&gt; return HttpResponse(...
0
2016-09-30T21:15:08Z
39,801,082
<p>So as @MadWombat mentioned, you are not passing enough arguments, so you need to pass <code>self</code>, which already passing by calling from instance objects, <code>request</code>(not passing), <code>var</code>(passing). And as you are not providing that you are passing <code>var=2222</code>, python thinks that <c...
1
2016-09-30T22:41:44Z
[ "python", "django", "django-views" ]
Accumulate values of "neigborhood" from edgelist with numpy
39,800,223
<p>I have a undirected network where each node can be one of <strong>k</strong> types. For each node <em>i</em>, I need to calculate the number of neighbors that node <em>i</em> has of each type.</p> <p>Right now I am representing the edges with an edgelist where the columns are indexes of the nodes. The nodes are rep...
4
2016-09-30T21:16:18Z
39,805,998
<p>If I understand your question correctly, the <a href="https://pypi.python.org/pypi/numpy-indexed" rel="nofollow">numpy_indexed</a> package (disclaimer: I am its author) has a fast and elegant solution to this:</p> <pre><code># generate a random example graph n_edges = 50 n_nodes = 10 n_types = 3 edges = np.random.r...
2
2016-10-01T11:22:43Z
[ "python", "numpy", "vectorization", "graph-algorithm", "numpy-broadcasting" ]
Accumulate values of "neigborhood" from edgelist with numpy
39,800,223
<p>I have a undirected network where each node can be one of <strong>k</strong> types. For each node <em>i</em>, I need to calculate the number of neighbors that node <em>i</em> has of each type.</p> <p>Right now I am representing the edges with an edgelist where the columns are indexes of the nodes. The nodes are rep...
4
2016-09-30T21:16:18Z
39,840,352
<p>You can simply use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ufunc.at.html" rel="nofollow"><code>np.add.at</code></a> -</p> <pre><code>out = np.zeros_like(nodes) np.add.at(out, edges[:,0],nodes[edges[:,1]]) np.add.at(out, edges[:,1],nodes[edges[:,0]]) </code></pre>
1
2016-10-03T21:00:37Z
[ "python", "numpy", "vectorization", "graph-algorithm", "numpy-broadcasting" ]
Can't access models from seperate: ImportError: no module named "HealthNet.ActivityLog"
39,800,229
<p>I've been working on a way to log the activity of a system for a school project in Python 3.4 and Django 1.9. I am currently trying to import a models.py file from my ActivityLog app into other applications in my HealthNet project to save the activity. The IDE I'm using (Pycharm), is telling me that my code is corre...
0
2016-09-30T21:16:47Z
39,800,312
<pre><code>from ActivityLog.models import Log </code></pre> <p>'ActivityLog' and 'Appointments' are apps. So add 'ActivityLog' and 'Appointments' to INSTALLED_APPS in settings.py</p> <p>For eg: </p> <pre><code> INSTALLED_APPS = [ 'Appointment.apps.AppointmentConfig', 'User.apps.UserConfig', ............
1
2016-09-30T21:25:33Z
[ "python", "django" ]
Python: replace data frame values based on column name and conditional
39,800,232
<p>Let’s say we have a data frame with 6 columns. For a subset of 3 of those columns we want to change instances of 3 to 1. Can you suggest an elegant way to do so? Simply writing a line like:</p> <pre><code>df['A'][df.A == 3] = 1 </code></pre> <p>is inefficient in my real data as the dimensions are much larger (l...
2
2016-09-30T21:16:52Z
39,800,526
<p>You can loop through the subset of columns and use <code>loc</code> for assignment.</p> <pre><code>subset cols = ['A', 'B', 'C'] # For example. for col in subset_cols: df.loc[df[col] == 3, col] = 1 </code></pre>
0
2016-09-30T21:47:30Z
[ "python", "dataframe" ]
Python 2.7 calculating remainder with division and two inputs
39,800,282
<p>It's a question for my assignment in intro to programming and I'm not quite understanding how to do this without the use of Ifs because our prof just wants basic modulus and division. Im trying to get 3 outputs. balloons greater than children (which works), balloons equal to children which just outputs 0 and 0. an...
0
2016-09-30T21:22:09Z
39,800,454
<p>You need to fix your variable assignment, you are assigning to the wrong variables and actually divide the numbers to get <code>receive_balloons</code> correctly:</p> <pre><code>balloons = int(input("Enter number of balloons: ")) children = int(input("Enter the number of children coming to the party: ")) receive_b...
1
2016-09-30T21:39:15Z
[ "python", "python-2.7", "modulus" ]
Python 2.7 calculating remainder with division and two inputs
39,800,282
<p>It's a question for my assignment in intro to programming and I'm not quite understanding how to do this without the use of Ifs because our prof just wants basic modulus and division. Im trying to get 3 outputs. balloons greater than children (which works), balloons equal to children which just outputs 0 and 0. an...
0
2016-09-30T21:22:09Z
39,800,502
<p>You need to use the // operator for the number of balloons per child and % for remaining balloons</p> <pre><code># number of balloons balloons = int(input("Enter number of balloons: ")) # number of children coming to the party children = int(input("Enter the number of children coming to the party: ")) receive_bal...
1
2016-09-30T21:44:18Z
[ "python", "python-2.7", "modulus" ]
python package import works locally, then blows up in cronjob
39,800,373
<p>running a cronjob I get the following error:</p> <pre><code>From cchilders@C02S21TWG8WMMBP.localdomain Fri Sep 30 15:58:00 2016 Return-Path: &lt;cchilders@C02S21TWG8WMMBP.localdomain&gt; X-Original-To: cchilders Delivered-To: cchilders@C02S21TWG8WMMBP.localdomain Received: by C02S21TWG8WMMBP.localdomain (Postfix, ...
0
2016-09-30T21:31:06Z
39,800,523
<p><code>Cron</code> doesn't know which directory is relative to your project, only what is relative to itself. It's likely looking for the modules in some place off in la-la land. A quick fix might be to specify the working directory of the script then try importing the modules:</p> <pre><code>os.chdir("/Users/cchild...
1
2016-09-30T21:47:08Z
[ "python", "bash", "osx", "unix", "crontab" ]
Accesing laptop camera with openCV
39,800,435
<p>I run the following code, according this page - <a href="http://docs.opencv.org/3.0-beta/doc/py_tutorials/py_gui/py_video_display/py_video_display.html" rel="nofollow">http://docs.opencv.org/3.0-beta/doc/py_tutorials/py_gui/py_video_display/py_video_display.html</a></p> <pre><code>cap = cv2.VideoCapture(0) print ca...
0
2016-09-30T21:37:29Z
39,802,980
<p>For OpenCV 2.4, use the following code:</p> <pre><code>import cv2 import cv cap = cv2.VideoCapture(0) while True: ret,img=cap.read() cv2.imshow('Video', img) if(cv2.waitKey(10) &amp; 0xFF == ord('b')): break </code></pre> <p>If you still can't get the camera input, replace VideoCapture(0) with Vid...
0
2016-10-01T04:18:50Z
[ "python", "opencv" ]
Code that generates a random 10 digit filename and creates the file
39,800,513
<p>I tried using:</p> <pre><code>import random filenamemaker = random.randint(1,1000) </code></pre> <p>all help would be great thanks :)</p>
2
2016-09-30T21:45:22Z
39,800,572
<p>The simplest way would be with <a href="https://docs.python.org/3/library/string.html#string.digits" rel="nofollow"><code>string.digits</code></a> and <a href="https://docs.python.org/3/library/random.html#random.sample" rel="nofollow"><code>random.sample</code></a>. You could also use the <a href="https://docs.pyth...
3
2016-09-30T21:52:04Z
[ "python", "python-3.x", "random" ]
Code that generates a random 10 digit filename and creates the file
39,800,513
<p>I tried using:</p> <pre><code>import random filenamemaker = random.randint(1,1000) </code></pre> <p>all help would be great thanks :)</p>
2
2016-09-30T21:45:22Z
39,800,579
<pre><code>import random filename = "" for i in range(10): filename += str(random.randint(0,9)) f = open(filename + ".txt", "w") </code></pre>
0
2016-09-30T21:52:33Z
[ "python", "python-3.x", "random" ]
Code that generates a random 10 digit filename and creates the file
39,800,513
<p>I tried using:</p> <pre><code>import random filenamemaker = random.randint(1,1000) </code></pre> <p>all help would be great thanks :)</p>
2
2016-09-30T21:45:22Z
39,800,588
<p><code>randint</code> takes two arguments: a lower and upper (inclusive) bound for the generated number. Your code will generate a number between 1 and 1000 (inclusive), which could be anywhere from 1 to 4 digits.</p> <p>This will generate a number between 1 and 9999999999:</p> <pre><code>&gt;&gt;&gt; n = random.ra...
0
2016-09-30T21:53:28Z
[ "python", "python-3.x", "random" ]
Stacked Lines in Pandas
39,800,620
<p>I want to draw stacked lines in <code>pandas Dataframe</code>. So, currently I draw one line:</p> <pre><code>df.plot.line(x='xvals',y='yvals') </code></pre> <p>in which <code>xvals</code> column contains <code>x</code> values, and <code>yvals</code> contains <code>y</code> values. </p> <p>How can I add another li...
2
2016-09-30T21:56:42Z
39,800,902
<p>Keep the returned <code>Axes</code> object and pass to <code>ax</code> argument:</p> <pre><code>ax = df.plot.line(x='xvals',y='yvals') df.plot.line(x='xvals2',y='yvals2', ax=ax) </code></pre>
2
2016-09-30T22:22:32Z
[ "python", "pandas", "dataframe" ]
&pound; displaying in urllib2 and Beautiful Soup
39,800,624
<p>I'm trying to write a small web scraper in python, and I think I've run into an encoding issue. I'm trying to scrape <a href="http://www.resident-music.com/tickets" rel="nofollow">http://www.resident-music.com/tickets</a> (specifically the table on the page) - a row might look something like this -</p> <pre><code> ...
2
2016-09-30T21:57:18Z
39,800,910
<p>I used <code>requests</code> for this but hopefully you can do that using <code>urllib2</code> also. So here is the code:</p> <pre><code>#!/usr/bin/env python # -*- coding: utf-8 -*- import requests from BeautifulSoup import BeautifulSoup soup = BeautifulSoup(requests.get('your_url').text) chart = soup.findAll(n...
1
2016-09-30T22:23:22Z
[ "python", "encoding", "beautifulsoup", "urllib2" ]
&pound; displaying in urllib2 and Beautiful Soup
39,800,624
<p>I'm trying to write a small web scraper in python, and I think I've run into an encoding issue. I'm trying to scrape <a href="http://www.resident-music.com/tickets" rel="nofollow">http://www.resident-music.com/tickets</a> (specifically the table on the page) - a row might look something like this -</p> <pre><code> ...
2
2016-09-30T21:57:18Z
39,801,638
<p>You want to <em>unescape</em> the html which you can do using <em>html.unescape</em> in python3:</p> <pre><code>In [14]: from html import unescape In [15]: h = """&lt;tr&gt; ....: &lt;td style="width:64.9%;height:11px;"&gt; ....: &lt;p&gt;&lt;strong&gt;the great escape 2017&amp;nbsp; local e...
2
2016-10-01T00:01:49Z
[ "python", "encoding", "beautifulsoup", "urllib2" ]
Exception Class Failed to Import
39,800,625
<p>I have two files. One is <code>program_utils.py</code> with the contents:</p> <pre><code>class SomeException(Exception): def __init__(self, *args, **kwargs): Exception.__init__(self, *args, **kwargs) </code></pre> <p>another, say, <code>program.py</code>, with </p> <pre><code>import program_utils de...
0
2016-09-30T21:57:18Z
39,800,715
<p>Unlike <code>#include</code> in <code>C</code>/<code>C++</code>, in python the <code>import</code> statement is not equivalent to copy/pasting the file into your file.</p> <p>If you want that behavior, you can sort of get it by doing:</p> <pre><code>from program_utils import * </code></pre> <p>However, there are ...
2
2016-09-30T22:04:43Z
[ "python", "exception", "python-import" ]
Python: TypeError: 'int' object is not callable. Most likely a easy fix. cant seem to fiture out how to fix it
39,800,654
<p>here is the a section of the code.</p> <pre><code>import math length_centre=eval(input("Enter length from centre to corner of pentagon: ")) side_length= 2*length_centre*(math.sin(math.pi/5)) print(side_length) areaP =(5((side_length)**2))/(4*((math.tan)((math.pi)/5))) print(areaP) </code></pre> <p>error for the ...
2
2016-09-30T21:59:16Z
39,800,701
<p>Programming languages don't have implicit multiplication like written math, so <code>5((side_length)**2)</code> is not legal, it's trying to call <code>5</code> as a function with argument <code>side_length ** 2</code>. I'm guessing you want <code>5 * side_length**2</code> (removing some extraneous parens that aren'...
3
2016-09-30T22:03:59Z
[ "python", "int" ]
comment python code in visual studio code
39,800,665
<p>My visual studio code comment python code with <code>'''</code> instead of using <code>#</code> when try to comment a block of code with the key combination <code>ctrl + shift + a</code>. I have ubuntu 16.04</p>
0
2016-09-30T21:59:51Z
39,801,177
<p>This has nothing specifically to to with Visual Studio, but a result of the python commenting styles. Generally, single line comments are done with the pound (or hash) symbol:</p> <pre><code># This is a comment </code></pre> <p>In contrast, three quotation marks (either ''' or """) can be used to easily produce mu...
2
2016-09-30T22:53:36Z
[ "python", "vscode" ]
How to change date format and add a day to the date
39,800,751
<p>I have a date format that looks like this: 2016-08-30 and need to transform it to yyyy,mm,dd, as well as add a day. The purpose is to get a quandl format for days.</p> <pre><code>i = datetime.strptime(i,'%Y-%m-%d').strftime('%Y,%-m,%d') print i j = dt.datetime(i) + dt.timedelta(1) </code></pre> <p>This is the code...
0
2016-09-30T22:08:39Z
39,800,775
<p>You can use <code>timedelta</code> to add a day and use <code>strftime</code> to format the date string.</p> <pre><code>import datetime dt = datetime.datetime.strptime('2016-01-23', '%Y-%m-%d') dt = dt + datetime.timedelta(days=1) print dt.strftime('%Y,%m,%d') </code></pre>
0
2016-09-30T22:10:43Z
[ "python", "datetime", "date-formatting", "timedelta" ]
Adding a sorted tuple to a dictionary as a key
39,800,762
<p>I am very new to Python and i am trying my best to learn Python. I have been trying to implement a community detection algorithm that i came across and i would really appreciate if i could get help from anyone here. </p> <p>I have a <strong>defaultdict(list)</strong>, my input, which looks like : </p> <pre><code...
0
2016-09-30T22:09:28Z
39,800,796
<p><a href="https://docs.python.org/3/library/functions.html#sorted" rel="nofollow"><code>sorted</code> returns a new sorted <code>list</code></a>, regardless of the input's type. If you want the result to be a sorted <code>tuple</code>, just wrap the <code>sorted</code> call in the <code>tuple</code> constructor:</p> ...
2
2016-09-30T22:12:42Z
[ "python", "dictionary", "tuples", "defaultdict" ]
Email logging with Python Django
39,800,772
<p>Django does support email log handlers.</p> <p>But this way, if some error is repeated often, we risk to be mail-bombed by ERROR emails.</p> <p>How to send us emails on errors but not too often?</p> <p>Any other solutions?</p>
1
2016-09-30T22:10:32Z
39,806,260
<p>Use a <code>BufferingSMTPHandler</code> as described in <a href="https://gist.github.com/1379446" rel="nofollow">this Gist</a>. You can adapt the described class to your needs.</p>
1
2016-10-01T11:47:33Z
[ "python", "django", "logging" ]