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 listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
keep getting an error 'function @ 0xb6ff9924 (or something similar)' | 38,300,169 | <p>I am attempting to create a little program that will calculate the area of a shape. When ever I put in the name of the shape it prints out "function at 0xetc". I am having a heck of a time figure out where the issue is. I know that my <code>area</code> function is probably messed up but I can't get there to debug it... | 0 | 2016-07-11T06:08:21Z | 38,300,424 | <p>You have in total 6 errors that you need to fix:</p>
<ul>
<li>In <code>area()</code> class, remove all the 4 return instructions you have.</li>
<li>As the 4 methods you are calling in area() return values, you need to display their results by: <code>print method_name(arguments)</code></li>
<li>Finally, you will hav... | 0 | 2016-07-11T06:27:53Z | [
"python",
"python-2.7",
"function",
"raw-input"
] |
keep getting an error 'function @ 0xb6ff9924 (or something similar)' | 38,300,169 | <p>I am attempting to create a little program that will calculate the area of a shape. When ever I put in the name of the shape it prints out "function at 0xetc". I am having a heck of a time figure out where the issue is. I know that my <code>area</code> function is probably messed up but I can't get there to debug it... | 0 | 2016-07-11T06:08:21Z | 38,300,786 | <p>your main problem is simple, you don't call the functions.</p>
<p>In your last line <code>print area</code> what you get there is the position in memory where that function is located, you need to call it as <code>print area(s)</code> with your previously defined variable <code>s</code>. </p>
<p>Then in your funct... | 0 | 2016-07-11T06:54:29Z | [
"python",
"python-2.7",
"function",
"raw-input"
] |
keep getting an error 'function @ 0xb6ff9924 (or something similar)' | 38,300,169 | <p>I am attempting to create a little program that will calculate the area of a shape. When ever I put in the name of the shape it prints out "function at 0xetc". I am having a heck of a time figure out where the issue is. I know that my <code>area</code> function is probably messed up but I can't get there to debug it... | 0 | 2016-07-11T06:08:21Z | 38,301,668 | <p>I think you get confused with function name and its return value, here is what learned from <a href="http://interactivepython.org/courselib/static/thinkcspy/Functions/functions.html" rel="nofollow">How to Think Like a Computer Scientist</a>:</p>
<p>"In Python, a function is a named sequence of statements that belon... | 0 | 2016-07-11T07:47:01Z | [
"python",
"python-2.7",
"function",
"raw-input"
] |
Exploring a website's Source code on Python and Text to Speech | 38,300,317 | <p>I'm new to python and this forum. I am currently using PyCharm, and using it to make a simple code that prints the source code of website on the screen. I saw a video and the code was something like: </p>
<pre><code>import requests
from bs4 import BeautifulSoup4
url = "Google.com"
S = requests.get(url)
C = s.text... | -3 | 2016-07-11T06:19:30Z | 38,331,181 | <p>I got it to work . It was I guess , a bug ...
I did this at the end </p>
<pre><code>import requests
len=20 #length of string u want to copy
Url="some random url"
T1=requests.get(Url)
T2=T1.content
Pos=T2.find("Search string")
String=T2[pos:pos+len]
print(String)
</code></pre>
<p>In my original project the string ... | 0 | 2016-07-12T14:04:44Z | [
"python",
"website",
"text-to-speech",
"speech-recognition-api"
] |
Pandas: how to merge df with condition | 38,300,461 | <p>I have df</p>
<pre><code>number A B C
123 10 10 1
123 10 11 1
123 18 27 1
456 10 18 2
456 42 34 2
789 13 71 3
789 19 108 3
789 234 560 4
</code></pre>
<p>and second df </p>
<pre><code>number A B
123 18 27
456 32 19
... | 1 | 2016-07-11T06:31:28Z | 38,300,613 | <p>One way is to give df2 a dummy column:</p>
<pre><code>In [11]: df2["in_df2"] = True
</code></pre>
<p>then you can do the merge:</p>
<pre><code>In [12]: df1.merge(df2, how="left")
Out[12]:
number A B C in_df2
0 123 10 10 1 NaN
1 123 10 11 1 NaN
2 123 18 27 1 True
3 ... | 4 | 2016-07-11T06:42:44Z | [
"python",
"pandas"
] |
For loop not iterating through all values of a dictionary | 38,300,476 | <p>I'm trying to retrieve data from a webpage (<a href="http://python-data.dr-chuck.net/comments_295023.json" rel="nofollow">http://python-data.dr-chuck.net/comments_295023.json</a>), parse it in Python using JSON, and perform some operations on it. However, I've run into a roadblock.</p>
<p>This is my code:</p>
<pre... | 0 | 2016-07-11T06:32:45Z | 38,300,521 | <p>It is because most of your data is inside 'comments' key. Try this</p>
<pre><code>for item in info:
print item
if item == 'comments':
for x in info['comments']:
print x['count']
print x['name']
</code></pre>
| 0 | 2016-07-11T06:36:11Z | [
"python",
"json",
"python-2.7"
] |
For loop not iterating through all values of a dictionary | 38,300,476 | <p>I'm trying to retrieve data from a webpage (<a href="http://python-data.dr-chuck.net/comments_295023.json" rel="nofollow">http://python-data.dr-chuck.net/comments_295023.json</a>), parse it in Python using JSON, and perform some operations on it. However, I've run into a roadblock.</p>
<p>This is my code:</p>
<pre... | 0 | 2016-07-11T06:32:45Z | 38,300,523 | <p>Your first example worked <em>just fine</em>. You are iterating over a <em>dictionary</em>, one with two keys, <code>'note'</code> and <code>'comments'</code>. Iteration yields those keys, and you printed them.</p>
<p>Just access either key:</p>
<pre><code>print info['comments']
print info['note']
</code></pre>
<... | 1 | 2016-07-11T06:36:13Z | [
"python",
"json",
"python-2.7"
] |
For loop not iterating through all values of a dictionary | 38,300,476 | <p>I'm trying to retrieve data from a webpage (<a href="http://python-data.dr-chuck.net/comments_295023.json" rel="nofollow">http://python-data.dr-chuck.net/comments_295023.json</a>), parse it in Python using JSON, and perform some operations on it. However, I've run into a roadblock.</p>
<p>This is my code:</p>
<pre... | 0 | 2016-07-11T06:32:45Z | 38,300,630 | <p>As I saw in you link is your data struct a dict of lists of dicts. Use </p>
<pre><code>for key, item in info.iteritems()
</code></pre>
<p>This will supply th output you need. Note that for the inner dicts you need another loop. </p>
| 0 | 2016-07-11T06:43:49Z | [
"python",
"json",
"python-2.7"
] |
Compare two csv files and add columns that are not common in both of them | 38,300,666 | <p>I have to CSV files Book1 and Book2. The columns in Book1 are <code>A, B, C, D, E</code> and in Book2 are <code>A, B, E, H.</code>
I want to modify Book2 in such a way that it contains only those column names that are common with Book1 plus whatever additional is there in Book1. The files are :</p>
<p>Book1</p>
<... | 2 | 2016-07-11T06:46:03Z | 38,300,717 | <p>Use <code>reindex</code> on <code>book2</code>'s columns with <code>book1</code>'s columns. You'll have to transpose first, then transpose back.</p>
<pre><code>book2.T.reindex(book1.columns).T
</code></pre>
<p><a href="http://i.stack.imgur.com/IP2bY.png" rel="nofollow"><img src="http://i.stack.imgur.com/IP2bY.png... | 3 | 2016-07-11T06:48:57Z | [
"python",
"python-2.7",
"csv",
"pandas"
] |
Chat server using python tkinter | 38,300,749 | <p>I found this code for a simple chat server here <a href="http://www.ibm.com/developerworks/linux/tutorials/l-pysocks/" rel="nofollow">http://www.ibm.com/developerworks/linux/tutorials/l-pysocks/</a> and it works using telnet. It works so beautifully and i really want to modify it to have a GUI.<br/>
What I want to ... | -2 | 2016-07-11T06:51:30Z | 38,303,412 | <p>Although this Question is really very broad, I think a hint to "where to look" / "where to ask" would be okay.</p>
<p>As TigerhawkT3 already commented - <i>"if you have a specific issue that you cannot resolve through independent research, ask a new question"</i></p>
<p>What I get from your question is that there ... | 0 | 2016-07-11T09:25:11Z | [
"python",
"user-interface",
"tkinter",
"client-server",
"chat"
] |
Python TCP raw socket not listening on lo (localhost/ 127.0.0.1) | 38,300,753 | <p>I created a simple packet sniffer using raw socket in Python.</p>
<pre><code>import socket
s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_TCP)
while True:
print s.recvfrom(1600)
</code></pre>
<p>The internet traffic it's showing. But when I turn the primary network interface down and send ... | 0 | 2016-07-11T06:51:53Z | 38,300,937 | <p>On Linux :</p>
<pre><code>soc = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(3))
soc.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 2**30)
soc.bind(("eth0",0x0003))
</code></pre>
<p>Need to open <code>RAW</code> not <code>TCP</code>.</p>
<p>Edit for comment :</p>
<pre><code>a = soc.recvform(655... | 1 | 2016-07-11T07:03:03Z | [
"python",
"sockets",
"localhost"
] |
Django: Database caching to store web service result | 38,300,858 | <p>I have a method to load all ideas from <code>database</code>. There are few comments on each idea. </p>
<p>I have store <code>users id</code> who commented on ideas, in respective table.</p>
<p>I have a <code>web service</code> which contains all the data related to <code>user id</code></p>
<p>When i load a page,... | 0 | 2016-07-11T06:58:49Z | 38,301,220 | <p>The Django documentation on the <a href="https://docs.djangoproject.com/en/1.9/topics/cache/" rel="nofollow">cache framework</a> is pretty easy to follow and will show you exactly how to set up a database cache for pages and other things in your views, including for how long you'd like the cache to exist, <code>TIME... | 1 | 2016-07-11T07:19:45Z | [
"python",
"django",
"database",
"caching"
] |
How to find an azure vm cpu utilization statistics, using python azurerm sdk | 38,300,896 | <p>I am not able to find the cpu utilization of an azurerm using azurerm python sdk. </p>
| 0 | 2016-07-11T07:00:46Z | 38,346,882 | <p>@Ramani, I don't know there are any APIs of Azure SDK for Python which can directly get the Azure VM CPU utilization data, even Azure REST APIs.</p>
<p>However, there is a way to help you getting the VM diagnostic data which includes CPU utilization, please see below.</p>
<ol>
<li>You need to refer to the article ... | 0 | 2016-07-13T08:50:53Z | [
"python",
"azure",
"azure-virtual-machine",
"azure-sdk-python"
] |
How to run kivy after 1.9.1 on windows? | 38,301,047 | <p>After the installation of Kivy 1.9.1 on Windows using the commands of Kivy installation tutorials, I can't run the program using "kivy ***.py". I don't know how to set up the environment variables, and I can't find it on the official websites.</p>
<ul>
<li>Kivy: 1.9.1</li>
<li>Python: 3.4.4</li>
<li>Windows 10</li>... | 0 | 2016-07-11T07:09:21Z | 38,301,272 | <p>Make sure you're running the command from the folder where the <strong>*.py file is located, "kivy *</strong>.py" should run from there.</p>
| 1 | 2016-07-11T07:22:36Z | [
"python",
"environment-variables",
"kivy"
] |
How to run kivy after 1.9.1 on windows? | 38,301,047 | <p>After the installation of Kivy 1.9.1 on Windows using the commands of Kivy installation tutorials, I can't run the program using "kivy ***.py". I don't know how to set up the environment variables, and I can't find it on the official websites.</p>
<ul>
<li>Kivy: 1.9.1</li>
<li>Python: 3.4.4</li>
<li>Windows 10</li>... | 0 | 2016-07-11T07:09:21Z | 39,752,083 | <p>To run kivy application on windows it's simply </p>
<pre><code>python *.py
</code></pre>
<p>But on MacOS it should be </p>
<pre><code>kivy *.py
</code></pre>
| 0 | 2016-09-28T15:42:34Z | [
"python",
"environment-variables",
"kivy"
] |
python compare two excel sheet and append correct record | 38,301,076 | <p>I need to create an excel sheet comparing two sample sheets one contains the serial number and other information. Second sheet contains the warranty date. For example,
source1 sheet contains data as below</p>
<pre><code>Model Serial Location
Dell 1234 A
Thoshiba 2345 B
Apple 34... | 0 | 2016-07-11T07:11:28Z | 38,301,158 | <p>Install <a href="http://pandas.pydata.org/pandas-docs/version/0.18.0/" rel="nofollow"><code>pandas</code></a>, then you can load each sheet as a dataframe and join by the <code>Serial</code>:</p>
<pre><code>import pandas as pd
source1_df = pd.read_excel('path/to/excel', sheetname='source1_sheet_name')
source2_df =... | 0 | 2016-07-11T07:16:02Z | [
"python",
"excel",
"sorting",
"comparison"
] |
python compare two excel sheet and append correct record | 38,301,076 | <p>I need to create an excel sheet comparing two sample sheets one contains the serial number and other information. Second sheet contains the warranty date. For example,
source1 sheet contains data as below</p>
<pre><code>Model Serial Location
Dell 1234 A
Thoshiba 2345 B
Apple 34... | 0 | 2016-07-11T07:11:28Z | 38,367,726 | <p>try the below code, which I modified :</p>
<pre><code>import pandas as pd
source1_df = pd.read_excel('a.xlsx', sheetname='source1')
source2_df = pd.read_excel('a.xlsx', sheetname='source2')
joined_df = pd.merge(source1_df,source2_df,on='Serial',how='outer')
joined_df.to_excel('/home/user1/test/result.xlsx')
</code... | 1 | 2016-07-14T07:11:16Z | [
"python",
"excel",
"sorting",
"comparison"
] |
Find variable in files using RegEx | 38,301,211 | <p>I want read out variable which is mentioned below in file.</p>
<pre><code>#define xyz_u8 abc_0x0_u8 = 0x0 (for hex)
#define xyz_f16 abc_MOD1_f32 = -0.1f (for int and float)
#define xyz abc_YY = YY_ZZ (for others)
</code></pre>
<p>I am using </p>
<pre><code>re.compile(r"^#define\s+(\w+)\s+(\w+)(0[xX][0-9a-fA-F]+)"... | 2 | 2016-07-11T07:19:16Z | 38,301,374 | <p>I suggest</p>
<pre><code>^#define\s+(\w+)\s+(\w+) = (.+)
</code></pre>
<p>Use it with the <code>re.I</code> and <code>re.M</code> (if you have multiline input).</p>
<p>See the <a href="https://regex101.com/r/jF2zI3/1" rel="nofollow">regex demo</a></p>
<p><strong>Pattern explanation</strong>:</p>
<ul>
<li><code>... | 1 | 2016-07-11T07:28:55Z | [
"python",
"regex"
] |
Do properties support inheritance? | 38,301,453 | <p>In my code class <code>A</code> has a property, but class <code>B</code> doesn't inherit it. Does <code>@property</code> support inheritance? Or is it my fault?</p>
<pre><code>class A(object):
def __init__(self):
self._x = 100
@property
def x(self):
return self._x
@x.setter
de... | 2 | 2016-07-11T07:34:21Z | 38,301,569 | <p>It just doesn't know where to get <code>x</code> from. You can do this instead:</p>
<pre><code>class A(object):
def __init__(self):
self._x = 100
@property
def x(self):
return self._x
class B(A):
@A.x.setter
def x(self, v):
self._x = v
</code></pre>
| 2 | 2016-07-11T07:40:46Z | [
"python",
"inheritance",
"properties"
] |
Do properties support inheritance? | 38,301,453 | <p>In my code class <code>A</code> has a property, but class <code>B</code> doesn't inherit it. Does <code>@property</code> support inheritance? Or is it my fault?</p>
<pre><code>class A(object):
def __init__(self):
self._x = 100
@property
def x(self):
return self._x
@x.setter
de... | 2 | 2016-07-11T07:34:21Z | 38,302,045 | <p>The <code>NameError</code> is because <code>x</code> isn't in the global scope; it's defined within <code>A</code>'s class namespace, so you need to access it there explicitly by using <code>A.x</code>. This is a pretty common mistake, see e.g. <a href="http://stackoverflow.com/q/3648564/3001761">python subclass acc... | 2 | 2016-07-11T08:09:15Z | [
"python",
"inheritance",
"properties"
] |
How do I check if a number is divisible by every number in a list | 38,301,588 | <p>I'm totally helpless about this, the only solutions I found are using generators (which I don't understand, because I've just started "trying to code").</p>
<p>Here is my code: </p>
<pre><code>x = 9
PrimeCount = 4
PrimeList = [2, 3, 5, 7]
while PrimeCount < 10002:
if all():
y == x
PrimeLi... | 1 | 2016-07-11T07:42:09Z | 38,301,867 | <blockquote>
<p>How do I check if a number is divisible by every number in a list</p>
</blockquote>
<pre><code>>>> def divisible(n, lst):
... return all(map(lambda y: n%y == 0, lst))
...
>>> divisible(10, [2,5])
True
>>> divisible(10, [2,5, 7])
False
</code></pre>
<p>Just check i... | 0 | 2016-07-11T07:59:00Z | [
"python",
"list",
"solution"
] |
How do I check if a number is divisible by every number in a list | 38,301,588 | <p>I'm totally helpless about this, the only solutions I found are using generators (which I don't understand, because I've just started "trying to code").</p>
<p>Here is my code: </p>
<pre><code>x = 9
PrimeCount = 4
PrimeList = [2, 3, 5, 7]
while PrimeCount < 10002:
if all():
y == x
PrimeLi... | 1 | 2016-07-11T07:42:09Z | 38,302,017 | <p>I'm going to write the code in C++ but I'm sure you'll be able to understand and implement it:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>int x = 9;
int PrimeCount ... | -1 | 2016-07-11T08:08:11Z | [
"python",
"list",
"solution"
] |
How do I check if a number is divisible by every number in a list | 38,301,588 | <p>I'm totally helpless about this, the only solutions I found are using generators (which I don't understand, because I've just started "trying to code").</p>
<p>Here is my code: </p>
<pre><code>x = 9
PrimeCount = 4
PrimeList = [2, 3, 5, 7]
while PrimeCount < 10002:
if all():
y == x
PrimeLi... | 1 | 2016-07-11T07:42:09Z | 38,302,266 | <p>This is also a brute force solution, similar that the one you are trying and easier to understand:</p>
<pre><code>primeList = [2]
check = 3
while len(primeList)<6:
flag = True
for num in primeList:
if check%num == 0:
flag = False
if flag:
primeList.append(check)
check... | 0 | 2016-07-11T08:22:23Z | [
"python",
"list",
"solution"
] |
How do I check if a number is divisible by every number in a list | 38,301,588 | <p>I'm totally helpless about this, the only solutions I found are using generators (which I don't understand, because I've just started "trying to code").</p>
<p>Here is my code: </p>
<pre><code>x = 9
PrimeCount = 4
PrimeList = [2, 3, 5, 7]
while PrimeCount < 10002:
if all():
y == x
PrimeLi... | 1 | 2016-07-11T07:42:09Z | 38,302,910 | <p>A generator could be considerd as a function/subroutine which returns a list, but only does so one element at a time. Thus allowing you to interact with each element indiviually without ever having to store the whole of the list in memory and loop through it.</p>
<p>A prime number generator, idealy, would return th... | 0 | 2016-07-11T08:59:35Z | [
"python",
"list",
"solution"
] |
How do I check if a number is divisible by every number in a list | 38,301,588 | <p>I'm totally helpless about this, the only solutions I found are using generators (which I don't understand, because I've just started "trying to code").</p>
<p>Here is my code: </p>
<pre><code>x = 9
PrimeCount = 4
PrimeList = [2, 3, 5, 7]
while PrimeCount < 10002:
if all():
y == x
PrimeLi... | 1 | 2016-07-11T07:42:09Z | 38,349,810 | <blockquote>
<p>How do I check if a number is divisible by every number in a list</p>
</blockquote>
<p>Do you really mean <strong>every</strong>, surely to find a prime number you need to know if the number is divisible by <strong>any</strong> number in the list.</p>
<p>There are going to be neater, or faster, or m... | 0 | 2016-07-13T11:01:26Z | [
"python",
"list",
"solution"
] |
Python. Calculate dimension totals for list of dictionaries | 38,301,595 | <h1>I have 2 dimensions:</h1>
<pre><code>dimensions = ('product', 'place')
</code></pre>
<h1>And 2 metrics:</h1>
<pre><code>metrics = ('METRIC_1', 'METRIC_2')
</code></pre>
<h1>Input is the following list of dicts with dimensions and metrics</h1>
<pre><code>input = [
{'product': 'eggs', 'place': 'fridge', 'MET... | 0 | 2016-07-11T07:42:48Z | 38,304,133 | <p>Here's a code that I came up with. It takes input, dimensions and dictionary of aggregate functions as a parameters. Then in iterates over every row in the input and aggregates metrics to every relevant row in output that is internally a dict. Finally the result dict is flattened to produce the list output:</p>
<pr... | 0 | 2016-07-11T10:02:33Z | [
"python"
] |
Python. Calculate dimension totals for list of dictionaries | 38,301,595 | <h1>I have 2 dimensions:</h1>
<pre><code>dimensions = ('product', 'place')
</code></pre>
<h1>And 2 metrics:</h1>
<pre><code>metrics = ('METRIC_1', 'METRIC_2')
</code></pre>
<h1>Input is the following list of dicts with dimensions and metrics</h1>
<pre><code>input = [
{'product': 'eggs', 'place': 'fridge', 'MET... | 0 | 2016-07-11T07:42:48Z | 38,323,121 | <p>@niemmi , thank you. yours failed on np.mean aggregation, so let me add solution that worked for me.</p>
<pre><code>def powerset(iterable):
xs = list(iterable)
return chain.from_iterable(combinations(xs, n) for n in range(len(xs)+1))
def calc_totals(input_list, dimensions, metric_func_dict):
# metric... | 0 | 2016-07-12T08:00:33Z | [
"python"
] |
Can't parse microseconds correctly with strptime() | 38,301,650 | <p>I have a string <code>19:04:01:94891</code>.</p>
<p>When I pass this to <code>datetime.datetime.strptime()</code> as:</p>
<pre><code>datetime.strptime('19:04:01:94891', "%H:%M:%S:%f")
</code></pre>
<p>I get the following result:</p>
<pre><code>datetime.datetime(1900, 1, 1, 19, 4, 1, 948910)
</code></pre>
<p>How... | 0 | 2016-07-11T07:46:00Z | 38,301,883 | <p>From the documentation on <a href="https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior" rel="nofollow"><code>strptime()</code></a>:</p>
<blockquote>
<p>When used with the <code>strptime()</code> method, the <code>%f</code> directive accepts from
one to six digits and zero pads on the ... | 0 | 2016-07-11T07:59:47Z | [
"python",
"python-2.7",
"datetime"
] |
Can't parse microseconds correctly with strptime() | 38,301,650 | <p>I have a string <code>19:04:01:94891</code>.</p>
<p>When I pass this to <code>datetime.datetime.strptime()</code> as:</p>
<pre><code>datetime.strptime('19:04:01:94891', "%H:%M:%S:%f")
</code></pre>
<p>I get the following result:</p>
<pre><code>datetime.datetime(1900, 1, 1, 19, 4, 1, 948910)
</code></pre>
<p>How... | 0 | 2016-07-11T07:46:00Z | 38,301,950 | <p>The problem is that your input isn't zero-padded, so the problem would be even worse if we were at, say, 11 microseconds. Let's fix the problem at it's source, and clean up the input first:</p>
<pre><code>def fixMicroseconds(timestamp):
parts = timestamp.split(':')
return ':'.join(
parts[:-1] + ['{:06... | 0 | 2016-07-11T08:04:34Z | [
"python",
"python-2.7",
"datetime"
] |
Is it possible to get output of pydot graph without intermediate file? | 38,301,651 | <p>I have a very simple graph that I want to plot as svg. For example:</p>
<pre><code># graph.dot
graph {
a -- b;
b -- c;
}
</code></pre>
<p>I am currently using pydot to read the file and then generate the svg file as follows:</p>
<pre><code>import pydot
graphs = pydot.graph_from_dot_file('g... | 2 | 2016-07-11T07:46:01Z | 38,302,369 | <p>After spending some more time looking at the available methods on <code>pydot</code> object and <code>graph</code> object, it could be figured out:</p>
<p>The following code works:</p>
<pre><code>import pydot
dot_string = """graph {
a -- b;
b -- c;
} "... | 1 | 2016-07-11T08:28:27Z | [
"python",
"svg",
"graphviz",
"pygraphviz",
"pydot"
] |
iPython history of valid commands | 38,301,675 | <p>I am learning python using IPython. When I did something nice I like to copy this into some kind of private CheatSheet-file. Therefore I use the iPython <code>%hist</code> command. I am wondering, if there is a way to only print those commands which had been syntactically correct and did not raise an error. Any idea... | 0 | 2016-07-11T07:47:14Z | 38,302,182 | <p>Have you considered trying ipython notebook ? (I've used it on a couple of training courses)</p>
<p>You access the interatctive python via a web browser creating 'boxes' of runnable code. So if you ran a block, it gave the answer you wanted and threw no errors, you could then create another block and move on (prese... | 1 | 2016-07-11T08:16:58Z | [
"python",
"ipython"
] |
Pandas dataframe compression | 38,301,806 | <p>How do I map one dataframe into another df with less number of rows summing values of rows whoose indices are in given interval?</p>
<p>For example</p>
<p>Given df:</p>
<pre><code> Survived
Age
20 1
22 1
23 3
24 2
30 2
33 1
40 8... | 3 | 2016-07-11T07:55:12Z | 38,302,080 | <p>You can create an new column from the column <code>Age</code> and then use groupby:</p>
<p>In order to create the new column, <code>Age</code> needs to be taken out of the index:</p>
<pre><code>df.reset_index(inplace = True)
def cat_age(age):
return 10*int(age/10.)
df['category_age'] = df.Age.apply(lambda x... | 0 | 2016-07-11T08:11:05Z | [
"python",
"pandas"
] |
Pandas dataframe compression | 38,301,806 | <p>How do I map one dataframe into another df with less number of rows summing values of rows whoose indices are in given interval?</p>
<p>For example</p>
<p>Given df:</p>
<pre><code> Survived
Age
20 1
22 1
23 3
24 2
30 2
33 1
40 8... | 3 | 2016-07-11T07:55:12Z | 38,302,110 | <p>First convert <code>int</code> index to <code>TimedeltaIndex</code> and then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.resample.html" rel="nofollow"><code>resample</code></a>:</p>
<pre><code>df.index = pd.TimedeltaIndex(df.index.to_series(), unit='s')
print (df)
Survived... | 1 | 2016-07-11T08:13:10Z | [
"python",
"pandas"
] |
Pandas dataframe compression | 38,301,806 | <p>How do I map one dataframe into another df with less number of rows summing values of rows whoose indices are in given interval?</p>
<p>For example</p>
<p>Given df:</p>
<pre><code> Survived
Age
20 1
22 1
23 3
24 2
30 2
33 1
40 8... | 3 | 2016-07-11T07:55:12Z | 38,302,120 | <p>You can use a function for the <code>groupby</code> argument:</p>
<pre><code>In [6]: df.groupby(lambda x: x//10 * 10).sum()
Out[6]:
Survived
20 7
30 3
40 15
</code></pre>
<p>Note, this also works with 5 but it doesn't work the way you want with empty groups, that is, it doesn't fill in ... | 1 | 2016-07-11T08:13:52Z | [
"python",
"pandas"
] |
Match whole word | 38,301,838 | <p>I want to search the input that user fill in the web. </p>
<p>I called input as <code>aranan</code>, but it dose not work properly. </p>
<p>I search <code>urla</code> but it return me <code>memurlarin</code> . the <code>urla</code> is inside the word <code>memurlarin</code>. but I want to get back just sentences t... | -2 | 2016-07-11T07:57:07Z | 38,307,147 | <p>The problem is in this line I guess:</p>
<pre><code>for i in range(len(sen1)):
if (aranan in sen1[i] and aranan in sen2[i]):
</code></pre>
<p>You can't iterate over the words of your sentences in this way because they may have different length and you won't be able to test all of their words. And this is not ... | 0 | 2016-07-11T12:37:53Z | [
"python",
"django"
] |
How do I print start and end of function with verbose, Python? | 38,301,979 | <p>I've written a nice chunk of code, and I'm looking to improve my verbose output. I had the idea of an <code>if verbose: print '**** function_name ****'</code> at the start and end of the function and even defined a function to make it easier to call (I'm using the very sexy verbose print written by kindall <a href="... | 0 | 2016-07-11T08:06:29Z | 38,302,319 | <p>Considering you want to print something only at the start and end of the function then the best way to do this is to use a decorator.</p>
<pre><code>def verbwrap(function):
def wrapper(*args, **kwargs):
verboseprint(' ****** %s ******' %(function.__name__))
result = function(*args, **kwargs)
... | 2 | 2016-07-11T08:25:11Z | [
"python",
"python-2.7",
"debugging",
"printing",
"verbose"
] |
How to disable java script in Chrome Driver Selenium Python | 38,301,993 | <p>How can I disable Java Script in Selenium's Chrome Driver using python</p>
| 1 | 2016-07-11T08:07:15Z | 38,302,233 | <p>Disabling <code>JavaScript</code> in <code>Chrome</code> is possible with old <code>ChromeDriver</code> prior to <code>ChromeDriver2</code>, which only supports <strong>Chrome 28 or under</strong>. try as below :-</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.chrome.options import Options
c... | 0 | 2016-07-11T08:20:05Z | [
"python",
"selenium",
"selenium-chromedriver"
] |
How to disable java script in Chrome Driver Selenium Python | 38,301,993 | <p>How can I disable Java Script in Selenium's Chrome Driver using python</p>
| 1 | 2016-07-11T08:07:15Z | 38,302,237 | <p>It's really difficult. You can try doing this way:</p>
<pre><code>DesiredCapabilities caps = DesiredCapabilities.chrome();
caps.setCapability("chrome.switches", Arrays.asList("--disable-javascript"));
</code></pre>
<p>But as it is written <a href="http://yizeng.me/2014/01/08/disable-javascript-using-selenium-webdr... | 0 | 2016-07-11T08:20:15Z | [
"python",
"selenium",
"selenium-chromedriver"
] |
How to disable java script in Chrome Driver Selenium Python | 38,301,993 | <p>How can I disable Java Script in Selenium's Chrome Driver using python</p>
| 1 | 2016-07-11T08:07:15Z | 38,506,511 | <p>It's Really easy ! Just try this code !</p>
<p>from selenium.webdriver.chrome.options import Options</p>
<pre><code>from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_experimental_option( "prefs",{'profile.managed_default_content_settings.javascript': 2})
chrome = w... | 2 | 2016-07-21T14:07:42Z | [
"python",
"selenium",
"selenium-chromedriver"
] |
Upgrade package from script using pip | 38,302,028 | <p>Using pip from a (python 3.5) script, how can i upgrade a package i previously installed via the command line (using <code>pip install</code>)?</p>
<p>Something like</p>
<pre><code>import pip
pip.install("mysuperawesomepackage", upgrade=True)
</code></pre>
| 0 | 2016-07-11T08:08:26Z | 38,302,132 | <pre><code>import pip
def install(package):
pip.main(['install', package])
# Example
if __name__ == '__main__':
install('mysuperawesomepackage')
</code></pre>
| 1 | 2016-07-11T08:14:22Z | [
"python",
"python-3.x",
"pip",
"python-3.5"
] |
Upgrade package from script using pip | 38,302,028 | <p>Using pip from a (python 3.5) script, how can i upgrade a package i previously installed via the command line (using <code>pip install</code>)?</p>
<p>Something like</p>
<pre><code>import pip
pip.install("mysuperawesomepackage", upgrade=True)
</code></pre>
| 0 | 2016-07-11T08:08:26Z | 38,302,134 | <p>You need to do this:</p>
<pre><code>pip.main(['install', '--upgrade', package]).
</code></pre>
<p>Ref - <a href="http://stackoverflow.com/questions/25862416/upgrading-python-module-within-code">upgrading python module within code</a></p>
| 1 | 2016-07-11T08:14:27Z | [
"python",
"python-3.x",
"pip",
"python-3.5"
] |
Django CSRF cookie not set correctly | 38,302,058 | <p>Update 7-18:</p>
<p>Here is my nginx config for the proxy server:</p>
<pre><code>server {
listen 80;
server_name blah.com; # the blah is intentional
access_log /home/cheng/logs/access.log;
error_log /home/cheng/logs/error.log;
location / {
proxy_pass http://127.0.0.1:8001;... | 16 | 2016-07-11T08:10:02Z | 38,436,440 | <p>Here is the issue: <strong>You cannot have a cookie which key contains either the character '[' or ']'</strong></p>
<p>I discovered the solution following @Todor's <a href="https://mail.python.org/pipermail/python-dev/2015-May/140135.html">link</a>, then I found out about this <a href="http://stackoverflow.com/a/33... | 14 | 2016-07-18T12:13:45Z | [
"python",
"django",
"cookies",
"csrf"
] |
write a pandas/python function which requires as inputs multiple columns in a pandas dataframe | 38,302,075 | <p>In a dataframe with two columns I can easily create a third without a function if it is a numerical operation such as multiply df["new"] =df["one"] * df["two"].</p>
<p>However what if I need to pass in more than two parameters to a function and those parameters are columns from a dataframe. </p>
<p>Passing one col... | 0 | 2016-07-11T08:10:51Z | 38,302,139 | <p>I think you need a <code>lambda</code> function in your apply:</p>
<pre><code>def WordLength(words):
return max(len(words[0]),len(words[1]),len(words[2]))
df['wordlength'] = df[['col1','col2','col3']].apply(lambda x: WordLength(x),axis=1)
</code></pre>
<p>Output:</p>
<pre><code> col1 col2 ... | 1 | 2016-07-11T08:14:37Z | [
"python",
"function",
"pandas",
"dataframe",
"parameter-passing"
] |
write a pandas/python function which requires as inputs multiple columns in a pandas dataframe | 38,302,075 | <p>In a dataframe with two columns I can easily create a third without a function if it is a numerical operation such as multiply df["new"] =df["one"] * df["two"].</p>
<p>However what if I need to pass in more than two parameters to a function and those parameters are columns from a dataframe. </p>
<p>Passing one col... | 0 | 2016-07-11T08:10:51Z | 38,302,451 | <p>Unless you <em>really</em> want a function to do this, you can use <code>DataFrame</code> operations, eg:</p>
<pre><code>df[['col1', 'col2', 'col3']].applymap(len).max(axis=1)
</code></pre>
<p>You can use <code>apply</code>'s <code>args</code> argument to pass in the columns to be processed and make the target fun... | 1 | 2016-07-11T08:34:03Z | [
"python",
"function",
"pandas",
"dataframe",
"parameter-passing"
] |
Should I use open alone in python | 38,302,136 | <p>As title, Should I use open alone as this situation instead of using f=open(file) and f.close, because I don't know how to close file when I just using open.<br>
More explain: I want to use just open instead of with-statement or f=open() and f.close() because it increase my mini app's size a few Megabytes but I don'... | -2 | 2016-07-11T08:14:36Z | 38,302,678 | <p>Use with-statement:</p>
<pre><code>def resource_path(relative_path):
try:
with open(relative_path) as file:
base_path = os.path.abspath(".")
except Exception:
base_path = sys._MEIPASS
return os.path.join(base_path, relative_path)
</code></pre>
| 2 | 2016-07-11T08:46:43Z | [
"python",
"python-3.x"
] |
cv2.videocapture doesn't works on Raspberry-pi | 38,302,161 | <p>How can i make the cv2.VideoCapture(0) recognize the USB camera of raspberry-pi.</p>
<pre><code>def OnRecord(self, evt):
capture = cv2.VideoCapture(0)
if (not capture.isOpened()):
print "Error"
# video recorder
fourcc = cv2.cv.CV_FOURCC(*'XVID') # cv2.VideoWriter_fourcc() does not exist
vid... | 3 | 2016-07-11T08:15:48Z | 38,303,215 | <p>Go to terminal and type <em>lsusb</em> and check whether the USB camera is recognized or not. If it is recognized then try to give different device ID such as 1 or 2 or 3 rather than 0.</p>
| 0 | 2016-07-11T09:15:04Z | [
"python",
"opencv",
"raspberry-pi2"
] |
cv2.videocapture doesn't works on Raspberry-pi | 38,302,161 | <p>How can i make the cv2.VideoCapture(0) recognize the USB camera of raspberry-pi.</p>
<pre><code>def OnRecord(self, evt):
capture = cv2.VideoCapture(0)
if (not capture.isOpened()):
print "Error"
# video recorder
fourcc = cv2.cv.CV_FOURCC(*'XVID') # cv2.VideoWriter_fourcc() does not exist
vid... | 3 | 2016-07-11T08:15:48Z | 38,303,552 | <p>looks Like you might have issue with codec, try using 'MJPG' codec instead of XVID.
For more details have a look <a href="http://www.pyimagesearch.com/2016/02/22/writing-to-video-with-opencv/" rel="nofollow">here</a></p>
| 0 | 2016-07-11T09:31:41Z | [
"python",
"opencv",
"raspberry-pi2"
] |
cv2.videocapture doesn't works on Raspberry-pi | 38,302,161 | <p>How can i make the cv2.VideoCapture(0) recognize the USB camera of raspberry-pi.</p>
<pre><code>def OnRecord(self, evt):
capture = cv2.VideoCapture(0)
if (not capture.isOpened()):
print "Error"
# video recorder
fourcc = cv2.cv.CV_FOURCC(*'XVID') # cv2.VideoWriter_fourcc() does not exist
vid... | 3 | 2016-07-11T08:15:48Z | 38,379,980 | <p>Make sure that the camera that you are using is UVC compatible, as openCV running on linux based systems (like a raspi) starts to do some silly things when it is working with non UVC cameras.</p>
| 0 | 2016-07-14T16:53:55Z | [
"python",
"opencv",
"raspberry-pi2"
] |
cv2.videocapture doesn't works on Raspberry-pi | 38,302,161 | <p>How can i make the cv2.VideoCapture(0) recognize the USB camera of raspberry-pi.</p>
<pre><code>def OnRecord(self, evt):
capture = cv2.VideoCapture(0)
if (not capture.isOpened()):
print "Error"
# video recorder
fourcc = cv2.cv.CV_FOURCC(*'XVID') # cv2.VideoWriter_fourcc() does not exist
vid... | 3 | 2016-07-11T08:15:48Z | 38,400,632 | <p>In my experience with CV2 replacing a webcam source on linux isn't always easy. How OpenCV works is it automatically draws from the systems default video source, which is known (usually) as video0. Unplug your usb webcam and go into a terminal and typing <code>ls /dev/video*</code></p>
<p>Remember the number it say... | 0 | 2016-07-15T16:06:28Z | [
"python",
"opencv",
"raspberry-pi2"
] |
cv2.videocapture doesn't works on Raspberry-pi | 38,302,161 | <p>How can i make the cv2.VideoCapture(0) recognize the USB camera of raspberry-pi.</p>
<pre><code>def OnRecord(self, evt):
capture = cv2.VideoCapture(0)
if (not capture.isOpened()):
print "Error"
# video recorder
fourcc = cv2.cv.CV_FOURCC(*'XVID') # cv2.VideoWriter_fourcc() does not exist
vid... | 3 | 2016-07-11T08:15:48Z | 40,134,101 | <p>load the correct video 4 linux drivers</p>
<pre><code>sudo modprobe bcm2835-v4l2
</code></pre>
| 0 | 2016-10-19T14:21:15Z | [
"python",
"opencv",
"raspberry-pi2"
] |
TypeError: Incorrect padding (b64decode Python) | 38,302,165 | <p>Trying to scrape one site (Russian language, cyrillic) and save all content in csv, but get error </p>
<blockquote>
<p>Traceback (most recent call last):
File "/Users/kr/PycharmProjects/education_py/credit_parser.py", line 30, in
base64.b64decode(listing_title[0].encode('utf-8')),
File "/System/Lib... | 0 | 2016-07-11T08:16:16Z | 38,302,598 | <p>Like this :</p>
<pre><code>try:
if divmod(len(field),4)[1] != 0:
field += "="*(4-divmod(len(field),4)[1])
#decode field here
except Exception,e: print e
</code></pre>
<p>Field = base64 encoding items.</p>
<p>Encrypted not <code>base64.encoding</code>, encode first before decoding and never decode... | 1 | 2016-07-11T08:42:19Z | [
"python",
"python-2.7",
"csv",
"encoding",
"base64"
] |
TypeError: Incorrect padding (b64decode Python) | 38,302,165 | <p>Trying to scrape one site (Russian language, cyrillic) and save all content in csv, but get error </p>
<blockquote>
<p>Traceback (most recent call last):
File "/Users/kr/PycharmProjects/education_py/credit_parser.py", line 30, in
base64.b64decode(listing_title[0].encode('utf-8')),
File "/System/Lib... | 0 | 2016-07-11T08:16:16Z | 38,315,262 | <p>You should use <code>b64encode</code> instead of <code>b64decode</code>.</p>
| 0 | 2016-07-11T20:03:32Z | [
"python",
"python-2.7",
"csv",
"encoding",
"base64"
] |
TastyPie Serializing during dehydrate | 38,302,206 | <p>So I have a <code>QuestionResource</code>:</p>
<pre><code>class QuestionResourse(ModelResource):
def dehydrate(self, bundle):
bundle.data['responses'] = Responses.objects.filter(question_id=bundle.data['id'])
return bundle
class Meta:
resource_name='question'
queryset = Questions.objects.all()
a... | 0 | 2016-07-11T08:18:30Z | 38,304,090 | <p>You should create a separate <code>ResponseResource</code> and link both in <strong>api.py</strong>.</p>
<p>The <code>full=True</code> parameter is what makes the API return a full representation of each Response</p>
<pre><code>from tastypie import resources, fields
class ResponseResource(resources.ModelResource)... | 2 | 2016-07-11T09:59:59Z | [
"python",
"django",
"api",
"serialization",
"tastypie"
] |
Validating input to follow a specific order | 38,302,228 | <p>I have to make sure that an email address that is inputted is valid. An email address must:</p>
<ul>
<li><p>Start with a string of alphanumeric characters</p></li>
<li><p>followed by the <code>@</code> symbol</p></li>
<li><p>another string of alphanumeric characters</p></li>
<li><p>followed by a <code>.</code></p><... | -2 | 2016-07-11T08:19:52Z | 38,302,521 | <p>Use <a href="https://docs.python.org/3/library/re.html" rel="nofollow">Regular Expression</a></p>
<p>An example:</p>
<pre><code>import re
if re.search(r'[\w.-]+@[\w.-]+.\w+', email):
do stuff
else
do other stuff
</code></pre>
| 2 | 2016-07-11T08:37:34Z | [
"python"
] |
Validating input to follow a specific order | 38,302,228 | <p>I have to make sure that an email address that is inputted is valid. An email address must:</p>
<ul>
<li><p>Start with a string of alphanumeric characters</p></li>
<li><p>followed by the <code>@</code> symbol</p></li>
<li><p>another string of alphanumeric characters</p></li>
<li><p>followed by a <code>.</code></p><... | -2 | 2016-07-11T08:19:52Z | 38,303,067 | <p>I would split the string at the <em>@</em> character into two new strings and check if the string to the left of <em>@</em> only contains alphanumeric characters. Then I would split the string on the right at the <em>.</em> character and check if both left and right string contain only alphanumeric characters.</p>
... | 0 | 2016-07-11T09:06:51Z | [
"python"
] |
Validating input to follow a specific order | 38,302,228 | <p>I have to make sure that an email address that is inputted is valid. An email address must:</p>
<ul>
<li><p>Start with a string of alphanumeric characters</p></li>
<li><p>followed by the <code>@</code> symbol</p></li>
<li><p>another string of alphanumeric characters</p></li>
<li><p>followed by a <code>.</code></p><... | -2 | 2016-07-11T08:19:52Z | 38,303,110 | <p>This is my take on this:</p>
<pre><code>def email_valid(email_str):
if email_str.count('@') != 1 or email_str.count('.') != 1:
return False
if len(min(email_str.split('@'))) == 0 or len(min(email_str.split('@')[1].split('.'))) == 0:
return False
parts = email_str.split('@')[1].split('.')... | 0 | 2016-07-11T09:09:06Z | [
"python"
] |
Validating input to follow a specific order | 38,302,228 | <p>I have to make sure that an email address that is inputted is valid. An email address must:</p>
<ul>
<li><p>Start with a string of alphanumeric characters</p></li>
<li><p>followed by the <code>@</code> symbol</p></li>
<li><p>another string of alphanumeric characters</p></li>
<li><p>followed by a <code>.</code></p><... | -2 | 2016-07-11T08:19:52Z | 38,318,090 | <p>Here's another non-regex way to do it:</p>
<pre><code>def validate_email(email):
user, sep, domain = email.partition('@')
parts = [user]
parts.extend(domain.split('.'))
return len(parts) == 3 and all(part.isalnum() for part in parts)
>>> for email in 'a@b.c', 'ab23@f45.d3', 'a_b@p_q.com', ... | 0 | 2016-07-12T00:12:53Z | [
"python"
] |
Creating sequence vector from text in Python | 38,302,280 | <p>I am now trying to prepare the input data for LSTM-based NN.
I have some big number of text documents and what i want is to make sequence vectors for each document so i am able to feed them as train data to LSTM RNN.</p>
<p>My poor approach:</p>
<pre><code>import re
import numpy as np
#raw data
train_docs = ['this... | 0 | 2016-07-11T08:23:16Z | 38,303,815 | <p>You could use NLTK to tokenise the training documents. NLTK provides a standard word tokeniser or allows you to define your own tokeniser (e.g. RegexpTokenizer). Take a look <a href="http://www.nltk.org/api/nltk.tokenize.html" rel="nofollow">here</a> for more details about the different tokeniser functions available... | 0 | 2016-07-11T09:45:37Z | [
"python",
"word2vec",
"lstm"
] |
Creating sequence vector from text in Python | 38,302,280 | <p>I am now trying to prepare the input data for LSTM-based NN.
I have some big number of text documents and what i want is to make sequence vectors for each document so i am able to feed them as train data to LSTM RNN.</p>
<p>My poor approach:</p>
<pre><code>import re
import numpy as np
#raw data
train_docs = ['this... | 0 | 2016-07-11T08:23:16Z | 38,306,607 | <p>Solved with Keras text preprocessing classes:
<a href="http://keras.io/preprocessing/text/" rel="nofollow">http://keras.io/preprocessing/text/</a></p>
<p>done like this:</p>
<pre><code>from keras.preprocessing.text import Tokenizer, text_to_word_sequence
train_docs = ['this is text number one', 'another text that... | 0 | 2016-07-11T12:10:17Z | [
"python",
"word2vec",
"lstm"
] |
telepot error helper router: 'module' object has no attribute 'router' | 38,302,353 | <p>I'm try to use telepot to build my first telegram bot with python.
I want to route conversation by command, so Iâve read the documentation in <a href="https://github.com/nickoala/telepot/blob/master/REFERENCE.md#telepothelperrouter" rel="nofollow">Telepot Helper Router</a>, but I don't know how can I use it.</p>
... | 0 | 2016-07-11T08:27:25Z | 38,304,052 | <p>Issue is that you are trying to call function, instead of Class.
If you check source of Telepot <a href="https://github.com/nickoala/telepot/blob/master/telepot/helper.py#L785" rel="nofollow">here</a> you will see that <code>Router</code> is a class</p>
<p>So instead of:</p>
<pre><code>r = telepot.helper.router
</... | 0 | 2016-07-11T09:58:09Z | [
"python",
"telegram-bot"
] |
Python : Numpy Matrix split | 38,302,523 | <p>I have a matrix of shape <code>4 x 129</code>. I am trying to do a horizontal split like the example shown below: </p>
<pre><code>In [18]: x = np.arange(4*129)
In [19]: x = x.reshape(4, 129)
In [20]: x.shape
Out[20]: (4, 129)
In [21]: y = np.hsplit(x, 13)
ValueError: array split does not result in an equal divi... | 4 | 2016-07-11T08:37:48Z | 38,302,878 | <p>You can pass the indices for split and in this case you can create them simply using <code>np.arange()</code>:</p>
<pre><code>>>> a = np.hsplit(x, np.arange(12, 129, 12))
>>>
>>> a[0].shape
(4, 12)
>>> a[-1].shape
(4, 9)
</code></pre>
| 5 | 2016-07-11T08:58:20Z | [
"python",
"numpy",
"matrix"
] |
Python : Numpy Matrix split | 38,302,523 | <p>I have a matrix of shape <code>4 x 129</code>. I am trying to do a horizontal split like the example shown below: </p>
<pre><code>In [18]: x = np.arange(4*129)
In [19]: x = x.reshape(4, 129)
In [20]: x.shape
Out[20]: (4, 129)
In [21]: y = np.hsplit(x, 13)
ValueError: array split does not result in an equal divi... | 4 | 2016-07-11T08:37:48Z | 38,302,982 | <p>I do not know how to do it using np.hsplit with an int as second parameter, but while looking around, I found a way to do it using an array, as a parameter. </p>
<p>The way to do it would be :</p>
<pre><code>temp_array = [(i+1)*10 for i in range((129-1)//10)]
y = np.hsplit(x,temp_array)
</code></pre>
<p>or in on... | 2 | 2016-07-11T09:02:37Z | [
"python",
"numpy",
"matrix"
] |
SQLite3 - One cell has different type than other cells in column | 38,302,563 | <p>I have a <code>SQLite3</code> db. I use <strong>SQLite Browser</strong> and Python to work with this db. I have a column <code>description</code> which is a text column on the tabe. I've changed the text in one row using <strong>Sqlite3 Browser</strong>. From then, I'm getting error in python script. </p>
<pre><cod... | 0 | 2016-07-11T08:40:18Z | 38,303,285 | <p>You can use <code>unicode()</code> to convert a byte string from some encoding to Unicode, but unless you specifiy the encoding, Python assumes it's ASCII.</p>
<p>SQLite does not use ASCII but UTF-8, so you have to tell Python about it:</p>
<pre><code>...join(unicode(y, 'UTF-8') for y in ...)
</code></pre>
| 1 | 2016-07-11T09:18:03Z | [
"python",
"sqlite",
"sqlite3"
] |
Python multithreading - play multiple sine waves simultaneously | 38,302,606 | <p>I would like to generate sine wave noises at a given frequency and duration. I would like this to play simultaneously while using a GUI.</p>
<p>I've created a class that makes use of threading but it doesn't seem to work. I cannot execute code at the same time as invoking the .run() line. For example when running t... | 0 | 2016-07-11T08:42:41Z | 38,302,986 | <p>You seem to have got it fully right. Following test code is working perfectly fine with your code.</p>
<pre><code>objs = []
number_of_threads = 10
print 'Creating thread objects'
for i in range(number_of_threads):
objs.append(WavePlayerLoop(freq=440 * i, length=10., volume=0.1 * i))
print 'Starting thread obj... | 1 | 2016-07-11T09:02:41Z | [
"python",
"multithreading"
] |
Run WebSocket server in Thread | 38,302,613 | <p>this is probably more a question about threading than about my websocket.
I'm using "SimpleWebSocket" from github ( <a href="https://github.com/dpallot/simple-websocket-server" rel="nofollow">https://github.com/dpallot/simple-websocket-server</a> )
The example works fine:</p>
<pre><code>from SimpleWebSocketServer i... | 1 | 2016-07-11T08:43:03Z | 38,302,684 | <p>The main problem seems to be <em>where</em> you're starting the server. The <code>Thread.__init__()</code> method runs inside the main thread (of the <em>caller</em>), not the actual <code>WebSocketThread()</code>. This needs to be done in the <code>Thread.run()</code> method:</p>
<pre><code>class WebSocketThread(t... | 0 | 2016-07-11T08:47:14Z | [
"python",
"multithreading",
"websocket"
] |
Bluetooth - listening to a pairing even in a Linux device in Python | 38,302,629 | <p>I'm pretty new to Bluetooth so this might be trivial, but I'll still ask:</p>
<p>I would like to connect 2 devices via Bluetooth - a mobile device with a Linux device (like Raspberry Pi, but another one...).</p>
<p>Side 1 - the mobile: It has an app that should pair with the Linux device, and send some data to it ... | 1 | 2016-07-11T08:43:50Z | 38,302,762 | <p>Good morning, there is a library written in Python that handle Bluetooth connection for you already <code>PyBluez</code>
to install use <code>sudo pip install pybluez</code>
here is an example on how to use sockets to communicate with bluetooth devices</p>
<pre><code>import bluetooth
bd_addr = "01:23:45:67:89:AB"
p... | 2 | 2016-07-11T08:52:11Z | [
"python",
"linux",
"bluetooth",
"rfcomm"
] |
Monitor for category/folder change in Outlook with Python | 38,302,631 | <p>I am looking to build a Python tool that monitors category and folder changes in Outlook.</p>
<p>So far I managed to hook into the OnNewMailEx event and monitor for all incoming emails using the code below:</p>
<pre><code>import win32com.client
import pythoncom
import re
def getPath(folder, path=[]):
if folde... | 0 | 2016-07-11T08:44:13Z | 38,318,899 | <p>The OlkCategory interface you are referencing is tied to the Categories control that is used in Outlook Form Regions; it's useless by itself. To monitor property changes (including Categories) of an item you need to hook into the MailItem.PropertyChange event: <a href="https://msdn.microsoft.com/en-us/library/ff866... | 0 | 2016-07-12T02:04:45Z | [
"python",
"outlook",
"activex",
"win32com",
"dispatch"
] |
Using binary indexers on a multi-index | 38,302,718 | <p>I have a DataFrame of the form:</p>
<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><table border="1" class="dataframe">\n
<thead>\n
<tr style="tex... | 0 | 2016-07-11T08:49:14Z | 38,302,921 | <p>I think you get values if <code>p < 1</code> if use <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>boolean indexing</code></a>:</p>
<pre><code>print (p)
Panama
Contract Date
201501 2014-04-29 -1416.0
2014-04-... | 0 | 2016-07-11T09:00:06Z | [
"python",
"pandas"
] |
Setting position for Multiple Label frame in python | 38,302,751 | <p>I am using Grid manager to set each of my label frame in rows and columns, after my code run, the middle 2 frame does not appear as what i set in my coding.How can i ensure the middle 2 frame is appear in my program, Regards.</p>
<p><a href="http://i.stack.imgur.com/WtOZ3.jpg" rel="nofollow">Screenshot</a></p>
<pr... | 0 | 2016-07-11T08:51:41Z | 38,303,231 | <p>In the first two lines of your init, you set your maxheight to 520.</p>
<p>Your first row elements (A, D) are at a height of 520.</p>
<p>The second row element (B) can not be displayed as it exceeds the frame limits.</p>
<p>The third row element (D) is not affected by self.framepackC.grid_propagate(0).</p>
<p><b... | 1 | 2016-07-11T09:15:53Z | [
"python",
"user-interface",
"tkinter",
"grid"
] |
Python - reading 10 bit integers from a binary file | 38,302,765 | <p>I have a binary file containing a stream of 10-bit integers. I want to read it and store the values in a list.</p>
<p>It is working with the following code, which reads <code>my_file</code> and fills <code>pixels</code> with integer values:</p>
<pre><code>file = open("my_file", "rb")
pixels = []
new10bitsByte = "... | 3 | 2016-07-11T08:52:18Z | 38,306,171 | <p>As there is no direct way to read a file x-bit by x-bit in Python, we have to read it byte by byte. Following MisterMiyagi and PM 2Ring's suggestions I modified my code to read the file by 5 byte chunks (i.e. 40 bits) and then split the resulting string into 4 10-bit numbers, instead of looping over the bits individ... | 1 | 2016-07-11T11:47:20Z | [
"python",
"file-io",
"binary"
] |
Python - reading 10 bit integers from a binary file | 38,302,765 | <p>I have a binary file containing a stream of 10-bit integers. I want to read it and store the values in a list.</p>
<p>It is working with the following code, which reads <code>my_file</code> and fills <code>pixels</code> with integer values:</p>
<pre><code>file = open("my_file", "rb")
pixels = []
new10bitsByte = "... | 3 | 2016-07-11T08:52:18Z | 38,306,406 | <p>Here's a generator that does the bit operations without using text string conversions. Hopefully, it's a little more efficient. :) </p>
<p>To test it, I write all the numbers in range(1024) to a <a href="https://docs.python.org/3/library/io.html#io.BytesIO" rel="nofollow">BytesIO</a> stream, which behaves like a bi... | 1 | 2016-07-11T11:59:44Z | [
"python",
"file-io",
"binary"
] |
heroku: issue importing python module | 38,303,101 | <p>This is my project structure:</p>
<pre><code>project_name
|___src
|___model.py
</code></pre>
<p>On my local dev environment, I have added <code>project_name</code>'s parent directory to PYTHONPATH, so I can do <code>from project_name.src.model import func_name</code> in a file inside the project.</p>
<p>But w... | 0 | 2016-07-11T09:08:49Z | 38,303,311 | <p>Do that path manipulation inside wsgi.py instead.</p>
| -1 | 2016-07-11T09:19:38Z | [
"python",
"heroku",
"python-import"
] |
Repeating python code multiple times - is there a way of condensing it? | 38,303,138 | <p>I've got multiple blocks of code which I need to repeat multiple times (in sequence). Here's an example of two blocks (there are many more). </p>
<pre><code>#cold winter
wincoldseq = [] #blank list
ran_yr = np.random.choice(coldwinter,1) #choose a random year from the extreme winter variable
wincoldseq += [(ran_yr... | -1 | 2016-07-11T09:10:28Z | 38,303,267 | <p>You could just extract this out into a function, to avoid repeating code. For example:</p>
<pre><code>def do_something_with(projection, data, input_list)
items = []
ran_yr = np.random.choice(input_list, 1)
items += [(ran_yr[0], 1)]
for item in output:
projection.append(data.query("Year == ... | 3 | 2016-07-11T09:17:15Z | [
"python",
"pandas"
] |
Repeating python code multiple times - is there a way of condensing it? | 38,303,138 | <p>I've got multiple blocks of code which I need to repeat multiple times (in sequence). Here's an example of two blocks (there are many more). </p>
<pre><code>#cold winter
wincoldseq = [] #blank list
ran_yr = np.random.choice(coldwinter,1) #choose a random year from the extreme winter variable
wincoldseq += [(ran_yr... | -1 | 2016-07-11T09:10:28Z | 38,304,245 | <p>I suggest you just make it a function. For instance:</p>
<pre><code>def spring():
sprwetseq = [] #blank list
ran_yr = np.random.choice(wetspring,1) #choose a random year from the extreme winter variable
sprwetseq += [(ran_yr[0], 2)] #take the random year and the value '2' for spring to sample from
... | 2 | 2016-07-11T10:07:42Z | [
"python",
"pandas"
] |
datetime.strptime unexpected behavior - locale issue | 38,303,217 | <p>Wondering if anyone has a workaround for a strange error I am getting with <a href="https://docs.python.org/2/library/datetime.html#datetime.datetime.strptime" rel="nofollow"><code>datetime.datetime.strptime</code></a>.</p>
<p><strong>NOTE:</strong> not a duplicate of the timezone issue.</p>
<p>I am getting this e... | 0 | 2016-07-11T09:15:10Z | 38,306,732 | <p>Thanks to <a href="http://stackoverflow.com/users/476/deceze">deceze's</a> <a href="http://stackoverflow.com/questions/38303217/datetime-strptime-unexpected-behavior?noredirect=1#comment64022991_38303217">comment</a> I was able to figure out a solution to this problem.</p>
<p>Indeed, the issue was with the locale o... | 1 | 2016-07-11T12:17:58Z | [
"python",
"datetime",
"strptime"
] |
Printing only the final odeint output | 38,303,255 | <p>I am sorry this may appear as a pretty dumb question, but I need to ask whether it is possible to print only the final output value while solving coupled differential equations in odeint? Actually I am trying to solve two coupled differential equations for time intervals generated randomly and get only the final out... | 0 | 2016-07-11T09:16:48Z | 38,318,557 | <p>The last element of the array of y-values is <code>y[-1]</code>. For example:</p>
<pre><code>import numpy as np
import scipy.integrate as si
def F(y, t):
return [y[1], y[0]]
t = np.arange(0, 1, 0.001)
y = si.odeint(F, [1, 0], t)
print(y[-1])
</code></pre>
<p>returns <code>[ 1.54190626 1.17365875]</code>. The ... | 0 | 2016-07-12T01:17:57Z | [
"python",
"scipy",
"odeint"
] |
Python code to create list from a file | 38,303,283 | <p>I have a dictionary file.txt, with 3 - 5 words in each line.</p>
<p>Like: </p>
<pre><code>apple ball back hall
hello bike like
</code></pre>
<p>I need a python code to put all these words into a list before any other coding occurs.</p>
<p>My idea is to read the file line-by-line, and use <code>split()</code>, an... | -3 | 2016-07-11T09:17:59Z | 38,303,448 | <p>You can do something like:</p>
<pre><code>file_list = []
with open('file.txt', 'r') as file:
for line in file.readlines().rstrip('\n'):
for word in line.split(' '):
file_list.append(word)
</code></pre>
<p>If <code>file.txt</code> has the following contents:</p>
<pre><code>apple ball back h... | 1 | 2016-07-11T09:26:51Z | [
"python",
"list",
"file"
] |
Create a "random" number between range without any module except time | 38,303,316 | <p>I would like to create myself a "random" number generator of integers between 2 edges. Moreover, I would like to create the same thing but with float numbers between two edges (like the random.random but of the range I want). </p>
<p>Time is required for me for timestamps.</p>
<p>I am currently learning the way ra... | 0 | 2016-07-11T09:19:46Z | 38,303,536 | <p>Given that you're always taking your number modulo <code>m</code>, <code>m</code> is the maximum value of the result. Also, finding a random number between <code>min</code> and <code>max</code> is the same as finding a random number between 0 and <code>max - min</code>, and adding <code>min</code> to that.</p>
<pre... | 1 | 2016-07-11T09:31:06Z | [
"python",
"random",
"time",
"range",
"generator"
] |
Heatmap from large CSV file | 38,303,661 | <p>I'm trying to plot a heatmap from a large CSV. Specifically I have a matrix like this:</p>
<pre><code>O0 X1 X2 X3 . . . Xn
Y1 Z1 Z2 Z3 . . . Zn
Y2 Z1 Z2 Z3 . . . Zn
Y3 Z1 Z2 Z3 . . . Zn
. . . . . . . .
. . . . . . . .
. . . . . . . .
Yn Z1 Z2 Z3 . . . Zn
</code></pre>
<p>With more than 4K X values, and... | 1 | 2016-07-11T09:37:13Z | 38,305,333 | <p>This is what I got so far:</p>
<pre><code>import csv
from PIL import Image
with open('TESTCSV100x100.csv') as f:
reader = csv.reader(f, delimiter=';')
i, j = 0, 0
pixels = dict()
for i, row in enumerate(reader):
for j, val in enumerate(row):
r, g, b = (int(int(val) / (1000 / 25... | 0 | 2016-07-11T11:04:43Z | [
"python",
"csv",
"matplotlib",
"plot",
"heatmap"
] |
Heatmap from large CSV file | 38,303,661 | <p>I'm trying to plot a heatmap from a large CSV. Specifically I have a matrix like this:</p>
<pre><code>O0 X1 X2 X3 . . . Xn
Y1 Z1 Z2 Z3 . . . Zn
Y2 Z1 Z2 Z3 . . . Zn
Y3 Z1 Z2 Z3 . . . Zn
. . . . . . . .
. . . . . . . .
. . . . . . . .
Yn Z1 Z2 Z3 . . . Zn
</code></pre>
<p>With more than 4K X values, and... | 1 | 2016-07-11T09:37:13Z | 38,370,095 | <p>I tried your problem using <a href="http://www.vips.ecs.soton.ac.uk/index.php?title=VIPS" rel="nofollow">vips</a>. Here's my program:</p>
<pre><code>#!/usr/bin/python
import sys
import gi
gi.require_version('Vips', '8.0')
from gi.repository import Vips
im = Vips.Image.new_from_file(sys.argv[1])
im = (255 * im / ... | 1 | 2016-07-14T09:10:58Z | [
"python",
"csv",
"matplotlib",
"plot",
"heatmap"
] |
Python: Different accuracy in and out of a function | 38,303,797 | <p>I know there are many questions and articles about floating point precision in Python and in general. But I didn't find the answer to this question.</p>
<p>I am calculating the same statement once by calling a function and second time without it. The value calculated by the function deviates by 0.003 which is not l... | 0 | 2016-07-11T09:44:27Z | 38,303,873 | <blockquote>
<p>I am calculating the same statement</p>
</blockquote>
<p>No, you're not. This</p>
<pre><code>0.5 * pow(sigma, 2) - log(ltv) / sigma
</code></pre>
<p>is <strong>not</strong> equivalent to this</p>
<pre><code>(0.5 * pow(sigma, 2) - log(0.7)) / sigma
</code></pre>
<p>The <a href="https://docs.python... | 5 | 2016-07-11T09:48:21Z | [
"python"
] |
Python Mechanize: Gateway Time-out when opening url, but url opens fine in internet browser | 38,303,812 | <p>I am scraping hotel room data from expedia.co.uk using Python (2.7) mechanize (on a Mac), looping through a list of about 1000 url's (200 hotels and 5 different periods).</p>
<p>When I ran the code, it worked fine for the first 200 and then gave me the following error: </p>
<blockquote>
<p>httperror_seek_wrapper... | 0 | 2016-07-11T09:45:25Z | 38,304,903 | <p>I can get rid of the timeout error using:</p>
<pre><code>br.addheaders.append(
('User-Agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/601.3.9 (KHTML, like Gecko) Version/9.0.2 Safari/601.3.9')
)
</code></pre>
<p>If you print out the mechanize headers for a simple request to a random websit... | 0 | 2016-07-11T10:41:25Z | [
"python",
"mechanize"
] |
Converting pandas df containing rownames, columnnames and frequency to Term Document Matrix | 38,303,833 | <p>I have a pandas df in the following format:
Input :</p>
<pre><code> Freq Document TermId
3 A 112
5 A 055
1 C 003
4 D 001
2 B 003
1 D 089
</code></pre>
<p>I want to convert this dataframe to a term document matrix (preferably another pandas df) . W... | 2 | 2016-07-11T09:46:39Z | 38,303,912 | <p>Notice that the desired DataFrame has an index whose labels are from <code>df['TermId']</code> and whose column labels are from <code>df['Document']</code>. Whenever the index and column labels come from columns of <code>df</code>, think about using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pand... | 3 | 2016-07-11T09:50:32Z | [
"python",
"numpy",
"pandas",
"scikit-learn",
"nltk"
] |
Concatenate strings from two different RDD in Python Spark | 38,303,903 | <p>Let's say I have 2 rdds :
the first rdd is composed of strings which are html requests :</p>
<p><strong>rdd1 :</strong></p>
<pre><code>serverIP:80 clientIP1 - - [10/Jun/2016:10:47:37 +0200] "GET /path/to/page1 [...]"
serverIP:80 clientIP2 - - [11/Jun/2016:11:25:12 +0200] "GET /path/to/page2 [...]"
...
</code></pre... | 0 | 2016-07-11T09:50:12Z | 38,304,096 | <p>If you can rely on the sequence of the two rdd's to match you can use zip:</p>
<pre><code>val rdd1 = sc.parallelize(List("a", "b", "c"))
val rdd2 = sc.parallelize(List(1.1, 1.2, 1.3))
val rdd3 = rdd1.zip(rdd2).map({case (s, d) => s + " " + d})
rdd3.collect() foreach println
// a 1.1
// b 1.2
// c 1.3
</code><... | 1 | 2016-07-11T10:00:27Z | [
"python",
"string",
"apache-spark",
"concatenation",
"rdd"
] |
Why do I need to declare encoding before hashing in Python, and how can I do this? | 38,304,088 | <p>I am trying to create an <a href="http://kittykatcoder.github.io/edison-ai/" rel="nofollow" title="AI-like chatbot">AI-like chatbot</a>, and one of its features is a login. I have used the login code before and it works fine, but I am now encountering difficulties with the code dealing with the hashing of the passw... | 0 | 2016-07-11T09:59:53Z | 38,304,123 | <p>Hashing works on <em>bytes</em>. <code>str</code> objects contain Unicode text, not bytes, so you must encode first. Pick an encoding that a) can handle all codepoints you are likely to encounter, and perhaps b) other systems that produce the same hashes also use.</p>
<p>If you are the only user of the hashes, then... | 0 | 2016-07-11T10:02:03Z | [
"python",
"osx",
"hash",
"character-encoding",
"password-storage"
] |
Trying to call the AlchemyLanguage API | 38,304,159 | <p>I have written code for calling the AlchemyLanguage API of Bluemix in Python. I need the keywords and entities, but it is only showing the first keyword and first entity for the text file. Where am I going wrong?</p>
<pre><code>import requests
import urllib
import urllib2
def call_alchemy_api(text, API_KEY... | 1 | 2016-07-11T10:03:44Z | 38,308,562 | <p>Change the <code>maxRetrieve</code> keyword's value.</p>
<p><strong>Example:</strong></p>
<pre><code>payload = {'outputMode':'json','extract':'entities,keywords','sentiment':'1','maxRetrieve':'3', 'url':'https://www.ibm.com/us-en/'}
</code></pre>
<p><strong>API Link:</strong></p>
<p><a href="http://www.ibm.com/w... | 1 | 2016-07-11T13:44:10Z | [
"python",
"api",
"ibm-bluemix",
"alchemyapi"
] |
Iteratively add columns of various length to DataFrame | 38,304,318 | <p>I have few categorical columns (description) in my DataFrame <code>df_churn</code> which i'd like to convert to numerical values. And of course I'd like to create a lookup table because i will need to convert them back eventually.</p>
<p>The problem is that every column has a different number of categories so appen... | 0 | 2016-07-11T10:11:06Z | 38,306,672 | <p>There is a temporary solution, but I am sure it can be done in a better way.</p>
<pre><code>df_CLI_REGION = pd.DataFrame()
df_CLI_PROVINCE = pd.DataFrame()
df_CLI_ORIGIN = pd.DataFrame()
df_cli_origin2 = pd.DataFrame()
df_cli_origin3 = pd.DataFrame()
df_ONE_PRD_TYPE_1 = pd.DataFrame()
cat_clmn = ['CLI_REGION','CL... | 0 | 2016-07-11T12:14:09Z | [
"python",
"dataframe"
] |
How can I retrieve a list from context in my django template | 38,304,323 | <p>I have a detail view with one model Room, in get_context_data method I add to my context another queryset of objects from second model:Worker</p>
<pre><code>class RoomView(DetailView):
template_name = 'detail.html'
model = Room
context_object_name = "room"
def get_object(self):
object = sup... | 0 | 2016-07-11T10:11:28Z | 38,304,430 | <p>You put this queryset in context with name 'workers' so retrieve it from this name: </p>
<pre><code>{% for worker in workers %}
<tr>
<td>{{worker.id}}</td>
<td>{{worker.first_name}}</td>
<td>{{worker.last_name}}</td>
<td>{{worker.email}}</td>
&l... | 0 | 2016-07-11T10:16:25Z | [
"python",
"django",
"django-templates",
"django-context"
] |
How can I use NLTK to repharse a sentence or a paragraph | 38,304,330 | <p>I am trying to use NLTK to rephrase a sentence or a paragraph which is grammatically correct. I am aware of article spinners but they generally just replace words with their synonyms. So, is there a way to easily use NLTK to generate sentences with a different structure than the original but essentially give the sam... | 0 | 2016-07-11T10:11:43Z | 38,438,116 | <p>I don't think there is anything "easy" beyond using synonyms.
The successful solutions for paraphrasing (like the ones winning SemEval Task 1 on text similarity - <a href="http://alt.qcri.org/semeval2016/task1/" rel="nofollow">http://alt.qcri.org/semeval2016/task1/</a>) are based on deep learning and Word2Vec word/s... | 0 | 2016-07-18T13:33:54Z | [
"python",
"nlp",
"nltk"
] |
Parse JSON object to Django template | 38,304,355 | <p>I am trying to parse a JSON object to Django template so that I can parse this json object to javascript.</p>
<p>Here how my view creates and parse the json object to the template:</p>
<pre><code> countries = Country.objects.filter(Enabled=True)
citiesByCountry = {}
for country in countries:
ci... | 2 | 2016-07-11T10:13:04Z | 38,304,875 | <p>I think you have two options:</p>
<ol>
<li><p>Parse the JSON in the <code><option></code> tags with javascript.</p>
<pre><code><script>
var json = JSON.parse({{citiesByCountry}});
//Loop through json and append to <option>
</script>
</code></pre></li>
<li><p>Add an extra <code>conte... | 1 | 2016-07-11T10:39:37Z | [
"python",
"json",
"django"
] |
Parse JSON object to Django template | 38,304,355 | <p>I am trying to parse a JSON object to Django template so that I can parse this json object to javascript.</p>
<p>Here how my view creates and parse the json object to the template:</p>
<pre><code> countries = Country.objects.filter(Enabled=True)
citiesByCountry = {}
for country in countries:
ci... | 2 | 2016-07-11T10:13:04Z | 38,304,886 | <p>To answer you question in the title:</p>
<p>In <code><head></code> (or somewhere), build your array of counties:</p>
<pre><code><script>
var country_objs = [];
{% for country in citiesByCountry%}
country_objs.push({{country|escapejs}});
{% endfor %}
<\script>
</code></pre>
<p... | 2 | 2016-07-11T10:40:10Z | [
"python",
"json",
"django"
] |
Parse JSON object to Django template | 38,304,355 | <p>I am trying to parse a JSON object to Django template so that I can parse this json object to javascript.</p>
<p>Here how my view creates and parse the json object to the template:</p>
<pre><code> countries = Country.objects.filter(Enabled=True)
citiesByCountry = {}
for country in countries:
ci... | 2 | 2016-07-11T10:13:04Z | 38,305,648 | <p>When you do <code>citiesByCountry = json.dumps({'a': "b", 'c': None})</code>, <code>citiesByCountry</code> is a string. This is why you get character after character when you iterate over it.</p>
<p>This string representing a JSON object, you can "affect" as-is to a JavaScript variable:</p>
<pre><code>var citiesBy... | 1 | 2016-07-11T11:19:46Z | [
"python",
"json",
"django"
] |
How to authenticate a Python script on Google AppEngine to use Google Firebase? | 38,304,372 | <p>Google has provided nice examples for Node.js, Android and iOS authentication of clients to connect to Firebase to use Firebase Realtime Databases - but how does one connect via Python from a Google AppEngine app to a Firebase Realtime Database and authenticate properly?</p>
| 2 | 2016-07-11T10:13:52Z | 38,304,570 | <p>Here are the steps we took to get this working. </p>
<p>(1) First you need a Firebase Secret.
After you have a project in Firebase, then click Settings. Then click Database and choose to create a secret. <a href="http://i.stack.imgur.com/WX70K.png" rel="nofollow"><img src="http://i.stack.imgur.com/WX70K.png" alt=... | 3 | 2016-07-11T10:23:10Z | [
"python",
"google-app-engine",
"firebase",
"firebase-authentication"
] |
Stop celery workers to consume from all queues | 38,304,548 | <p>Cheers,</p>
<p>I have a celery setup running in a production environment (on Linux) where I need to consume two different task types from two dedicated queues (one for each). The problem that arises is, that all workers are always bound to <strong>both queues</strong>, even when I specify them to only consume from ... | 1 | 2016-07-11T10:22:30Z | 38,315,610 | <p>You can create 2 separate workers for each queue and each one's define what queue it should get tasks from using the <code>-Q</code> command line argument. </p>
<p>If you want to keep the number processes the same, by default a process is opened for each core for each worker you can use the <code>--concurrency</cod... | 0 | 2016-07-11T20:24:15Z | [
"python",
"multithreading",
"celery"
] |
list to custom dictionary one liner | 38,304,572 | <p>I have a list:</p>
<pre><code>a = [0,1,2,5]
</code></pre>
<p>I want to get output something similar to:</p>
<pre><code>output = [{'i':0,'v':0},{'i':1,'v':0},{'i':2,'v':0},{'i':5,'v':0}]
</code></pre>
<p>with one line of code/expression where:</p>
<pre><code>output[indx]['i'] = a[indx]
</code></pre>
<p>and:</p>... | -5 | 2016-07-11T10:23:20Z | 38,304,605 | <p>Use a <a href="https://docs.python.org/2/tutorial/datastructures.html#list-comprehension" rel="nofollow">list comprehension</a> to produce your output list:</p>
<pre><code>[{'i': i, 'v': 0} for i in a]
</code></pre>
<p>This produces a list with the same number of elements as <code>a</code> has, each a dictionary w... | 2 | 2016-07-11T10:24:56Z | [
"python",
"dictionary"
] |
drop rows with errors for pandas data coercion | 38,304,691 | <p>I have a dataframe, for which I need to convert columns to floats and ints, that has bad rows, ie., values that are in a column that should be a float or an integer are instead string values. </p>
<p>If I use <code>df.bad.astype(float)</code>, I get an error, this is expected. </p>
<p>If I use <code>df.bad.astype(... | 0 | 2016-07-11T10:29:19Z | 38,304,784 | <p>Since the bad values are replaced with <code>np.NaN</code> would it not be simply just <code>df.dropna()</code> to get rid of the bad rows now?</p>
<p>EDIT:
Since you need to not drop the initial NaNs, maybe you could use <code>df.fillna()</code> prior to using <code>pd.to_numeric</code></p>
| 0 | 2016-07-11T10:34:12Z | [
"python",
"pandas",
"coercion"
] |
Changing the default ValueError of file.index | 38,304,726 | <p>I was using <code>file.index</code> to search for a string in a file.</p>
<pre><code>def IfStringExistsInFile(self,path,lineTextCheck):
file = open(path).read()
if file.index(lineTextCheck):
print (lineTextCheck + " was found in: " + path)
else:
raise ValueError (lineTextCheck + " was NO... | 1 | 2016-07-11T10:31:18Z | 38,304,778 | <p>As far as i know you cant change the built in errors. When you <code>raise</code> an error you raise it wherever you want, but in cause you done <code>except</code> the built-in error you will still get that.</p>
<p>So your second solution is the best i think, to <code>except</code> the built-in error, and treat it... | 1 | 2016-07-11T10:33:58Z | [
"python",
"python-2.7",
"error-handling"
] |
Changing the default ValueError of file.index | 38,304,726 | <p>I was using <code>file.index</code> to search for a string in a file.</p>
<pre><code>def IfStringExistsInFile(self,path,lineTextCheck):
file = open(path).read()
if file.index(lineTextCheck):
print (lineTextCheck + " was found in: " + path)
else:
raise ValueError (lineTextCheck + " was NO... | 1 | 2016-07-11T10:31:18Z | 38,304,879 | <blockquote>
<p>Any better way would be greatly appreciated</p>
</blockquote>
<p>You solved it exactly how this should be solved.</p>
<p>Note that you can create your own <code>Exception</code> by creating a class that inherits from <code>BaseException</code>, but this is rarely needed.</p>
| 2 | 2016-07-11T10:39:41Z | [
"python",
"python-2.7",
"error-handling"
] |
Changing the default ValueError of file.index | 38,304,726 | <p>I was using <code>file.index</code> to search for a string in a file.</p>
<pre><code>def IfStringExistsInFile(self,path,lineTextCheck):
file = open(path).read()
if file.index(lineTextCheck):
print (lineTextCheck + " was found in: " + path)
else:
raise ValueError (lineTextCheck + " was NO... | 1 | 2016-07-11T10:31:18Z | 38,304,889 | <p><a href="https://docs.python.org/3/glossary.html#term-eafp" rel="nofollow"><em>Easier to Ask for Forgiveness than Permission</em></a>. </p>
<p>Using a <code>try/except</code> for this is standard practice. You can also drop that <code>if</code> so the line gets printed if the index is found without raising errors:<... | 1 | 2016-07-11T10:40:33Z | [
"python",
"python-2.7",
"error-handling"
] |
Can a matplotlib figure object be pickled then retrieved? | 38,304,731 | <p>I am trying to pickle a matplotlib Figure object to be able to regenerate the graph with x and y data and labels and title at a later time. Is this possible?</p>
<p>When trying to use open and dump to pickle I get this traceback: </p>
<pre><code>#3rd Party Imports and built-in
import random
import matplotlib.pypl... | 2 | 2016-07-11T10:31:30Z | 38,305,054 | <p>Yes. Try</p>
<pre><code>import pickle
import matplotlib.pyplot as plt
file = open('myfile', 'wb')
fig = plt.gcf()
pickle.dump(fig, file)
file.close()
</code></pre>
<p>Then to read</p>
<pre><code>file = open('myfile', 'rb')
pickle.load(file)
plt.show()
file.close()
</code></pre>
| 3 | 2016-07-11T10:49:38Z | [
"python",
"matplotlib",
"pickle"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.