title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags list |
|---|---|---|---|---|---|---|---|---|---|
How to get __init__() to raise a more useful exception instead of TypeError when incorrect # of arguments? | 37,980,612 | <p>I have a class with an <strong>init</strong> that takes many arguments--some required, some not.</p>
<p>If one of the needed arguments is not supplied, you may get a TypeError, with an unhelpful message like 'requires at least 10 arguments (14 given)'.</p>
<p>I would like to have a custom TypeError subclass that a... | 5 | 2016-06-23T01:01:08Z | 37,992,475 | <p>In Python 3, you can define a function that takes "required keyword-only arguments." This is clearest documented in <a href="https://www.python.org/dev/peps/pep-3102/" rel="nofollow">PEP 3102</a>. The error message you get when you omit required keyword-only arguments includes the argument names.</p>
<pre><code>$... | 1 | 2016-06-23T13:03:09Z | [
"python",
"django",
"typeerror"
] |
How to get __init__() to raise a more useful exception instead of TypeError when incorrect # of arguments? | 37,980,612 | <p>I have a class with an <strong>init</strong> that takes many arguments--some required, some not.</p>
<p>If one of the needed arguments is not supplied, you may get a TypeError, with an unhelpful message like 'requires at least 10 arguments (14 given)'.</p>
<p>I would like to have a custom TypeError subclass that a... | 5 | 2016-06-23T01:01:08Z | 38,085,741 | <p>I ended up using a variation off of <a href="http://stackoverflow.com/a/37981082/4526479">Tomas Gonzalez's answer</a>, rewriting it so that it supports the mixture of ordered args, keyword args, and default values that existed. This supported our requirement of writing code that is always backwards compatible with l... | 0 | 2016-06-28T20:30:19Z | [
"python",
"django",
"typeerror"
] |
How to copy the spatial reference from a shapefile to a geotiff raster? | 37,980,623 | <p>I have constructed a python script that constructs a geotiff raster from a shapefile. At present the geotiff produced does not contain the spatial reference of the shapefile. How do I copy the spatial reference from the shapefile to the geotiff? I have tried copying the spatial reference of the shapefile to the g... | 1 | 2016-06-23T01:03:02Z | 37,994,060 | <p>The GDAL <code>dataset.SetProjection()</code> method expects well-known text (WKT) or PROJ4 strings, as per <a href="http://www.gdal.org/classGDALDataset.html#ae2d2e231f6d632f8c2b2cf0078a01150" rel="nofollow">the docs</a>: "The string should be in OGC WKT or PROJ.4 format".</p>
<p>You can achieve this by doing one ... | 0 | 2016-06-23T14:08:37Z | [
"python",
"gdal",
"shapefile",
"geotiff",
"ogr"
] |
Extracting values from the | 37,980,632 | <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code> <a href="javascript:popUp('http://www.abcd.com/calendar/event.php?calendar=1&amp;category=&amp;event=43221&... | -2 | 2016-06-23T01:04:02Z | 37,983,477 | <p><strong>Try this:</strong></p>
<pre><code>from bs4 import BeautifulSoup
data = """<a href="javascript:popUp('http://www.abcd.com/calendar/event.php?calendar=1&amp;category=&amp;event=43221&amp;date=2016-02-22','520','520');" onmouseout="javascript:hideEventDetailsBox();" onmouseover="javascript:even... | 0 | 2016-06-23T06:03:59Z | [
"javascript",
"python",
"web-scraping",
"beautifulsoup"
] |
Python: writing two different dictionaries out to two different csv files | 37,980,648 | <p>My program looks into a folder of text files and generates counts of two features I am looking at "SS" and "DS" and how many times they occur. So I set up a dictionary that lists the feature and how many times it occurs in the texts.</p>
<p>I want my SS dictionary to write out to one csv file and the DS dictionary ... | 0 | 2016-06-23T01:06:01Z | 37,981,156 | <p>The citizens of StackOverflow cannot run your code. It often helps to create a <a href="http://stackoverflow.com/help/mcve">Minimal, Complete, and Verifiable</a> example that others can run.</p>
<p>A crucial question: do <code>list_SS</code> and <code>list_DS</code> have data in them? Drop all of the code starting ... | 1 | 2016-06-23T02:08:05Z | [
"python",
"csv",
"dictionary"
] |
Why is Python datetime time delta not found? | 37,980,655 | <p>I am trying to make an array of dates in mmddyyyy format. The dates will start on the current day and then go two weeks into the future. So it all depends on the starting date. When I run my code I get an error that states:</p>
<pre><code>Traceback (most recent call last):
File "timeTest.py", line 8, in <module&... | 1 | 2016-06-23T01:07:44Z | 37,980,668 | <p>You already imported <code>timedelta</code>. You don't need to access it through datetime.</p>
<pre><code>import time
from datetime import datetime, date, time, timedelta
dayDates = []
today = datetime.now()
dayDates.append(today.strftime("%m%d%Y"))
for i in range(0,14):
day = today + timedelta(days=i)
pri... | 1 | 2016-06-23T01:09:41Z | [
"python",
"timedelta",
"python-datetime"
] |
Why is Python datetime time delta not found? | 37,980,655 | <p>I am trying to make an array of dates in mmddyyyy format. The dates will start on the current day and then go two weeks into the future. So it all depends on the starting date. When I run my code I get an error that states:</p>
<pre><code>Traceback (most recent call last):
File "timeTest.py", line 8, in <module&... | 1 | 2016-06-23T01:07:44Z | 37,980,747 | <p>The method you want to call is <code>datetime.timedelta</code>, as seen <a href="https://docs.python.org/2/library/datetime.html#timedelta-objects" rel="nofollow">here</a>. <code>datetime</code> is the module containing <code>timedelta</code>.</p>
<p>If you look at your <code>import</code> line:</p>
<pre><code>fr... | 1 | 2016-06-23T01:17:35Z | [
"python",
"timedelta",
"python-datetime"
] |
Why is Python datetime time delta not found? | 37,980,655 | <p>I am trying to make an array of dates in mmddyyyy format. The dates will start on the current day and then go two weeks into the future. So it all depends on the starting date. When I run my code I get an error that states:</p>
<pre><code>Traceback (most recent call last):
File "timeTest.py", line 8, in <module&... | 1 | 2016-06-23T01:07:44Z | 37,980,802 | <pre><code>import time
from datetime import datetime, date, time, timedelta
dayDates = []
today = datetime.now()
dayDates.append(today.strftime("%m%d%Y"))
for i in range(0,14):
day = today + datetime.timedelta(days=i)
print day
</code></pre>
<p>The error that you are getting says, that <code>datetime</code> h... | 1 | 2016-06-23T01:26:32Z | [
"python",
"timedelta",
"python-datetime"
] |
Count number of rows between filled values in python dataframe | 37,980,758 | <p>I'm still pretty new to pandas. I would like to count the number of rows with zero values up to the next row with a value in it. So for example, I would like to take a dataframe that looks like this:</p>
<pre><code>id Distance
00 0
01 0
02 0
03 0
04 0
05 10
06 0
07 0
08 0... | -2 | 2016-06-23T01:18:32Z | 37,981,161 | <p>This code achieves what you want. Notice that you need that <code>.copy()</code> because <code>counts</code> is modified on the fly.</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame({'Distance': [0,0,0,0,0,10,0,0,0,0,16,0,0,6]})
non_zeros = df['Distance'].values != 0
zeros = ~non_zeros
cou... | 0 | 2016-06-23T02:08:35Z | [
"python",
"pandas",
"dataframe"
] |
Python parsing HTML with BeautifulSoup | 37,980,812 | <p>I'm trying to take specific data from this [webpage][1] and eventually want to put it into a table of my own, except for right now, I just want to be able to get the data that I want to show up. With the code below I am able to get all the teams with class team even to show up, however I want to have both 'team odd'... | 1 | 2016-06-23T01:27:35Z | 37,988,518 | <p>To just get the names is simple, use <code>class_="game"</code>so you get both odd and even then just pull the td with the text name:</p>
<pre><code>from bs4 import BeautifulSoup
import requests
soup = BeautifulSoup(requests.get("http://www.scoresandodds.com/index.html").content)
table = soup.select_one("#mlb").f... | 0 | 2016-06-23T10:06:56Z | [
"python",
"ajax",
"parsing",
"beautifulsoup"
] |
Multiprocessing: why is a numpy array shared with the child processes, while a list is copied? | 37,980,870 | <p>I used this <a href="http://stackoverflow.com/questions/13121790/using-multiprocessing-manager-list-instead-of-a-real-list-makes-the-calculation">script</a> (see code at the end) to assess whether a global object is shared or copied when the parent process is forked. </p>
<p>Briefly, the script creates a global <co... | 3 | 2016-06-23T01:33:58Z | 37,980,995 | <p>They're all copy-on-write. What you're missing is that when you do, e.g.,</p>
<pre><code>for x in data:
pass
</code></pre>
<p>the reference count on every object contained in <code>data</code> is temporarily incremented by 1, one at a time, as <code>x</code> is bound to each object in turn. For <code>int</co... | 2 | 2016-06-23T01:48:00Z | [
"python",
"python-2.7",
"fork",
"python-multiprocessing",
"copy-on-write"
] |
PYInstaller-compiled exe can't find file with absolute path | 37,980,970 | <p>I compiled my python gui with pyinstaller on Windows 10 but it seems like it cannot find my other script even though I provided the hard-coded absolute path to it (with r'"C:\Program Files...script path..."'). I even tried os.isfile (script path) but it returns False. The python script was compiled with <code>pyinst... | 0 | 2016-06-23T01:45:15Z | 37,997,430 | <p>Solved by adding <code>--onedir</code> which will put everything needed to run the program in one directory in the dist folder. </p>
| 0 | 2016-06-23T16:46:25Z | [
"python",
"python-2.7",
"windows-10",
"exe",
"pyinstaller"
] |
Python Plot -- Plot from Top X-Axis Down | 37,980,977 | <p>I have some temperature dependent X-ray data like the one posted below. The ticks at the bottom from the x-axis represent the main peaks for a certain phase. So, for my data, I have a transition from one phase at low temperature to a new phase at high temperature. I am able to show the ticks for the low T phase and ... | 1 | 2016-06-23T01:46:12Z | 37,982,424 | <p>You have to duplicate x-axis and set new custom ticks and their size for that new axis, like here:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twiny() # create new x-axis
X = np.linspace(0,1,100)
Y = np.cos(X*20)
ax1.plot(X,Y)
ax1.set_... | 0 | 2016-06-23T04:35:09Z | [
"python",
"matplotlib",
"plot",
"canopy"
] |
Boto RequestExpired | 37,980,983 | <p>When running long processes I keep getting:</p>
<pre><code>...
content_repl/replicate_content.py", line 667, in detach_and_delete
volumes = ec2_conn.get_all_volumes(volume_ids=volumes_ids)
File "/usr/lib/python2.7/site-packages/boto/ec2/connection.py", line 2158, in get_all_volumes
[('item', Volume)], ver... | 1 | 2016-06-23T01:47:09Z | 38,048,662 | <p>I've found that in the end the problem was just with the connection object. According to my testing the assumedRoleObject could be reused without problems. Just in case however, I've recreated that object too when I recreate the connection.</p>
<p>Connections are good for 1 hour, then they start failing.</p>
| 0 | 2016-06-27T08:00:20Z | [
"python",
"amazon-web-services",
"boto"
] |
K means clustering using weka python | 37,980,989 | <pre><code>from weka.clusterers import Clusterer
import weka.core.converters as converters
data = converters.load_any_file("/home/ubuntu/test.csv")
data.class_is_last()
clusterer = Clusterer(classname="weka.clusterers.SimpleKMeans", options=["-N", "3"])
clusterer.build_clusterer(data)
print(clusterer)
# cluster the... | 0 | 2016-06-23T01:47:22Z | 38,463,746 | <p>As described in the <a href="http://python-weka-wrapper.readthedocs.io/en/latest/api.html" rel="nofollow">python-weka-wrapper API</a> you have to import and start the Java Virtual Machine:</p>
<pre><code>import weka.core.jvm as jvm
jvm.start()
</code></pre>
<p>It should solve your problem.</p>
| 1 | 2016-07-19T16:17:25Z | [
"python",
"weka",
"k-means"
] |
Remove element from list if part of string is duplicate | 37,981,029 | <p>What I want to do is to remove string elements from my list that have some duplicate parts. For example, if I have given list.</p>
<pre><code>ls = ['02/27/1960', '07/21/2004', '08/13/2004', '09/12/2004', '02/27', '07/21', '08/13']
</code></pre>
<p>I want output as </p>
<pre><code>ls_out = ['02/27/1960', '07/21/20... | 1 | 2016-06-23T01:52:51Z | 37,981,110 | <p>I'm not sure if this is the most efficient way to do this, but it would definitely work:</p>
<pre><code>ls = ['02/27/1960', '07/21/2004', '08/13/2004', '09/12/2004', '02/27', '07/21', '08/13']
ls2 = ls
for item in ls:
for dup_item in ls2:
if item == dup_item:
continue
if item.startswith(dup_item):... | 1 | 2016-06-23T02:01:48Z | [
"python",
"string",
"list"
] |
Remove element from list if part of string is duplicate | 37,981,029 | <p>What I want to do is to remove string elements from my list that have some duplicate parts. For example, if I have given list.</p>
<pre><code>ls = ['02/27/1960', '07/21/2004', '08/13/2004', '09/12/2004', '02/27', '07/21', '08/13']
</code></pre>
<p>I want output as </p>
<pre><code>ls_out = ['02/27/1960', '07/21/20... | 1 | 2016-06-23T01:52:51Z | 37,981,124 | <pre><code>cache = set()
def fun(s):
ss = s.split('/')
key = ss[0] + '/' + ss[1]
if key in cache:
return None
else:
cache.add(key)
return s
ls = ['02/27/1960', '07/21/2004', '08/13/2004', '09/12/2004', '02/27', '07/21', '08/13']
new_ls = filter(fun, ls)
print new_ls
</code></pr... | 1 | 2016-06-23T02:03:51Z | [
"python",
"string",
"list"
] |
Remove element from list if part of string is duplicate | 37,981,029 | <p>What I want to do is to remove string elements from my list that have some duplicate parts. For example, if I have given list.</p>
<pre><code>ls = ['02/27/1960', '07/21/2004', '08/13/2004', '09/12/2004', '02/27', '07/21', '08/13']
</code></pre>
<p>I want output as </p>
<pre><code>ls_out = ['02/27/1960', '07/21/20... | 1 | 2016-06-23T01:52:51Z | 37,981,217 | <p>This can also be solve with a <code>for</code> loop and <a href="https://docs.python.org/3.4/library/functions.html#any" rel="nofollow"><code>any</code></a> built-in method:</p>
<pre><code>>>> ls
['02/27/1960', '07/21/2004', '08/13/2004', '09/12/2004', '02/27', '07/21', '08/13']
>>>
>>> l... | 3 | 2016-06-23T02:14:39Z | [
"python",
"string",
"list"
] |
How to print strings from a defined function - Python 2.7 | 37,981,121 | <p>I'm new to posting on Stackoverflow, so bare with me if something is wrong and let me know how to fix it.</p>
<p>I am wondering how I can print "myName, myAge, myHeight, myJob" from the function me(). It appears that I can't have it in the function and it gives me an error saying myName, etc. is not defined... How ... | 0 | 2016-06-23T02:03:16Z | 37,981,259 | <p>this should work</p>
<p>the variables that are defined in the function are not visible outside it
so you just have to print them while you are in the function not outside</p>
<pre><code>def me():
myName = raw_input("What is your name? ")
myAge = int(raw_input("How old are you? "))
myHeight = int(raw_input("H... | 0 | 2016-06-23T02:18:45Z | [
"python",
"function"
] |
How to print strings from a defined function - Python 2.7 | 37,981,121 | <p>I'm new to posting on Stackoverflow, so bare with me if something is wrong and let me know how to fix it.</p>
<p>I am wondering how I can print "myName, myAge, myHeight, myJob" from the function me(). It appears that I can't have it in the function and it gives me an error saying myName, etc. is not defined... How ... | 0 | 2016-06-23T02:03:16Z | 37,981,559 | <p>So, this is a question relating to <strong>scope</strong>. Scope is an idea that we want to encapsulate variables in a small little chunk, rather than letting anyone anywhere modify and use them. When you run a function, you create a <em>closure</em> - a new scope. Anything defined in that scope is only viable in th... | 1 | 2016-06-23T02:54:51Z | [
"python",
"function"
] |
How to print strings from a defined function - Python 2.7 | 37,981,121 | <p>I'm new to posting on Stackoverflow, so bare with me if something is wrong and let me know how to fix it.</p>
<p>I am wondering how I can print "myName, myAge, myHeight, myJob" from the function me(). It appears that I can't have it in the function and it gives me an error saying myName, etc. is not defined... How ... | 0 | 2016-06-23T02:03:16Z | 37,981,570 | <p>You cannot easily access the internals of a function. Part of the reason we use functions is that they encapsulate their behavior, so changes elsewhere in your program cannot affect what happens inside of your function.</p>
<p>The usual way to approach this would be for the <code>me</code> function to return the va... | 0 | 2016-06-23T02:56:26Z | [
"python",
"function"
] |
print a dictionary of dictionaries to a csv? | 37,981,131 | <p>I have a dictionary that looks like this: </p>
<pre><code>defaultdict(<type 'int'>, {'201304': defaultdict(<type 'int'>, {'District - 1': 20, 'District - 12': 9, 'District - 6': 5, 'District - 5': 1, 'District - 4': 1, 'District - 3': 1, 'District - 2': 13, 'District - 15': 1, 'District - 14': 2}), '201... | 1 | 2016-06-23T02:04:51Z | 37,981,238 | <pre><code>with open('output.csv','wb') as output_file:
w= csv.writer(output_file)
for month,values in months.iteritems():
for k,v in values.iteritems():
w.writerow([month, k ,v ] )
Update
</code></pre>
<p>for each value of inner dict, it could be sorted based on key value than add to output... | 2 | 2016-06-23T02:16:39Z | [
"python",
"csv",
"dictionary"
] |
print a dictionary of dictionaries to a csv? | 37,981,131 | <p>I have a dictionary that looks like this: </p>
<pre><code>defaultdict(<type 'int'>, {'201304': defaultdict(<type 'int'>, {'District - 1': 20, 'District - 12': 9, 'District - 6': 5, 'District - 5': 1, 'District - 4': 1, 'District - 3': 1, 'District - 2': 13, 'District - 15': 1, 'District - 14': 2}), '201... | 1 | 2016-06-23T02:04:51Z | 37,981,400 | <p>You need to process the raw data (a) to figure out all districts that exist, and (b) to reorganize it so that specific values can be looked up by month-district combinations.</p>
<pre><code>raw_data = {
'201304': {'District - 1': 120, 'District - 12': 9, 'District - 6': 5, 'District - 5': 1, 'District - 4': 1, ... | 2 | 2016-06-23T02:34:35Z | [
"python",
"csv",
"dictionary"
] |
print a dictionary of dictionaries to a csv? | 37,981,131 | <p>I have a dictionary that looks like this: </p>
<pre><code>defaultdict(<type 'int'>, {'201304': defaultdict(<type 'int'>, {'District - 1': 20, 'District - 12': 9, 'District - 6': 5, 'District - 5': 1, 'District - 4': 1, 'District - 3': 1, 'District - 2': 13, 'District - 15': 1, 'District - 14': 2}), '201... | 1 | 2016-06-23T02:04:51Z | 37,981,648 | <p>You can use <code>csv.DictWriter</code>, but need to add a month column since it is a two-dimensional dictionary:</p>
<pre><code>#!python3
from collections import defaultdict
import csv
# populate the defaultdict "months"
# <deleted to keep short>
# Build a set of unique districts
s = set()
for k,v in month... | 1 | 2016-06-23T03:06:09Z | [
"python",
"csv",
"dictionary"
] |
How can I save my file after writing to it in Python? | 37,981,135 | <p>I am learning python, and followed a guide for a quick and simple reddit bot. I wanted to try my skills and attempted to make a cache.txt file to write the comments that I have replyed to. Currently, the file opens, and the code runs, and writes the comment ID to the file correctly, but when I close the program, som... | -1 | 2016-06-23T02:05:22Z | 37,981,150 | <p>Make sure to <code>.close()</code> the file.</p>
| 0 | 2016-06-23T02:07:35Z | [
"python"
] |
Python - Scaling one section of an array and not the rest | 37,981,139 | <p>I'm trying to normalize a specific range of numbers in a data while keeping the rest the same value. This is a very large data set as well.</p>
<p>Here is my attempt,</p>
<pre><code>import numpy as np
# An unrelated scaling measure, the intial array shape I want to keep.
Intscale1 = np.array([data/1700 for data i... | 1 | 2016-06-23T02:06:29Z | 37,981,190 | <p>you can use map. The problem I see is where you are using 2 * array. That action is actually like doing array + array which in python will just append the array after itself, so with a map you can fix it</p>
<pre><code># An unrelated scaling measure, the intial array shape I want to keep.
Intscale1 = np.array([data... | 1 | 2016-06-23T02:12:09Z | [
"python",
"arrays"
] |
Python - Scaling one section of an array and not the rest | 37,981,139 | <p>I'm trying to normalize a specific range of numbers in a data while keeping the rest the same value. This is a very large data set as well.</p>
<p>Here is my attempt,</p>
<pre><code>import numpy as np
# An unrelated scaling measure, the intial array shape I want to keep.
Intscale1 = np.array([data/1700 for data i... | 1 | 2016-06-23T02:06:29Z | 37,981,208 | <p>The problem is, that <code>+</code> that you are trying to use works as an elementwise addition operator. It tries to add values from the arrays and fails, because they are of different size. The function concatenate from numpy lets you concatenate two numpy arrays into another, bigger one. If you had to rearrange t... | 0 | 2016-06-23T02:13:49Z | [
"python",
"arrays"
] |
How to use stdout and stderr child_process in Gulp | 37,981,218 | <p>I use gulp with python flask.</p>
<pre><code>var gulp = require('gulp');
var spawn = require('child_process').spawn;
var app = spawn('python', ['app.py']);
gulp.task('runserver', function() {
app.stdout.on('data', (data) => {
console.log(`stdout: ${data}`);
});
app.stderr.on('data', (data) =... | 0 | 2016-06-23T02:14:42Z | 37,988,128 | <p>Since you're in Node environment, you can use stdout and stderr by following</p>
<pre><code>app.stdin.on('readable', () => {
var chunk = process.stdin.read();
if (chunk !== null) {
process.stdout.write(`data: ${chunk}`);
}
});
app.stdout.write(`${msg}\n`);
</code></pre>
<p>The process objec... | 0 | 2016-06-23T09:50:56Z | [
"python",
"flask",
"gulp",
"child-process"
] |
Setting completekey=None removes up-arrow functionality | 37,981,271 | <p>I'm trying to write a small REPL using the <a href="https://docs.python.org/3/library/cmd.html" rel="nofollow"><code>cmd</code></a> library in Python. One of the features that it provides is automatic tab completion, which I do not want.</p>
<p>Luckily, the docs mention "If completekey is not None and readline is a... | 0 | 2016-06-23T02:20:03Z | 37,981,416 | <p>The <code>readline</code> module is only imported if <code>completekey</code> has a non-None value. It looks like the only way to use <code>readline</code> and disable completion is to specify a do-nothing completer.</p>
<pre><code>class CmdSubclass(Cmd):
# Other configuration
# ...
def complete(self, ... | 2 | 2016-06-23T02:36:32Z | [
"python",
"python-3.x",
"read-eval-print-loop"
] |
Create a new folder after moving 1 folder back | 37,981,373 | <p>Hi I have this old path:</p>
<pre><code>OldPath = "C:\\Desktop\\Outerfolder\\InnerFolder"
</code></pre>
<p>And using the following slice of code:</p>
<pre><code>os.path.normpath(OldPath + os.sep + os.pardir
</code></pre>
<p>I get <code>C:\Desktop\Outerfolder</code>
But using it within another slice of code:</p>
... | 0 | 2016-06-23T02:31:38Z | 37,981,714 | <p>Maybe you should write like below, without '//'</p>
<pre><code>NewFolder = os.path.join(os.path.normpath(OldPath + os.sep + os.pardir),"NewInnerFolder")
print NewFolder
</code></pre>
<p>When you pass '//NewInnerFolder', the <strong>os.path.join</strong> will treat it as a 'absolute path' and join it to drive_path.... | 2 | 2016-06-23T03:15:11Z | [
"python",
"os.path"
] |
How to calculate the length till a certain word in a sentence | 37,981,383 | <pre><code>str1 = "If you're reading this half sentence you are amazing because it's half."
</code></pre>
<p>I don't want the length of the entire string.I need the length until it reaches the word <strong>because</strong>.It should give me the length of:- </p>
<blockquote>
<p>"If you're reading this half sentence ... | -1 | 2016-06-23T02:32:20Z | 37,981,432 | <p>Use <a href="https://docs.python.org/3.5/library/stdtypes.html#str.find" rel="nofollow"><code>str.find</code></a>.</p>
<p>Example:</p>
<pre><code>>>> str1 = "If you reading this half sentence you are amazing because it's half."
>>> print(str1.find('because'))
50
</code></pre>
| 2 | 2016-06-23T02:38:04Z | [
"python",
"string",
"string-length"
] |
How to calculate the length till a certain word in a sentence | 37,981,383 | <pre><code>str1 = "If you're reading this half sentence you are amazing because it's half."
</code></pre>
<p>I don't want the length of the entire string.I need the length until it reaches the word <strong>because</strong>.It should give me the length of:- </p>
<blockquote>
<p>"If you're reading this half sentence ... | -1 | 2016-06-23T02:32:20Z | 37,983,118 | <p>You can use another function str.index(), it does the same thing. The only difference between find() and index() is find() method return -1 if it doesn't find the sub string but index() method raises an exception.
Usage:
len = str1.index('because')</p>
| 0 | 2016-06-23T05:35:30Z | [
"python",
"string",
"string-length"
] |
How to calculate the length till a certain word in a sentence | 37,981,383 | <pre><code>str1 = "If you're reading this half sentence you are amazing because it's half."
</code></pre>
<p>I don't want the length of the entire string.I need the length until it reaches the word <strong>because</strong>.It should give me the length of:- </p>
<blockquote>
<p>"If you're reading this half sentence ... | -1 | 2016-06-23T02:32:20Z | 37,989,389 | <p>You could just do it this way, must you include whitespace or not?</p>
<pre><code>def find_till_word(sentence, word):
count = 0
for char in sentence[:sentence.index(word)]:
count += 1
return count
</code></pre>
<p>Output:</p>
<pre><code>>>> str1 = "If you reading this half sentence yo... | 0 | 2016-06-23T10:44:44Z | [
"python",
"string",
"string-length"
] |
How do you replace and reverse a string in python? | 37,981,405 | <p>This is what I have so far, it is not replacing the C with a G for some reason. Why might this be?</p>
<pre><code>DNASeq=raw_input("Enter the DNA sequence here: ")
DNASeq=DNASeq.upper().replace(" ","")
reverse=DNASeq[::-1]
print reverse.replace('A','U').replace('T','A').replace('C','G').replace('G','C')
</code></... | 0 | 2016-06-23T02:34:52Z | 37,981,469 | <p>The problem is that you replace <code>C</code> with <code>G</code> then <code>G</code> with <code>C</code>. One simple way to prevent you going from one to the other would be to replace <code>C</code> with <code>g</code>, so it wouldn't then go back to <code>C</code>, then uppercase the result:</p>
<pre><code>gatta... | 2 | 2016-06-23T02:43:20Z | [
"python",
"string",
"reverse"
] |
How do you replace and reverse a string in python? | 37,981,405 | <p>This is what I have so far, it is not replacing the C with a G for some reason. Why might this be?</p>
<pre><code>DNASeq=raw_input("Enter the DNA sequence here: ")
DNASeq=DNASeq.upper().replace(" ","")
reverse=DNASeq[::-1]
print reverse.replace('A','U').replace('T','A').replace('C','G').replace('G','C')
</code></... | 0 | 2016-06-23T02:34:52Z | 37,981,562 | <p>As pointed out already, the problem is that your are replacing ALL Cs with Gs first. I wanted to throw in this approach because I think it would be the most efficient:</p>
<pre><code>>>> complement = {'A':'U', 'G':'C', 'C':'G','T':'A'}
>>> seq = "GATTACA"
>>> "".join(complement[c] for c i... | 0 | 2016-06-23T02:55:04Z | [
"python",
"string",
"reverse"
] |
How do you replace and reverse a string in python? | 37,981,405 | <p>This is what I have so far, it is not replacing the C with a G for some reason. Why might this be?</p>
<pre><code>DNASeq=raw_input("Enter the DNA sequence here: ")
DNASeq=DNASeq.upper().replace(" ","")
reverse=DNASeq[::-1]
print reverse.replace('A','U').replace('T','A').replace('C','G').replace('G','C')
</code></... | 0 | 2016-06-23T02:34:52Z | 37,982,063 | <p>You have done almost correct code.
but here one thing you need to understand is First you replace C with G and again you replace G with C.</p>
<blockquote>
<p>.replace('C','G').replace('G','C')</p>
</blockquote>
<p>just remove <code>.replace('G','C')</code> from your code and everything works fine.</p>
<p>here ... | 0 | 2016-06-23T03:55:46Z | [
"python",
"string",
"reverse"
] |
global scope in functions in Python | 37,981,408 | <p>In the code below I am trying to not use "global" in the function as I have read that is bad practice. If I remove them the code wont work. I have looked over tons of stuff on passing parameters to other functions but when I try what they have in the examples I can't get it to pass the other functions.</p>
<p>This ... | 0 | 2016-06-23T02:35:33Z | 37,981,476 | <p>You need to specify arguments for functions when they are defined:</p>
<pre><code>def burgerChoice(numBurgers, burgerTotal, extraBurgers):
</code></pre>
<p>Then you need to pass parameters when they are called:</p>
<pre><code>burgerChoice(numBurgers, burgerTotal, extraBurgers)
</code></pre>
| 0 | 2016-06-23T02:43:46Z | [
"python"
] |
global scope in functions in Python | 37,981,408 | <p>In the code below I am trying to not use "global" in the function as I have read that is bad practice. If I remove them the code wont work. I have looked over tons of stuff on passing parameters to other functions but when I try what they have in the examples I can't get it to pass the other functions.</p>
<p>This ... | 0 | 2016-06-23T02:35:33Z | 37,982,593 | <p>This question is related to 'Python functions call by reference'.</p>
<p>Here is a short example:</p>
<p>(with global)</p>
<pre><code>def main():
func_a();
func_b();
print 'main(): %d, %d' % (gv, id(gv))
def func_a():
global gv;
gv = 1
print 'func_a(): %d, %d' % (gv, id(gv))
def func_b()... | 0 | 2016-06-23T04:51:48Z | [
"python"
] |
Error when uploading an image to ImageField via Django Admin | 37,981,474 | <p>Trying to upload a picture via the Django admin panel and I'm getting an error. The model is:</p>
<pre><code>fs = FileSystemStorage(location='/media')
class Picture(models.Model):
picture_path = models.ImageField(upload_to=fs, blank=True)
hunter_ID = models.ForeignKey(User,
... | 1 | 2016-06-23T02:43:42Z | 37,981,583 | <p>As the error indicates, the issue id with your <code>Picture</code> model's <code>__str__</code> method. Instead of returning a string it is returning an <code>ImageFieldFile</code> object. </p>
<p>Change it to return a string - e.g., </p>
<pre><code>def __str__(self):
return str(self.picture_path)
</code></pr... | 4 | 2016-06-23T02:57:44Z | [
"python",
"django",
"python-3.x",
"imagefield"
] |
How to make statistic according to week unit in pandas? | 37,981,518 | <p>I have a DataFrame like this:</p>
<pre><code> usr1 usr2
2016-01-01 20 NaN
2016-01-02 13 12
2016-01-03 NaN 12
2016-01-04 NaN 23
2016-01-05 13 21
2016-01-06 20 NaN
2016-01-07 NaN 12
2016-01-08 NaN 23
2016-01-09 13 21
2016-01-10 20 NaN
. . .
. ... | 1 | 2016-06-23T02:49:49Z | 37,981,585 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.resample.html" rel="nofollow"><code>.resample()</code></a>:</p>
<pre><code>df.resample('W').sum()
</code></pre>
<p>If you don't want to keep the <code>date_time</code> values that indicate when the weeks occurred, you can <... | 1 | 2016-06-23T02:58:29Z | [
"python",
"pandas"
] |
How to make statistic according to week unit in pandas? | 37,981,518 | <p>I have a DataFrame like this:</p>
<pre><code> usr1 usr2
2016-01-01 20 NaN
2016-01-02 13 12
2016-01-03 NaN 12
2016-01-04 NaN 23
2016-01-05 13 21
2016-01-06 20 NaN
2016-01-07 NaN 12
2016-01-08 NaN 23
2016-01-09 13 21
2016-01-10 20 NaN
. . .
. ... | 1 | 2016-06-23T02:49:49Z | 37,982,625 | <p>Some more statistics</p>
<pre><code>df.groupby(pd.TimeGrouper('W')).describe().dropna()
</code></pre>
<p><a href="http://i.stack.imgur.com/ufYhM.png" rel="nofollow"><img src="http://i.stack.imgur.com/ufYhM.png" alt="enter image description here"></a></p>
| 1 | 2016-06-23T04:54:12Z | [
"python",
"pandas"
] |
How are keys stored and accessed in python 2? | 37,981,523 | <p>I'm trying to implement DFS and BFS in python. I have this code for Depth First Search, which works and I almost understand it.</p>
<p>What I don't understand is how are the keys being accessed. The program could have chosen any key in G.keys(),but it always ends up choosing the next adjacent key in the graph. Sinc... | 0 | 2016-06-23T02:50:23Z | 37,981,637 | <p>The storage of a dictionary tends to be in the order of the hashes of its keys, although this is not guaranteed. You can see that in your particular example, the hashes all rise in relation to the character.</p>
<pre><code>>>> for x in 'ABCDEFGH':
print hash(x)
-269909568
-141909181
-13908798
11409158... | 0 | 2016-06-23T03:04:42Z | [
"python",
"python-2.7",
"dictionary",
"depth-first-search"
] |
How are keys stored and accessed in python 2? | 37,981,523 | <p>I'm trying to implement DFS and BFS in python. I have this code for Depth First Search, which works and I almost understand it.</p>
<p>What I don't understand is how are the keys being accessed. The program could have chosen any key in G.keys(),but it always ends up choosing the next adjacent key in the graph. Sinc... | 0 | 2016-06-23T02:50:23Z | 37,981,661 | <p><code>start_traversal</code> is not where the adjacent key is chosen. That's the part in <code>traverse</code>, specifically <code>for other_nodes in G[node]:</code>. Since <code>G[node]</code> contains only adjacent nodes, all of them will be iterated over.</p>
<p>What <code>for node in G.keys():</code> does is se... | 0 | 2016-06-23T03:07:46Z | [
"python",
"python-2.7",
"dictionary",
"depth-first-search"
] |
How are keys stored and accessed in python 2? | 37,981,523 | <p>I'm trying to implement DFS and BFS in python. I have this code for Depth First Search, which works and I almost understand it.</p>
<p>What I don't understand is how are the keys being accessed. The program could have chosen any key in G.keys(),but it always ends up choosing the next adjacent key in the graph. Sinc... | 0 | 2016-06-23T02:50:23Z | 37,982,641 | <p>first of all their is a error in the program in line: 13 col:19 it must be
print 'node:'+node<p>
it you want the output in the same line you can add a comma after node<p>
second thing a dictionary stored the elements in the sorted order of ascii value of the keys<p>
but in your program what is happening is in line ... | 0 | 2016-06-23T04:56:12Z | [
"python",
"python-2.7",
"dictionary",
"depth-first-search"
] |
Persistence of variables within a single session | 37,981,549 | <p>I am working with Reinforcement Learning and would like to store my examples within the TF graph to avoid moving data between python and TF. I thought I could use a TF.Variable() as it should persist for the entire session and simply add a sample on the end when needed. Here is an example of one of the approaches:... | 0 | 2016-06-23T02:54:00Z | 37,985,962 | <p>You were almost there. If you want to modify a Variable, you have to create an assign op. This operation will be run in <code>sess.run()</code> and will update the content of the Variable.</p>
<p>Here the trick is that when assigning the Variable, you modify its shape. You have to use <code>tf.assign</code> with ar... | 1 | 2016-06-23T08:21:53Z | [
"python",
"tensorflow"
] |
Use Python "with" statement for ogr.open(file) | 37,981,614 | <p>Is it possible to use the Python <a href="https://docs.python.org/3/tutorial/inputoutput.html#methods-of-file-objects" rel="nofollow">"with"</a> statement with the ogr.open(file) function?</p>
<p>For example, I would like to do something like:</p>
<pre><code>with ogr.open(file) as ds:
</code></pre>
<p>At the mome... | 0 | 2016-06-23T03:01:31Z | 37,981,984 | <p>According to the documentation, it appears that you cannot use <code>with ogr.Open(file)</code> ...</p>
<p>A Python object that you use in a <code>with</code> statement needs to have methods <code>__enter__</code> and <code>__exit__</code> to set up and take down a context used inside the <code>with</code> block. <... | 1 | 2016-06-23T03:46:55Z | [
"python",
"file",
"geospatial",
"ogr"
] |
How to excute selenium webdriver in linux without display | 37,981,643 | <p>I am trying to use selenium webdriver in centos to test my webpage.
But,I got an error message when I execute the process.
Can someone help me?</p>
<pre><code>from pyvirtualdisplay import Display
from selenium import webdriver
display=Display(visible=0, size=(320, 240)).start()
path = "/usr/bin/firefox"
driver= we... | 1 | 2016-06-23T03:05:30Z | 37,982,508 | <p>Pretty sure your problem has to do with the fact that your trying to pass the path to your firefox binary as a string, instead as a "FirefoxBinary" object, furthermore the first argument to Firefox() is a FirefoxProfile(). Doing the following should resolve the issue.</p>
<pre><code>from pyvirtualdisplay import Dis... | 0 | 2016-06-23T04:43:52Z | [
"python",
"linux",
"selenium"
] |
matplotlib does not show plot() | 37,981,665 | <p>I tried running plt.show() but no plot is shown. I had tried lots of solutions from stackoverflow including setting matplotlib backend to Qt4Agg, switching to other backends (i.e. TkAgg, Agg) and reinstalling matplotlib package but still not solving the issue. Some solutions that I had tried but not working are: </p... | 0 | 2016-06-23T03:07:57Z | 37,981,813 | <p>The labels must use parentheses such as <code>plt.xlabel("text")</code>, not assigned to a string with <code>=</code> like you have in your example code. Make the changes in your code, save the changes, quit and reopen Spyder or whatever interpreter you are running, then run the code again.</p>
<pre><code>plt.figur... | 1 | 2016-06-23T03:27:36Z | [
"python",
"matplotlib",
"plot",
"anaconda",
"spyder"
] |
How to align indexes of many dataframes and fill in respective missing values in Pandas? | 37,981,678 | <p>I have 4 dataframes with data of similar datetime indexes, however in each of them there are few missing lines and I know that the gaps can be filled using previous known data.</p>
<p>I would like to 'align' these dataframes so that they have union of indexes of all dataframes and to fill in missing values.
I know ... | 3 | 2016-06-23T03:09:52Z | 37,981,786 | <p>Is this the behavior you are trying to achieve? Note that this method works regardless of whether or not the indexes on the dataframes are monotonic.</p>
<pre><code>df1 = pd.DataFrame({'values': 1}, index=pd.DatetimeIndex(['2016-06-01', '2016-06-03']))
df2 = pd.DataFrame({'values': 2}, index=pd.DatetimeIndex(['2016... | 3 | 2016-06-23T03:23:50Z | [
"python",
"pandas",
"dataframe",
"reindex",
"datetimeindex"
] |
Spyder crashes at start: UnicodeDecodeError | 37,981,860 | <p>During a Spyder session my Linux froze. After startup, I could not start Spyder; I got the following error instead:</p>
<pre><code>(trusty)dreamer@localhost:~$ spyder
Traceback (most recent call last):
File "/home/dreamer/anaconda2/bin/spyder", line 2, in <module>
from spyderlib import start_app
File ... | 0 | 2016-06-23T03:32:00Z | 37,986,272 | <p>My guess is that your spyder configuration file somehow got corrupted. This is the file <code>spyder.ini</code>, which resides in a directory like <code>~/.spyder2</code> (the exact name of the directory depends on the version you have installed). Maybe the encoding of the configuration file changed or a Unicode byt... | 0 | 2016-06-23T08:35:52Z | [
"python",
"spyder"
] |
set up $DISPLAY VARIABLE | 37,981,875 | <p>While trying to use the python turtle module to write a program I came across an issue. I have turtle installed but after I ran the code below for testing purposes:</p>
<pre><code>import turtle
import random
turtle = turtle.Turtle()
</code></pre>
<p>I came across this error in the terminal. There have been simila... | 0 | 2016-06-23T03:33:52Z | 37,983,124 | <p>their is no module name Turtle()<p>
instead of using Turtle use turtle python is a case sensitive language so please make sure that you are using right case of alphabets
<p>turtle = turtle.turtle()
<p>
if you find any such error first tried it in python shell you will definately get it corrected. </p>
| 0 | 2016-06-23T05:35:43Z | [
"python",
"tkinter",
"turtle-graphics"
] |
set up $DISPLAY VARIABLE | 37,981,875 | <p>While trying to use the python turtle module to write a program I came across an issue. I have turtle installed but after I ran the code below for testing purposes:</p>
<pre><code>import turtle
import random
turtle = turtle.Turtle()
</code></pre>
<p>I came across this error in the terminal. There have been simila... | 0 | 2016-06-23T03:33:52Z | 38,006,739 | <p>A couple of ideas for you:</p>
<p>1) launch your python program from inside an xterm instead of Terminal.app and then the $DISPLAY variable will already be set for you.</p>
<p>2) I typically don't have X11 running when I use the Python turtle module, things just work. Looking at my $DISPLAY in Terminal.app withou... | 0 | 2016-06-24T06:17:16Z | [
"python",
"tkinter",
"turtle-graphics"
] |
Do something only once Python | 37,981,885 | <p>I have this sequence of numbers</p>
<p>12345 do something
12345
12345
12346 do something
12346
12346
12346
12347 do something
12347
12347
12347</p>
<p>The numbers are repeated unknown number of times
I just need to do something on the first change</p>
| -4 | 2016-06-23T03:35:21Z | 37,982,009 | <p>You'll probably want to set a boolean saying whether you've already done the thing. Something like:</p>
<pre><code>have_done_something=False
if number_changed and not have_done_something:
have_done_something=True
#do something
</code></pre>
| -1 | 2016-06-23T03:50:09Z | [
"python"
] |
Do something only once Python | 37,981,885 | <p>I have this sequence of numbers</p>
<p>12345 do something
12345
12345
12346 do something
12346
12346
12346
12347 do something
12347
12347
12347</p>
<p>The numbers are repeated unknown number of times
I just need to do something on the first change</p>
| -4 | 2016-06-23T03:35:21Z | 37,983,013 | <p>you might have made an infinite loop please send your code so that we can help you<p>
so stop you program press ctrl +c.</p>
| 0 | 2016-06-23T05:28:12Z | [
"python"
] |
Trying to assign values to keys in dictionary gives type error | 37,981,890 | <p>dict["north-west"]=(south+width_NS,west)</p>
<p>TypeError: 'type' object does not support item assignment</p>
<pre><code>class Building:
def __init__(self, south, west, width_WE, width_NS, height=10):
</code></pre>
<blockquote>
<pre><code> keys=("north-west","north-east","south-west","south-east")
... | 0 | 2016-06-23T03:35:56Z | 37,981,957 | <p>You have to assign the created dictionary :</p>
<pre><code>d = dict.fromkeys(keys)
</code></pre>
<p>This gives :</p>
<pre><code>>>> d = dict.fromkeys(keys)
>>> d
{'south-west': None, 'south-east': None, 'north-east': None, 'north-west': None}
>>> d['north-west'] = (south+width_NS,west)
... | 1 | 2016-06-23T03:44:15Z | [
"python",
"dictionary"
] |
Trying to assign values to keys in dictionary gives type error | 37,981,890 | <p>dict["north-west"]=(south+width_NS,west)</p>
<p>TypeError: 'type' object does not support item assignment</p>
<pre><code>class Building:
def __init__(self, south, west, width_WE, width_NS, height=10):
</code></pre>
<blockquote>
<pre><code> keys=("north-west","north-east","south-west","south-east")
... | 0 | 2016-06-23T03:35:56Z | 37,982,093 | <p>Use another variable name, say, dict1. Here is the correct code:</p>
<pre><code>class Building:
def __init__(self, south, west, width_WE, width_NS, height=10):
keys=("north-west","north-east","south-west","south-east")
dict1 = dict.fromkeys(keys)
dict1['north-west']=(south+width_NS,west)
... | 0 | 2016-06-23T04:00:07Z | [
"python",
"dictionary"
] |
python: IOError: [Errno 36] File name too long: | 37,981,892 | <p>I want to create a file within tmpfs (under CentOS 6.5) like this:</p>
<pre><code>fpath = '/tmpfs_mounted/with/long/file/name'
with open(fpath, 'w') as fd:
write(somedata)
...
</code></pre>
<p>But I got the <code>IOError: [Errno 36] File name too long: ...</code> error, How to fix it?</p>
| 0 | 2016-06-23T03:36:14Z | 37,985,805 | <p>Ok, I got it. Linux really have a base-name limit for 256 bytes, see <a href="https://en.wikipedia.org/wiki/Comparison_of_file_systems" rel="nofollow">here</a> for a full list of all limitations. A simple code can verify that:</p>
<pre><code># -*- encoding:utf8 -*-
import os
if __name__ == '__main__':
base = '... | 0 | 2016-06-23T08:14:29Z | [
"python",
"centos6",
"tmpfs"
] |
Python Tornado connections timing out early -- Any way to prevent timeout (HTTP 599 errors)? | 37,981,897 | <p>I am using Tornado to asynchronously scrape data from many thousand URLS. Each of them is 5-50MB, so they take a while to download. I keep getting "Exception: HTTP 599: Connection closed http:â¦" errors, <em>despite</em> the fact that I am setting both connect_timeout and request_timeout to a very large number. </p... | 0 | 2016-06-23T03:36:51Z | 37,986,418 | <p>As you note <code>HTTPError 599</code> is raised on connection or request timeout, but this is not the only case. The other one is when connection has been closed by the server before request ends (including entire response fetch) e.g. due to its (server) timeout to handle request or whatever.</p>
| 1 | 2016-06-23T08:42:05Z | [
"python",
"asynchronous",
"tornado"
] |
Error messages in EAFP style | 37,981,909 | <p>"It's easier to ask for forgiveness than permission", or EAFP, is a common style in Python, where the coder writes code expecting an error and uses the error handling for expected flow control.</p>
<p>The problem I often find is that this can lead to confusing error messages. Consider this example.</p>
<pre><code>... | 0 | 2016-06-23T03:38:10Z | 38,216,916 | <p>For any wondering, I have ended up using the following (rather obvious) solution to remind myself when debugging.</p>
<pre><code>import logging
logger = logging.getLogger(__name__)
some_dict = {} # oops a bug, this should have 'expected key'
try:
some_dict['optional key'] # expected error
except KeyError as e... | 0 | 2016-07-06T05:34:21Z | [
"python",
"error-handling",
"styles"
] |
Memory Error in Python When Loading Dataset | 37,981,975 | <p>I'm trying to load the <a href="https://www.cs.toronto.edu/~kriz/cifar.html" rel="nofollow">Cifar-10</a> dataset. The code that I'm using using is from <a href="http://cs231n.stanford.edu/" rel="nofollow">this</a> class (I'm not enrolled though), and I keep getting told that there is a Memory Error. The code that l... | 1 | 2016-06-23T03:45:52Z | 38,090,799 | <p>I uninstalled the 32 bit version of Anaconda and installed the 64 bit one (which also uses 64 bit python) and it seemed to have gotten rid of the issue. I'm still unsure exactly why it didn't work before since it wasn't addressing enough memory to make a difference but this seems to have helped.</p>
| 0 | 2016-06-29T05:06:46Z | [
"python",
"image",
"memory"
] |
faster way to color cells in Excel via Python | 37,982,004 | <p>I have 3 dataframes difference_df, validatedOutput and initial_output all of same dimension. Also difference_df is defined as below.</p>
<pre><code>difference_df = validatedOutput == initial_output
</code></pre>
<p>I want to write validatedOutput to an Excel file, and color all those values in yellow where val... | 1 | 2016-06-23T03:49:40Z | 37,983,007 | <p>I'd try to write the two data sets (validated and initial) to two separate areas of the Excel file, e.g. two worksheets, and then use conditional formatting in Excel to do the coloring, rather than specifying colors via Python code.</p>
| 1 | 2016-06-23T05:27:43Z | [
"python",
"excel",
"pandas"
] |
Can not return a list from a recursive function | 37,982,117 | <p>I'm having an issue returning the result of a recursive function with Python.</p>
<p>My function needs to return a list of pairs of possible comparisons between integers in a range of max <code>list_upper_range</code>.</p>
<p>It's important that two ints are paired only once each pair.</p>
<p>The function behaves... | 0 | 2016-06-23T04:02:11Z | 37,982,153 | <p>python functions don't automatically return the last statement (the way ruby does), you have to do a </p>
<p><code>return generate_comparisons_list(list_upper_range, iter_start, list_of_cases)</code></p>
<p>at the end of your function.</p>
<p>Have a look <a href="https://repl.it/C5M4" rel="nofollow">here</a> to s... | 3 | 2016-06-23T04:06:10Z | [
"python",
"python-3.x",
"recursion"
] |
Can not return a list from a recursive function | 37,982,117 | <p>I'm having an issue returning the result of a recursive function with Python.</p>
<p>My function needs to return a list of pairs of possible comparisons between integers in a range of max <code>list_upper_range</code>.</p>
<p>It's important that two ints are paired only once each pair.</p>
<p>The function behaves... | 0 | 2016-06-23T04:02:11Z | 37,982,195 | <p>Your function <code>generate_comparisons_list()</code> is intended to return a list, but in the recursive call, the return value is discarded. Your need to return the result</p>
<pre><code>return generate_comparisons_list(list_upper_range, iter_start, list_of_cases)
</code></pre>
| 1 | 2016-06-23T04:10:46Z | [
"python",
"python-3.x",
"recursion"
] |
Python - Area of a Flag | 37,982,164 | <p>Trying to solve <a href="http://www.itmaybeahack.com/book/python-2.6/html/p05/p05c01_areas.html" rel="nofollow">Building Skills with Python</a>, area of a flag . I am trying to solve for the blue area however I'm off by about 2%. Additionally when I total up the other areas, the total does not equal the area of the ... | 0 | 2016-06-23T04:07:36Z | 37,982,203 | <p>Python is known to have issues dealing with floating point operations.</p>
<p>Here is more information for you <a href="https://docs.python.org/2/tutorial/floatingpoint.html" rel="nofollow">Floating Point Arithmetic: Issues and Limitations</a></p>
<p>Edit:
Also a previous Stack addressing the same/similar issue <a... | -3 | 2016-06-23T04:11:52Z | [
"python",
"precision",
"area"
] |
Python - Area of a Flag | 37,982,164 | <p>Trying to solve <a href="http://www.itmaybeahack.com/book/python-2.6/html/p05/p05c01_areas.html" rel="nofollow">Building Skills with Python</a>, area of a flag . I am trying to solve for the blue area however I'm off by about 2%. Additionally when I total up the other areas, the total does not equal the area of the ... | 0 | 2016-06-23T04:07:36Z | 37,982,301 | <p>Floating point precision issues aren't causing your calculations to be so significantly off. You've just got bugs in your code. Specifically, from your output, <code>Expected BLUE AREA is 0.355870</code> and <code>Actual BLUE AREA is 0.318644</code> are caused by using significantly different calculations.</p>
<p>A... | 0 | 2016-06-23T04:24:08Z | [
"python",
"precision",
"area"
] |
Python - Area of a Flag | 37,982,164 | <p>Trying to solve <a href="http://www.itmaybeahack.com/book/python-2.6/html/p05/p05c01_areas.html" rel="nofollow">Building Skills with Python</a>, area of a flag . I am trying to solve for the blue area however I'm off by about 2%. Additionally when I total up the other areas, the total does not equal the area of the ... | 0 | 2016-06-23T04:07:36Z | 37,982,393 | <p>First, it can be confusing to refer to 'length' and 'width' in this context; it would be better to use the vexillological terms 'hoist' (the dimension parallel to the flagpole) and 'fly' (the dimension perpendicular to the flagpole).</p>
<p>Second, your numbers are off. You're using <code>length*length_union</code>... | 0 | 2016-06-23T04:32:22Z | [
"python",
"precision",
"area"
] |
Python - Area of a Flag | 37,982,164 | <p>Trying to solve <a href="http://www.itmaybeahack.com/book/python-2.6/html/p05/p05c01_areas.html" rel="nofollow">Building Skills with Python</a>, area of a flag . I am trying to solve for the blue area however I'm off by about 2%. Additionally when I total up the other areas, the total does not equal the area of the ... | 0 | 2016-06-23T04:07:36Z | 37,984,212 | <p>Here's my calculation. The original problem had errors noted in comments below.</p>
<p><strong>Note:</strong> The <code>from __future__</code> makes division work like Python 3, where 1/2 = 0.5, not 0 like in Python 2. This cleans up the math.</p>
<p>Also, using same variables as the problem statement made it ea... | 2 | 2016-06-23T06:51:52Z | [
"python",
"precision",
"area"
] |
Pandas reindex and fill missing values: "Index must be monotonic" | 37,982,170 | <p>In answering <a href="http://stackoverflow.com/questions/37981678/how-to-align-indexes-of-many-dataframes-and-fill-in-respective-missing-values-in">this stackoverflow question</a>, I found some interesting behavior when using a fill method while reindexing a dataframe.</p>
<p>This <a href="https://github.com/pydata... | 1 | 2016-06-23T04:08:26Z | 37,982,276 | <p>Some element of <code>reindex</code> requires the incoming index to be sorted. I'm deducing that when <code>method</code> is passed, it fails to presort the incoming index and subsequently fails. I'm drawing this conclusion based on the fact that this works:</p>
<pre><code>print df.sort_index().reindex(newIndex.s... | 2 | 2016-06-23T04:20:58Z | [
"python",
"pandas",
"reindex"
] |
pandas DataFrame - find max between offset columns | 37,982,252 | <p>Suppose I have a pandas dataframe given by</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(5,2))
df
0 1
0 0.264053 -1.225456
1 0.805492 -1.072943
2 0.142433 -0.469905
3 0.758322 0.804881
4 -0.281493 0.602433
</code></pre>
<p>I want to ... | 1 | 2016-06-23T04:18:08Z | 37,982,331 | <p>You want to apply <code>max</code> to rows after having shifted the first column.</p>
<pre><code>pd.concat([df.iloc[:, 0].shift(), df.iloc[:, 1]], axis=1).apply(max, axis=1).dropna()
</code></pre>
| 1 | 2016-06-23T04:26:43Z | [
"python",
"pandas",
"dataframe"
] |
Python pandas groupby not working | 37,982,283 | <p>I want to do a pandas groupby on pr. ticker group. in below code. In order to calculate different KPIs pr. ticker in stocklist. Here i just show the col 'Difference' from the previous day. Obviously I do not want the difference between different tickers - that makes no sense - hence the groupby. But it does not work... | 1 | 2016-06-23T04:21:33Z | 37,982,467 | <p>After reviewing your code more closely, the scope in your <code>Screener</code> function is wrong. You're referencing <code>df</code> in that function without having passed a <code>df</code> parameter. This means that it is operating on the <code>df</code> variable defined in a scope outside of the function, namel... | 0 | 2016-06-23T04:39:16Z | [
"python",
"pandas",
"group-by"
] |
Unauthenticated error using gcloud-python to connect to google bigtable | 37,982,336 | <p>I've set up a Google Cloud BigTable cluster on my project. The main codebase for the project runs within a standard Python App Engine environment, which can't use the gcloud-python library because of the reliance on grpcio. To get around this, I've set up a Python App Engine Flexible Environment service within th... | 1 | 2016-06-23T04:27:19Z | 38,212,318 | <p>This issue is being tracked at <a href="https://github.com/GoogleCloudPlatform/gcloud-python/issues/1917" rel="nofollow">github</a>.</p>
| 0 | 2016-07-05T20:38:03Z | [
"python",
"google-app-engine",
"google-cloud-bigtable"
] |
two steps filtering, pandas | 37,982,584 | <p>I have a data frame with two columns: 'City' and 'Number'</p>
<pre><code>df = pd.DataFrame({'City':['1','1','3','4'],'Number':['3-1','42','23','3-4']})
</code></pre>
<p>If I want to filter by City, lets say City == 1. I can do this:</p>
<pre><code>df[df['City']=='1']
</code></pre>
<p>And got this:</p>
<pre><cod... | 1 | 2016-06-23T04:51:02Z | 37,982,642 | <p>Try:</p>
<pre><code>df[(df.City=='1') & (df.Number.str.contains('-'))]
</code></pre>
| 2 | 2016-06-23T04:56:12Z | [
"python",
"pandas",
"filter"
] |
cities_light don't have all the cities in my country? DJANGO | 37,982,666 | <p>I would like to know how to load all the data in cities_light of Django, I have 42 record when I run <code>python manage.py cities_light --force-import-all</code> or <code>python manage.py cities_light</code></p>
<p>in settings</p>
<pre><code>CITIES_LIGHT_TRANSLATION_LANGUAGES = ['es']
CITIES_LIGHT_INCLUDE_COUNTRI... | -1 | 2016-06-23T04:58:28Z | 37,985,990 | <p>Cities Light uses the open <a href="http://www.geonames.org/" rel="nofollow">Geonames</a> database. So it only knows the cities that are in the Geonames database. You can help and add missing cities there or fix the data on existing entries.</p>
<p>Also, there are <a href="http://download.geonames.org/export/dump/r... | 0 | 2016-06-23T08:23:01Z | [
"python",
"django",
"database"
] |
Count Distinct Group By Pandas Python | 37,982,699 | <p>Here's some sample data - </p>
<pre><code>ID Owner Activity
1 A W1
1 A W2
1 B W3
1 C W4
2 C W5
2 C W6
2 D W7
3 A W8
3 B W9
</code></pre>
<p>I want number of owners per ID. Output will be - </p>
<pre><code>ID Number of Owners
1 3
2 2
3 2
</code></pre>
<p>How can I do ... | 1 | 2016-06-23T05:02:10Z | 37,982,754 | <pre><code>df.groupby('ID').Owner.nunique()
</code></pre>
| 4 | 2016-06-23T05:07:06Z | [
"python",
"pandas",
"group-by",
"distinct"
] |
running octave/matlab code in interface mode | 37,982,718 | <p>If we run a program with <code>-i</code> flag in Python, the program gets executed and we enter interactive mode after executing the script. ( Which can be further used for debugging).</p>
<p>Example : <code>python -i exampleProgram.py</code>.</p>
<p>Is there a similar method to do the same in Octave?</p>
| 0 | 2016-06-23T05:03:39Z | 37,983,278 | <p><a href="https://www.gnu.org/software/octave/doc/v4.0.1/Command-Line-Options.html" rel="nofollow">Here</a> is a list of the command line arguments for Octave. You will see that it does support</p>
<blockquote>
<p>--interactive</p>
<p>-i</p>
<p>Force interactive behavior. This can be useful for running O... | 0 | 2016-06-23T05:48:34Z | [
"python",
"matlab",
"octave"
] |
running octave/matlab code in interface mode | 37,982,718 | <p>If we run a program with <code>-i</code> flag in Python, the program gets executed and we enter interactive mode after executing the script. ( Which can be further used for debugging).</p>
<p>Example : <code>python -i exampleProgram.py</code>.</p>
<p>Is there a similar method to do the same in Octave?</p>
| 0 | 2016-06-23T05:03:39Z | 37,984,738 | <p>What you are looking for is</p>
<pre><code>--persist Go interactive after --eval or reading from FILE.
</code></pre>
<p>see <code>octave --help</code> for a full list</p>
| 1 | 2016-06-23T07:19:16Z | [
"python",
"matlab",
"octave"
] |
Dynamically get an item on a django model object | 37,982,767 | <p>What I want to achieve is retrieving an item dynamically something like:</p>
<pre><code>x = "choice"
obj = Choices.objects.get(id=1)
obj[x]
</code></pre>
<p>not:</p>
<pre><code>obj.choice
</code></pre>
<p>The model is:</p>
<pre><code>class Choices(models.Model):
question = models.ForeignKey(Question)
ch... | 0 | 2016-06-23T05:08:02Z | 37,982,855 | <p>You could use:</p>
<pre><code>getattr(obj, x)
</code></pre>
| 5 | 2016-06-23T05:15:15Z | [
"python",
"django"
] |
PyQt - Displaying GIF While Other Function Runs | 37,982,872 | <p>I have an app that saves data to a file, and sometimes the save function takes quite awhile since my file is large. I wanted to have a "loading.gif" displayed while the file is being saved, but haven't figured out how to do so. Here is my code:</p>
<pre><code>def saveBook(self):
self.loadingWidget.setHidden(not... | 0 | 2016-06-23T05:16:07Z | 37,997,187 | <p>The GUI won't update while QT is processing other code in the main event loop. Generally, when you have long-running processes that you don't want to block the GUI, you would push those operations into a separate thread.</p>
| 0 | 2016-06-23T16:32:38Z | [
"python",
"pyqt",
"pyqt4",
"pyside"
] |
Port binding fails for script after 60 seconds when deployed to heroku | 37,982,925 | <p>So I was fooling around the slack API and ended up making a simple slack bot which posts on a slack channel whether a site is up or not (when provided with the URL)</p>
<p>Whenever I deploy it to heroku, it works for the first 60 seconds and then throws an error like this in the logs</p>
<pre><code>2016-06-22T20:1... | 0 | 2016-06-23T05:20:40Z | 37,999,224 | <p>I solved this problem by running a simple HTTP server on the port provided by Heroku and made it run as a background process. </p>
<p>After the changes, my <code>Procfile</code> looks like this</p>
<pre><code>web: (python -m http.server $PORT &) && (python margo/margo.py)
</code></pre>
<p>So, even tho... | 0 | 2016-06-23T18:30:29Z | [
"python",
"heroku",
"deployment"
] |
Create Dictionary List from XML in Python | 37,983,095 | <p>This is the sample XML.</p>
<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="UTF-8"?>
<Test plan_name="test">
<Big bro="S7" sys="lolipop">
<Work name="first"></Work>
<Work name="second"></Work>
</Big>
<Big bro="S6" sy... | 1 | 2016-06-23T05:33:58Z | 37,983,255 | <p>You modify your <code>test</code> dict in-place which result in a modification of the previously inserted reference in total as well.<br>
It should work by creating a copy of it before updating it: </p>
<pre><code>...
for child in root.findall('Big'):
test=child.attrib
for children in child:
testCopy = ... | 1 | 2016-06-23T05:47:06Z | [
"python",
"xml",
"list"
] |
Matplotlib: How to get same "base" and "offset" parameters for axis ticks and axis tick labels | 37,983,153 | <p>I want to plot a series of values against a date range in matplotlib. I changed the tick <code>base</code> parameter to 7, to get one tick at the beginning of every week (<code>plticker.IndexLocator, base = 7</code>). The problem is that the <code>set_xticklabels</code> function does not accept a <code>base</code> p... | 0 | 2016-06-23T05:38:32Z | 38,027,204 | <p>The reason your ticklabels went bad is that <a href="http://stackoverflow.com/questions/15123928/matplotlib-change-yaxis-tick-labels#comment26811197_16329458">setting manual ticklabels decouples the labels from your data</a>. The proper approach is to use a <code>Formatter</code> according to your needs. Since you h... | 0 | 2016-06-25T09:57:46Z | [
"python",
"matplotlib",
"plot",
"axis-labels"
] |
Matplotlib: How to get same "base" and "offset" parameters for axis ticks and axis tick labels | 37,983,153 | <p>I want to plot a series of values against a date range in matplotlib. I changed the tick <code>base</code> parameter to 7, to get one tick at the beginning of every week (<code>plticker.IndexLocator, base = 7</code>). The problem is that the <code>set_xticklabels</code> function does not accept a <code>base</code> p... | 0 | 2016-06-23T05:38:32Z | 38,065,683 | <p>Many thanks - your solution perfectly works. For the case that other people run into the same issue in the future: i have implemented the above-mentioned solution but also added some code so that the tick labels keep the desired rotation and also align (with their left end) to the respective tick. May not be pythoni... | 0 | 2016-06-28T01:29:02Z | [
"python",
"matplotlib",
"plot",
"axis-labels"
] |
wxWidgets: Panel inside BoxSizer doesn't behaviours as expected | 37,983,186 | <p>I use <code>Panel</code> to draw images from <code>OpenCV</code>, but it seems this <code>panel</code> cannot be placed into <code>BoxSizer</code>. I tried to do</p>
<pre><code>vbox = wx.BoxSizer(wx.VERTICAL)
panel.SetSizer(vbox)
vbox.Add(wx.Button(panel, label='aaa', size=(70, 30)))
vbox.Add(wx.Button(panel, label... | 2 | 2016-06-23T05:40:47Z | 38,002,000 | <p>This is likely the source of the problem:</p>
<blockquote>
<p>vbox.Add(OpenCVCanvas(self), border=10)</p>
</blockquote>
<p>You are creating buttons that are children of <code>panel</code> and addign them to the sizer which is set to the the <code>panel</code>'s sizer, but the <code>OpenCVCanvas</code> is using <... | 2 | 2016-06-23T21:15:35Z | [
"python",
"opencv",
"wxpython",
"wxwidgets",
"wx"
] |
Receiving onesignal.com notifications | 37,983,188 | <p>I would like my program to receive 3rd party notifications sent using the OneSignal (<a href="http://onesignal.com" rel="nofollow">http://onesignal.com</a>) platform.</p>
<p>Is there any (Python) client for it or is?</p>
| 0 | 2016-06-23T05:41:29Z | 38,004,285 | <p>OneSignal push notifications work on Android, iOS, Amazon FireOS, and Windows Phone. There isn't a Python client side library as this isn't normally used for mobile app development.</p>
| 0 | 2016-06-24T01:20:23Z | [
"python",
"push-notification",
"onesignal"
] |
Enumeration function Argument | 37,983,247 | <p>Python enumeration function enumerate takes one argument <strong><em>start</em></strong>.
What is the use of this argument ?
If i write some code using this argument it shifts only index e.g.</p>
<pre><code>>>a=[2,3,4,5,6,7]
>>for index,value in enumerate(a,start=2):
... print index,value
... ... | -1 | 2016-06-23T05:46:35Z | 37,983,340 | <p><code>enumerate()</code> associates a sequence of integers with an iterable, i.e. it enumerates the items of the sequence. Its argument <code>start</code> is not meant to affect the starting position within the iterable, just the initial value from which to start counting.</p>
<p>One use is to start the enumeration... | 1 | 2016-06-23T05:53:49Z | [
"python"
] |
Enumeration function Argument | 37,983,247 | <p>Python enumeration function enumerate takes one argument <strong><em>start</em></strong>.
What is the use of this argument ?
If i write some code using this argument it shifts only index e.g.</p>
<pre><code>>>a=[2,3,4,5,6,7]
>>for index,value in enumerate(a,start=2):
... print index,value
... ... | -1 | 2016-06-23T05:46:35Z | 37,983,527 | <p>Some people - most I suppose - aren't used to an enumerated list starting at zero. At the very least, this makes it easy to format the output so the enumeration starts at one, e.g.</p>
<pre><code>a = ['Fred', 'Ted', 'Bob', 'Alice']
for index, value in enumerate(a, start=1):
print index, value
</code></pre>
<p>... | 0 | 2016-06-23T06:08:13Z | [
"python"
] |
Python Regex to exclude the email domain and special character and extract @user in the twitter | 37,983,289 | <p>I have a string twitter text as following:</p>
<pre><code>str = "RT@aquage_7: ç°@tianke ãã£(´ã»Ïã»ï½) @_@, ï¼ __ç°ç§,
my email is tian@gmail.com, his@kate, I like @lucyãã,
and her email is kate@163.cn".
</code></pre>
<p>The regex pattern is: </p>
<pre><code>p_name3 = re.compile(r'[@ï¼ ]([a-zA-... | 1 | 2016-06-23T05:49:35Z | 37,984,637 | <p>Here is an example of the native Twitter's API user mentions parsing (using <a href="https://github.com/tweepy/tweepy" rel="nofollow">tweepy</a>) :</p>
<pre><code>import tweepy
consumer_key='put_key_here'
consumer_secret='put_secret_here'
access_token='put_key_here'
access_token_secret='put_secret_here'
auth = tw... | 2 | 2016-06-23T07:13:59Z | [
"python",
"regex",
"twitter"
] |
Python Regex to exclude the email domain and special character and extract @user in the twitter | 37,983,289 | <p>I have a string twitter text as following:</p>
<pre><code>str = "RT@aquage_7: ç°@tianke ãã£(´ã»Ïã»ï½) @_@, ï¼ __ç°ç§,
my email is tian@gmail.com, his@kate, I like @lucyãã,
and her email is kate@163.cn".
</code></pre>
<p>The regex pattern is: </p>
<pre><code>p_name3 = re.compile(r'[@ï¼ ]([a-zA-... | 1 | 2016-06-23T05:49:35Z | 37,985,223 | <p>Use the twitter API if you can. But if you are looking for a simple string solution, break the problem into two steps. First, locate and remove any likely email addresses, then use your regex to find twitter @mentions. </p>
<p>Adapting the first email matching regex from <a href="http://www.regular-expressions.info... | 0 | 2016-06-23T07:44:29Z | [
"python",
"regex",
"twitter"
] |
Python, copy only directories | 37,983,360 | <p>I have a program that has a list of some files. I have to copy only the directories and the subdirectories from the list to a specified directories and don't need to copy the files. I tried this, but it doesn't work.</p>
<pre><code>def copiarDirs():
items = list.curselection()
desti = tkFileDialog.ask... | 1 | 2016-06-23T05:55:36Z | 37,984,628 | <p>Try this:</p>
<pre><code>import os
def copyDirs(source, destination):
for subdir, dirs, files in os.walk(source):
for f in files:
dir = destination + os.path.join(subdir).split(':')[1]
if not os.path.exists(dir):
os.makedirs(dir)
sourceDir = 'D:\\Work\\'
destDir... | 0 | 2016-06-23T07:13:32Z | [
"python",
"directory",
"copy",
"subdirectory"
] |
Dynamic Programming Pr0blem on coins | 37,983,451 | <p>Consider a below problem</p>
<blockquote>
<p>Given an infinite number of nickels(5 cents) and pennies(1 cent). Write a code to calculate a number of ways of representing n cents.</p>
</blockquote>
<p>My code</p>
<pre><code>def coins(n):
if (n < 0):
return 0
elif (n == 0):
return 1
... | 4 | 2016-06-23T06:02:23Z | 37,983,523 | <p>While your implementation is a twist of the typical <a href="http://www.algorithmist.com/index.php/Coin_Change" rel="nofollow">Coin Change Problem</a> with 1 dimension less which may cause you double count a lot of the combinations, I think it is not that complicated for the given coin system.</p>
<p>I think the so... | 2 | 2016-06-23T06:08:07Z | [
"python",
"recursion",
"dynamic-programming",
"memoization"
] |
Dynamic Programming Pr0blem on coins | 37,983,451 | <p>Consider a below problem</p>
<blockquote>
<p>Given an infinite number of nickels(5 cents) and pennies(1 cent). Write a code to calculate a number of ways of representing n cents.</p>
</blockquote>
<p>My code</p>
<pre><code>def coins(n):
if (n < 0):
return 0
elif (n == 0):
return 1
... | 4 | 2016-06-23T06:02:23Z | 37,984,069 | <p>Instead of using a 1-dimensional list, you can use a 2-dimensional array where one dimension is the total, and the second dimension is the largest-value coin available.</p>
<p>Let's say <code>C</code> is your list of coin values in ascending order (in your example, <code>C = [1, 5]</code>). Then let <code>A[i][j]<... | 2 | 2016-06-23T06:43:43Z | [
"python",
"recursion",
"dynamic-programming",
"memoization"
] |
Saving a key from a dictionary without value | 37,983,754 | <p>I am representing a weighted graph as a dictionary where the key represents a vertex and the following lists represent the edges incident on the vertex (first number weight of edge and second number adjacent vertex):</p>
<pre><code>wGraph = { 1 : [[2, 2],[3, 4],[3, 3]],
3 : [[3, 2],[5, 4],[7, 5]],
2 :... | 1 | 2016-06-23T06:24:09Z | 37,983,893 | <p>To make a random choice from some values, use <code>random.choice</code>. You want to choose from the keys of the dictionary, so that's exactly what you pass in:</p>
<pre><code>random.choice(wGraph.keys())
</code></pre>
| 3 | 2016-06-23T06:33:31Z | [
"python",
"dictionary",
"graph"
] |
Saving a key from a dictionary without value | 37,983,754 | <p>I am representing a weighted graph as a dictionary where the key represents a vertex and the following lists represent the edges incident on the vertex (first number weight of edge and second number adjacent vertex):</p>
<pre><code>wGraph = { 1 : [[2, 2],[3, 4],[3, 3]],
3 : [[3, 2],[5, 4],[7, 5]],
2 :... | 1 | 2016-06-23T06:24:09Z | 37,984,122 | <pre><code>import random
visited = []
def random_key():
wGraph = {1: [[2, 2], [3, 4], [3, 3]],
3: [[3, 2], [5, 4], [7, 5]],
2: [[2, 1], [4, 4], [3, 6]],
4: [[3, 1], [4, 2], [1, 6], [5, 3]],
6: [[3, 2], [1, 4], [8, 5]],
5: [[7, 3], [8, 6], [9, 7... | 0 | 2016-06-23T06:46:43Z | [
"python",
"dictionary",
"graph"
] |
Saving a key from a dictionary without value | 37,983,754 | <p>I am representing a weighted graph as a dictionary where the key represents a vertex and the following lists represent the edges incident on the vertex (first number weight of edge and second number adjacent vertex):</p>
<pre><code>wGraph = { 1 : [[2, 2],[3, 4],[3, 3]],
3 : [[3, 2],[5, 4],[7, 5]],
2 :... | 1 | 2016-06-23T06:24:09Z | 37,984,176 | <p>The answer depends on the details -- how many keys do you have, are they always numbers 1...max, do you want to revisit keys you've already visited before, are graph nodes added over time or do they stay constant, will you eventually visit all keys or only a small percentage of them, and so on.</p>
<p>One idea: if ... | 3 | 2016-06-23T06:49:30Z | [
"python",
"dictionary",
"graph"
] |
Remove pre heades from csv before using DictReader - Python | 37,984,073 | <p>Hi I have csv file like this </p>
<pre><code>here is some text
some more text
summary
id score
1 33
2 22
3 11
detail
id try score
1 1 22
1 2 11
2 1 10
2 2 12
3 1 11
</code></pre>
<p>I want to parse the data id, try, score which comes after detail to DictReader
How can I do that?</p>
| 0 | 2016-06-23T06:43:49Z | 37,989,136 | <p>You can take a look at this :</p>
<pre><code>import csv
with open('file.txt', 'r') as f:
text = f.read()
relevant_lines = text.split('detail \n')[1].splitlines()
d_reader = csv.DictReader(relevant_lines, delimiter= ' ', skipinitialspace=True)
print(d_reader.fieldnames)
for row in d_reader:
print(row)
<... | 0 | 2016-06-23T10:33:42Z | [
"python",
"csv",
"parsing"
] |
Python, listing the attributes of a parameter | 37,984,162 | <p>This question may be a little green.</p>
<p>In the example below, I am trying to find out a list of the attribtues from the "message" parameter.</p>
<pre><code>@respond_to("^meow")
def remind_me_at(self, message):
fre = "asd: %s " % str(message.sender)
fre = "asd: %s " % str(message.mention_name)
fren ... | 2 | 2016-06-23T06:48:39Z | 37,984,202 | <p>Use the <code>dir()</code> built-in function. It returns a list of all attributes of an object.</p>
<pre><code>print dir(message)
</code></pre>
| 2 | 2016-06-23T06:51:27Z | [
"python",
"introspection",
"inspect"
] |
Python, listing the attributes of a parameter | 37,984,162 | <p>This question may be a little green.</p>
<p>In the example below, I am trying to find out a list of the attribtues from the "message" parameter.</p>
<pre><code>@respond_to("^meow")
def remind_me_at(self, message):
fre = "asd: %s " % str(message.sender)
fre = "asd: %s " % str(message.mention_name)
fren ... | 2 | 2016-06-23T06:48:39Z | 37,984,569 | <h2>dir</h2>
<pre><code>dir([object]) -> list of strings
If called without an argument, return the names in the current scope.
Else, return an alphabetized list of names comprising (some of) the
attributes of the given object, and of attributes reachable from it.
If the object supplies a method named __dir__, it ... | 2 | 2016-06-23T07:10:35Z | [
"python",
"introspection",
"inspect"
] |
Python, listing the attributes of a parameter | 37,984,162 | <p>This question may be a little green.</p>
<p>In the example below, I am trying to find out a list of the attribtues from the "message" parameter.</p>
<pre><code>@respond_to("^meow")
def remind_me_at(self, message):
fre = "asd: %s " % str(message.sender)
fre = "asd: %s " % str(message.mention_name)
fren ... | 2 | 2016-06-23T06:48:39Z | 37,984,730 | <p>The <code>dir</code> command, as noted by Rob, is a able to list the attributes. This is handy when you're trying to debug running code.</p>
<p>Provided you can have an interactive session with the code (you know, just running the ol' REPL interpretor) then try:</p>
<pre><code>>>> help(message)
</code></p... | 1 | 2016-06-23T07:19:01Z | [
"python",
"introspection",
"inspect"
] |
pure numpy expression for selecting same-length subarrays with different starting indices from 3-D array | 37,984,214 | <p>I have a 3-D <code>numpy</code> array (let's call it <code>a</code>) with shape <code>(74, 74, 4563)</code>, and I want to extract a length-<code>n</code> sub-array from each location in the first two dimensions. However, each of those sub-arrays starts in a different place, depending on the indices in the first two... | 1 | 2016-06-23T06:52:02Z | 37,985,433 | <p>Something along this line has been asked before, but for 2d. I may try to look that up.</p>
<p>But here's quick example of what was going on in the 2d case</p>
<pre><code>In [1463]: x=np.arange(12).reshape(3,4)
In [1464]: ix0=np.array([0,2,1])
In [1465]: N=2
</code></pre>
<p>We could iterate over each row of <co... | 3 | 2016-06-23T07:55:39Z | [
"python",
"numpy"
] |
Python, Why is my script not running? | 37,984,332 | <p>I've made a script to calculate the probability of a point in a tennis match, depending on the current score.</p>
<p>But for some reason when I want to run my script nothing happens. Explination is on the script.</p>
<p>Any suggestions?</p>
<pre><code> ## calculate the probability of server winning a single ga... | -4 | 2016-06-23T06:58:34Z | 37,984,360 | <p>Do you call the <code>gameProb</code> anywhere? Common practice is using this pattern:</p>
<pre><code>if __name__ == "__main__":
gameProb()
</code></pre>
<p>and make return lowercase.</p>
| 4 | 2016-06-23T07:00:18Z | [
"python"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.