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 |
|---|---|---|---|---|---|---|---|---|---|
Hidden references to function arguments causing big memory usage? | 39,644,060 | <p><strong>Edit:</strong> Never mind, I was just being completely stupid.</p>
<p>I came across code with recursion on smaller and smaller substrings, here's its essence plus my testing stuff:</p>
<pre><code>def f(s):
if len(s) == 2**20:
input('check your memory usage again')
else:
f(s[1:])
inp... | 0 | 2016-09-22T16:14:50Z | 39,644,615 | <p>Your function is recursive, so when you call <code>f()</code>, your current frame is put onto a stack, and a new one is created. So basically each function call keeps a reference to the new string it creates to pass down to the next call.</p>
<p>To illustrate the stack</p>
<pre><code>import traceback
def recursiv... | 2 | 2016-09-22T16:44:36Z | [
"python",
"function",
"memory"
] |
Hidden references to function arguments causing big memory usage? | 39,644,060 | <p><strong>Edit:</strong> Never mind, I was just being completely stupid.</p>
<p>I came across code with recursion on smaller and smaller substrings, here's its essence plus my testing stuff:</p>
<pre><code>def f(s):
if len(s) == 2**20:
input('check your memory usage again')
else:
f(s[1:])
inp... | 0 | 2016-09-22T16:14:50Z | 39,644,683 | <blockquote>
<p>Are there hidden additional references to the strings somewhere or what is going on</p>
</blockquote>
<p>Well, each function has a reference to its string while its on the stack, so the <code>s = s[1:]</code> is still going to keep <code>s[1:]</code> in the next function call. After 500 recursive ca... | 1 | 2016-09-22T16:49:11Z | [
"python",
"function",
"memory"
] |
Hidden references to function arguments causing big memory usage? | 39,644,060 | <p><strong>Edit:</strong> Never mind, I was just being completely stupid.</p>
<p>I came across code with recursion on smaller and smaller substrings, here's its essence plus my testing stuff:</p>
<pre><code>def f(s):
if len(s) == 2**20:
input('check your memory usage again')
else:
f(s[1:])
inp... | 0 | 2016-09-22T16:14:50Z | 39,645,025 | <p>While each call level <strong>does</strong> get rid of its own old string, it <strong>creates</strong> and <strong>keeps</strong> its own <strong>new</strong> string.</p>
<p>(Just putting this in my own words after reading the other answers, more directly addressing what I (question author) had missed.)</p>
| 0 | 2016-09-22T17:09:01Z | [
"python",
"function",
"memory"
] |
Coalesce terminal output strings into one string with Python | 39,644,114 | <p>I am trying to fetch the output of the <code>fortune</code> command and send it to web-based WhatsApp. I am able to fetch the output from the <code>fortune</code> command, but when I send it to WhatsApp, the <code>fortune</code> output is outputted as separate lines/messages. How do I make them into one and send it ... | 1 | 2016-09-22T16:17:56Z | 39,697,319 | <p>To coalesce the output strings of terminal into one, split the output at new lines and store them in a list. </p>
<pre><code>sentence = ""
cmd = ['fortune', fortune_list_reply[i]]
output = subprocess.Popen( cmd, stdout=subprocess.PIPE ).communicate()[0]
output = output.split('\n')
for string in output:
string =... | 0 | 2016-09-26T07:48:54Z | [
"python",
"shell",
"selenium",
"terminal",
"command"
] |
python pandas how to drop duplicates selectively | 39,644,167 | <p>I need to look at all the rows in a column ['b'] and if the row is non-empty go to another corresponding column ['c'] and drop duplicates of this particular index against all other rows in that third column ['c'] while preserving this particular index. I came across drop_duplicates, however I was unable to find a wa... | 1 | 2016-09-22T16:21:24Z | 39,645,757 | <p>Say you group your DataFrame according to the <code>'C'</code> column, and check each group for the existence of a <code>'B'</code>-column non-empty entry:</p>
<ul>
<li><p>If there is no such entry, return the entire group</p></li>
<li><p>Otherwise, return the group, for the non-empty entries in <code>'B'</code>, w... | 0 | 2016-09-22T17:52:41Z | [
"python",
"pandas",
"dataframe"
] |
Can you shorten logging headers when using python logging `%(funcName)s`? | 39,644,189 | <p>Sometimes I configure the python logging formatter using the <code>%(funcName)s</code>. But I don't like this when the function names are really long.</p>
<p><strong>Can you shorten logging headers when using python logging <code>%(funcName)s</code>? If yes, how?</strong></p>
<p>Can you say... limit the total numb... | 1 | 2016-09-22T16:22:46Z | 39,644,322 | <p>You can extend the <code>logging.formatter</code> class to get the desired formatting like below.</p>
<p>This is just an example. you should modify it based on your requirement
class MyFormatter(logging.Formatter):
in_console = False
def <strong>init</strong>(self):
self.mod_width = 30
self.... | 0 | 2016-09-22T16:29:26Z | [
"python",
"logging",
"instrumentation"
] |
Can you shorten logging headers when using python logging `%(funcName)s`? | 39,644,189 | <p>Sometimes I configure the python logging formatter using the <code>%(funcName)s</code>. But I don't like this when the function names are really long.</p>
<p><strong>Can you shorten logging headers when using python logging <code>%(funcName)s</code>? If yes, how?</strong></p>
<p>Can you say... limit the total numb... | 1 | 2016-09-22T16:22:46Z | 39,644,790 | <p>The <code>%(...)s</code> items in the logging format string are % replacements, and you can limit the length of a string replacement by doing something like <code>%(funcName).10s</code></p>
<p>e.g.</p>
<pre><code>import logging
logging.basicConfig(
format='%(funcName).10s %(message)s',
level=logging.INFO,... | 2 | 2016-09-22T16:55:49Z | [
"python",
"logging",
"instrumentation"
] |
Assigning empty list | 39,644,202 | <p>I don't really know how I stumbled upon this, and I don't know what to think about it, but apparently <code>[] = []</code> is a legal operation in python, so is <code>[] = ''</code>, but <code>'' = []</code> is not allowed. It doesn't seem to have any effect though, but I'm wondering: what the hell ? </p>
| 4 | 2016-09-22T16:23:41Z | 39,644,347 | <p>This is related to Python's multiple assignment (sequence unpacking):</p>
<pre><code>a, b, c = 1, 2, 3
</code></pre>
<p>works the same as:</p>
<pre><code>[a, b, c] = 1, 2, 3
</code></pre>
<p>Since strings are sequences of characters, you can also do:</p>
<pre><code>a, b, c = "abc" # assign each character to ... | 3 | 2016-09-22T16:30:51Z | [
"python",
"list",
"binding"
] |
Assigning empty list | 39,644,202 | <p>I don't really know how I stumbled upon this, and I don't know what to think about it, but apparently <code>[] = []</code> is a legal operation in python, so is <code>[] = ''</code>, but <code>'' = []</code> is not allowed. It doesn't seem to have any effect though, but I'm wondering: what the hell ? </p>
| 4 | 2016-09-22T16:23:41Z | 39,644,456 | <p>Do some search on packing/unpacking on python and you will find your answer.
This is basically for assigning multiple variables in a single go.</p>
<pre><code>>>> [a,v] = [2,4]
>>> print a
2
>>> print v
4
</code></pre>
| 1 | 2016-09-22T16:36:18Z | [
"python",
"list",
"binding"
] |
Argparse: parse multiple subcommands | 39,644,246 | <p>Did some research, but couldn't find any working solution. I'm trying to parse the following command line, where 'test' and 'train' are two independent subcommands each having distinct arguments:</p>
<pre><code>./foo.py train -a 1 -b 2
./foo.py test -a 3 -c 4
./foo.py train -a 1 -b 2 test -a 3 -c 4
</code></pre>
... | 0 | 2016-09-22T16:25:37Z | 39,645,406 | <p>This has been asked before, though I'm not sure the best way of finding those questions.</p>
<p>The whole subparser mechanism is designed for one such command. There are several things to note:</p>
<ul>
<li><p><code>add_subparsers</code> creates a positional argument; unlike <code>optionals</code> a `positional a... | 0 | 2016-09-22T17:32:42Z | [
"python",
"argparse",
"subcommand",
"subparsers"
] |
Flask and Tornado Applciation does not handle multiple concurrent requests | 39,644,247 | <p>I am running a simple Flask app with Tornado, but the view only handles one request at a time. How can I make it handle multiple concurrent requests?</p>
<p>The fix I'm using is to fork and use the multiple processes to handle requests, but I don't like that solution.</p>
<pre><code>from flask import Flask
app =... | 0 | 2016-09-22T16:25:39Z | 39,644,448 | <p>Your fix of spawning processes is correct in as much as using WSGI with Tornado is "correct". WSGI is a synchronous protocol: one worker handles one request at a time. Flask doesn't know about Tornado, so it can't play nice with it by using coroutines: handling the request happens synchronously.</p>
<p><a href="h... | 0 | 2016-09-22T16:35:54Z | [
"python",
"flask",
"tornado"
] |
Positive Count // Negative Sum | 39,644,259 | <p>A fairly easy problem, but I'm still practicing iterating over multiple variables with for loops. In the below, I seek to return a new list, where x is the count of positive numbers and y is the sum of negative numbers from an input array <code>arr.</code></p>
<p>If the input array is empty or null, I am to return ... | 0 | 2016-09-22T16:26:07Z | 39,644,378 | <p>Simply use a <code>sum</code> comprehension</p>
<pre><code>>>> arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14, -15]
>>> sum(1 for x in arr if x > 0)
10
>>> sum(x for x in arr if x < 0)
-65
</code></pre>
| 1 | 2016-09-22T16:32:37Z | [
"python",
"list-comprehension",
"multiple-variable-return"
] |
Positive Count // Negative Sum | 39,644,259 | <p>A fairly easy problem, but I'm still practicing iterating over multiple variables with for loops. In the below, I seek to return a new list, where x is the count of positive numbers and y is the sum of negative numbers from an input array <code>arr.</code></p>
<p>If the input array is empty or null, I am to return ... | 0 | 2016-09-22T16:26:07Z | 39,644,844 | <p>wim's way is good. Numpy is good for these types of things too. </p>
<pre><code>import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14, -15])
print([arr[arr >= 0].size, arr[arr < 0].sum()])
>> [10, -65]
</code></pre>
| 1 | 2016-09-22T16:58:41Z | [
"python",
"list-comprehension",
"multiple-variable-return"
] |
Positive Count // Negative Sum | 39,644,259 | <p>A fairly easy problem, but I'm still practicing iterating over multiple variables with for loops. In the below, I seek to return a new list, where x is the count of positive numbers and y is the sum of negative numbers from an input array <code>arr.</code></p>
<p>If the input array is empty or null, I am to return ... | 0 | 2016-09-22T16:26:07Z | 39,645,221 | <p>the error you get is from this part <code>for x,y in arr</code> that mean that <code>arr</code> is expected to be a list of tuples of 2 elements (or any similar container), like for example this <code>[(1,2), (5,7), (7,9)]</code> but what you have is a list of numbers, which don't contain anything else inside... </p... | 1 | 2016-09-22T17:22:06Z | [
"python",
"list-comprehension",
"multiple-variable-return"
] |
Django: Link a field of one model to a field of another | 39,644,287 | <p>I'm working through the Tango with Django book and have decided to add some of my own functionality but have an issue.</p>
<p>I have two models, Category and Page</p>
<pre><code>class Category(models.Model):
name = models.CharField(max_length=128, unique=True)
views = models.IntegerField(default=0)
lik... | 1 | 2016-09-22T16:27:44Z | 39,644,807 | <p>I would add this to your category class instead of using the views field:</p>
<pre><code>def get_views(self):
views=0
for page in pages_set:
views+=page.views
return views
</code></pre>
| 0 | 2016-09-22T16:56:32Z | [
"python",
"django",
"database",
"models"
] |
Django: Link a field of one model to a field of another | 39,644,287 | <p>I'm working through the Tango with Django book and have decided to add some of my own functionality but have an issue.</p>
<p>I have two models, Category and Page</p>
<pre><code>class Category(models.Model):
name = models.CharField(max_length=128, unique=True)
views = models.IntegerField(default=0)
lik... | 1 | 2016-09-22T16:27:44Z | 39,645,271 | <p>You should calculate this when you need it, rather than storing it. You can do it with an aggregation on the set of related objects for your category:</p>
<pre><code>from django.db.models import Sum
my_category.page_set.aggregate(Sum('views'))
</code></pre>
<p>or use annotationif you need to get several categories... | 0 | 2016-09-22T17:25:11Z | [
"python",
"django",
"database",
"models"
] |
Matplotpib figure in a loop not responding | 39,644,336 | <p>Python 2.7.11, Win 7, x64, Numpy 1.10.4, matplotlib 1.5.1</p>
<p>I ran the following script from an iPython console after entering <code>%matplotlib qt</code> at the command line</p>
<pre><code>from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import axes3d
import numpy as np
number = input("Number: ... | 0 | 2016-09-22T16:30:19Z | 39,644,651 | <p>I haven't replicated but when you input the <code>'y'</code> or <code>'n'</code>. try to put the single (or double quotes) are the <code>y</code> or <code>n</code></p>
<p>to input strings without quotes. Use <code>raw_input</code> instead of <code>input</code></p>
<p>as described here <a href="http://stackoverflow... | 1 | 2016-09-22T16:47:20Z | [
"python",
"numpy",
"matplotlib"
] |
Matplotpib figure in a loop not responding | 39,644,336 | <p>Python 2.7.11, Win 7, x64, Numpy 1.10.4, matplotlib 1.5.1</p>
<p>I ran the following script from an iPython console after entering <code>%matplotlib qt</code> at the command line</p>
<pre><code>from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import axes3d
import numpy as np
number = input("Number: ... | 0 | 2016-09-22T16:30:19Z | 39,648,572 | <p><a href="https://docs.python.org/2.7/library/functions.html?highlight=input#input" rel="nofollow"><code>input</code></a> tries to <a href="https://docs.python.org/2.7/library/functions.html?highlight=input#eval" rel="nofollow"><code>eval</code></a> the string you type in, treating it as though it is Python code, the... | 1 | 2016-09-22T20:44:22Z | [
"python",
"numpy",
"matplotlib"
] |
Matplotlib animation with blit -- how to update plot title? | 39,644,461 | <p>I use matplotlib to animate a plot, by copying the background and blitting:</p>
<pre><code>f = Figure(tight_layout=True)
canvas = FigureCanvasTkAgg(f, master=pframe)
canvas.get_tk_widget().pack()
ax = f.add_subplot(111)
# Set inial plot title
title = ax.set_title("First title")
canvas.show()
# Capture the backgroun... | 0 | 2016-09-22T16:36:41Z | 39,664,639 | <p>The following draws the plot and allows you to make changes,</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots(1,1)
ax.plot(np.linspace(0.,10.,100))
title = ax.set_title("First title")
plt.show(block=False)
</code></pre>
<p>The title can then be updated using,</p>
<pre><cod... | 0 | 2016-09-23T15:36:34Z | [
"python",
"animation",
"matplotlib",
"blit"
] |
Django Template Tags Creating Spaces | 39,644,478 | <p>I am working on a Django site which is live at <a href="http://petervkay.pythonanywhere.com/police_archive/officer/1903/" rel="nofollow">this site</a>. I am getting unwanted spaces in my output caused by unwanted whitespace in the HTML. </p>
<p>For instance, "01-1737 , Civilian Review Authority , INAPPROPRIATE LA... | 2 | 2016-09-22T16:38:08Z | 39,645,098 | <p>The reason <code>{% spaceless %}</code> didn't give remove all the space for you is because it only works <strong>between</strong> HTML tags. You whitespace is showing up <strong>within</strong> the <code><li></code> tag.</p>
<p>I can't seem to find a good solution for Django's standard templating system, but... | 1 | 2016-09-22T17:14:25Z | [
"python",
"django"
] |
How can i remove all extra characters from list of strings to convert to ints | 39,644,486 | <p>Hi I'm pretty new to programming and Python, and this is my first post, so I apologize for any poor form.</p>
<p>I am scraping a website's download counts and am receiving the following error when attempting to convert the list of string numbers to integers to get the sum.
<strong>ValueError: invalid literal for in... | -1 | 2016-09-22T16:38:27Z | 39,644,556 | <p>Strings are not mutable in Python. So when you call <code>item.replace(",", "")</code>, the method returns what you want, but it is not stored anywhere (thus not in <code>item</code>).</p>
<p><strong>EDIT :</strong></p>
<p>I suggest this :</p>
<pre><code>for i in range(len(downloadCount_clean)):
if "," in dow... | 2 | 2016-09-22T16:41:47Z | [
"python",
"replace",
"string-conversion"
] |
How can i remove all extra characters from list of strings to convert to ints | 39,644,486 | <p>Hi I'm pretty new to programming and Python, and this is my first post, so I apologize for any poor form.</p>
<p>I am scraping a website's download counts and am receiving the following error when attempting to convert the list of string numbers to integers to get the sum.
<strong>ValueError: invalid literal for in... | -1 | 2016-09-22T16:38:27Z | 39,644,689 | <p>For simplicities sake:</p>
<pre><code>>>> aList = ["abc", "42", "1,423", "def"]
>>> bList = []
>>> for i in aList:
... bList.append(i.replace(',',''))
...
>>> bList
['abc', '42', '1423', 'def']
</code></pre>
<p>or working just with a single list:</p>
<pre><code>>>>... | 0 | 2016-09-22T16:49:31Z | [
"python",
"replace",
"string-conversion"
] |
How to find ASN.1 components of EC key python-cryptography | 39,644,514 | <p>I am generating a EC key using python cryptography module in this way</p>
<pre><code>from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import ec
key=ec.generate_private_key(ec.SECP256R1(), default_backend())
</code></pre>
<p>The asn.1 structure of EC key is as ... | 6 | 2016-09-22T16:39:48Z | 39,694,727 | <p>It's relatively easy to extract the public point from the ASN.1 sequence using <a href="https://pypi.python.org/pypi/pyasn1" rel="nofollow">pyasn1</a>, but if you want PEM-encrypted PKCS1 (aka "traditional OpenSSL") then pyca/cryptography can do that quite easily:</p>
<pre><code>from cryptography.hazmat.backends im... | 0 | 2016-09-26T04:26:39Z | [
"python",
"cryptography",
"openssh",
"python-cryptography"
] |
Slice list of lists without numpy | 39,644,517 | <p>In Python, how could I slice my list of lists and get a sub list of lists without numpy?</p>
<p>For example, get a list of lists from A[1][1] to A[2][2] and store it in B:</p>
<pre><code>A = [[1, 2, 3, 4 ],
[11, 12, 13, 14],
[21, 22, 23, 24],
[31, 32, 33, 34]]
B = [[12, 13],
[22, 23]]
</cod... | 2 | 2016-09-22T16:39:55Z | 39,644,552 | <p>You can <em>slice</em> <code>A</code> and its sublists:</p>
<pre><code>In [1]: A = [[1, 2, 3, 4 ],
...: [11, 12, 13, 14],
...: [21, 22, 23, 24],
...: [31, 32, 33, 34]]
In [2]: B = [l[1:3] for l in A[1:3]]
In [3]: B
Out[3]: [[12, 13], [22, 23]]
</code></pre>
| 7 | 2016-09-22T16:41:36Z | [
"python",
"list",
"slice"
] |
Slice list of lists without numpy | 39,644,517 | <p>In Python, how could I slice my list of lists and get a sub list of lists without numpy?</p>
<p>For example, get a list of lists from A[1][1] to A[2][2] and store it in B:</p>
<pre><code>A = [[1, 2, 3, 4 ],
[11, 12, 13, 14],
[21, 22, 23, 24],
[31, 32, 33, 34]]
B = [[12, 13],
[22, 23]]
</cod... | 2 | 2016-09-22T16:39:55Z | 39,645,000 | <p>You may also perform nested list slicing using <a href="https://docs.python.org/2/library/functions.html#map" rel="nofollow"><code>map()</code></a> function as:</p>
<pre><code>B = map(lambda x: x[1:3], A[1:3])
# Value of B: [[12, 13], [22, 23]]
</code></pre>
<p>where <code>A</code> is the list mentioned in the que... | 0 | 2016-09-22T17:07:46Z | [
"python",
"list",
"slice"
] |
Django 1.9 adding a class to form label | 39,644,629 | <p>In my forms.py file I reconfigured the class UserForm's <code>__init__</code> function to include a css class. Unfortunately doing this only allowed me to add a class to the <code><input></code> and not the <code><label></code>. How can I add a class to the label as well?</p>
<p>Here is my forms.py file... | 0 | 2016-09-22T16:45:46Z | 39,645,855 | <p>Look at <a href="https://github.com/kmike/django-widget-tweaks/" rel="nofollow">Django Widget Tweaks</a>.</p>
| 0 | 2016-09-22T17:58:53Z | [
"python",
"django",
"django-forms",
"django-templates",
"django-1.9"
] |
How to take the nth digit of a number in python | 39,644,638 | <p>I want to take the nth digit from an N digit number in python. For example:</p>
<pre><code>number = 9876543210
i = 4
number[i] # should return 6
</code></pre>
<p>How can I do something like that in python? Should I change it to string first and then change it to int for the calculation?</p>
| -3 | 2016-09-22T16:46:31Z | 39,644,706 | <p>First treat the number like a string</p>
<pre><code>number = 9876543210
number = str(number)
</code></pre>
<p>Then to get the first digit:</p>
<pre><code>number[0]
</code></pre>
<p>The fourth digit:</p>
<pre><code>number[3]
</code></pre>
<p>EDIT:</p>
<p>This will return the digit as a character, not as a numb... | 2 | 2016-09-22T16:50:04Z | [
"python",
"int"
] |
How to take the nth digit of a number in python | 39,644,638 | <p>I want to take the nth digit from an N digit number in python. For example:</p>
<pre><code>number = 9876543210
i = 4
number[i] # should return 6
</code></pre>
<p>How can I do something like that in python? Should I change it to string first and then change it to int for the calculation?</p>
| -3 | 2016-09-22T16:46:31Z | 39,644,726 | <p>You can do it with integer division and remainder methods</p>
<pre><code>def get_digit(number, n):
return number // 10**n % 10
get_digit(987654321, 0)
# 1
get_digit(987654321, 5)
# 6
</code></pre>
<p>The <code>//</code> does integer division by a power of ten to move the digit to the ones position, then the ... | 0 | 2016-09-22T16:51:18Z | [
"python",
"int"
] |
Notation for intervals? | 39,644,748 | <p>I want to make a Python class for intervals of real numbers. Syntax most closely related to mathematical notation would be <code>Interval([a, b))</code> or, even better, <code>Interval[a, b)</code> to construct the interval of all real <code>x</code> satisfying <code>a <= x < b</code>.</p>
<p>Is it possible t... | 3 | 2016-09-22T16:53:10Z | 39,644,792 | <p>It's impossible to "fix" syntactically invalid python by making a custom class.</p>
<p>I think the closest you can get to the mathematical interval notation in python is</p>
<pre><code>Interval('[a, b)')
</code></pre>
<p>This way becomes even more lightweight if you are passing intervals as arguments to a functio... | 4 | 2016-09-22T16:55:51Z | [
"python"
] |
Notation for intervals? | 39,644,748 | <p>I want to make a Python class for intervals of real numbers. Syntax most closely related to mathematical notation would be <code>Interval([a, b))</code> or, even better, <code>Interval[a, b)</code> to construct the interval of all real <code>x</code> satisfying <code>a <= x < b</code>.</p>
<p>Is it possible t... | 3 | 2016-09-22T16:53:10Z | 39,645,859 | <p>You cannot make this exact syntax work. But you <em>could</em> do something like this by overriding the relevant comparison methods:</p>
<pre><code>a <= Interval() < b
</code></pre>
<p>This whole expression could then return a new <code>Interval</code> object that includes everything greater than or equal t... | 0 | 2016-09-22T17:59:04Z | [
"python"
] |
Notation for intervals? | 39,644,748 | <p>I want to make a Python class for intervals of real numbers. Syntax most closely related to mathematical notation would be <code>Interval([a, b))</code> or, even better, <code>Interval[a, b)</code> to construct the interval of all real <code>x</code> satisfying <code>a <= x < b</code>.</p>
<p>Is it possible t... | 3 | 2016-09-22T16:53:10Z | 39,646,218 | <p>You can't change Python's existing syntax rules (without changing the whole language), but you can get usably close to what you want:</p>
<pre><code>class Interval(object):
def __init__(self, left_bracket, a, b, right_bracket):
if len(left_bracket) !=1 or left_bracket not in '[(':
raise Valu... | 1 | 2016-09-22T18:19:32Z | [
"python"
] |
Call text but totally exclude tables | 39,644,778 | <p>I am using Beautiful Soup to load an XMl. All I need is the text, ignoring the tags, and the <code>text</code> attribute words nice.</p>
<p>However, I would like to totally exclude anything within <code><table><\table></code> tags. I had the idea of substituting everything in between with a regex, but... | 1 | 2016-09-22T16:55:05Z | 39,644,824 | <p>You can locate the <code>content</code> element and remove all <code>table</code> elements from it, then get the text:</p>
<pre><code>from bs4 import BeautifulSoup
s =""" <content><p>Hasselt ( ) is a <link target="Belgium">Belgian</link> <link target="city">city</link> and <l... | 1 | 2016-09-22T16:57:24Z | [
"python",
"xml",
"xml-parsing",
"beautifulsoup"
] |
Storing Kernel in Separate File - PyOpenCL | 39,644,821 | <p>I'm trying to store the kernel part of the code, with the 3 """ , in a different file. I tried saving it as a text file and a bin file, and reading it in, but I didn't find success with it. It started giving me an error saying """ is missing, or ) is missing. "However, if i just copy paste the kernel code into cl.Pr... | 0 | 2016-09-22T16:57:19Z | 39,646,088 | <p>Just put your kernel code in a plain text file, and then use <code>open(...).read()</code> to get the contents:</p>
<p><strong>foo.cl</strong></p>
<pre><code>__kernel void sum(__global double *a, __global double *b, __global double *c)
{
int gid = get_global_id(0);
c[gid] = 1;
}
</code></pre>
<p><strong>Pyth... | 0 | 2016-09-22T18:12:23Z | [
"python",
"opencl",
"pycuda",
"pyopencl"
] |
Turning a list into a string to then finding the location of the words in the string | 39,644,847 | <p><strong>Code: (Python 3.5.2)</strong></p>
<pre><code>import time
import sys
def Word_Position_Finder():
Chosen_Sentence = input("Make a simple sentence: ")
Sentence_List = Chosen_Sentence.split()
if len(Chosen_Sentence) == 0:
print("Your Sentence has no words! Restarting Program.")
tim... | 0 | 2016-09-22T16:58:58Z | 39,645,311 | <p>How's this?</p>
<pre><code> words_list = Users_Sentence.split()
for index, word in enumerate(words_list):
if(word == Chosen_Word):
print("Your word appears in the number " + str(index) + " slot of this sentence")
</code></pre>
<p>Here's some console output to show what split and enumerat... | 1 | 2016-09-22T17:27:51Z | [
"python"
] |
How to convert the string '1.000,0.001' to the complex number (1+0.001j)? | 39,644,848 | <p>The best I could come up with is</p>
<pre><code>s = '1.000,0.001'
z = [float(w) for w in s.split(',')]
x = complex(z[0],z[1])
</code></pre>
<p>Is there a shorter, cleaner, nicer way?</p>
| 1 | 2016-09-22T16:59:01Z | 39,644,899 | <p>I guess you could do the slightly shorter</p>
<pre><code>real, imag = s.split(',')
x = complex(float(real), float(imag))
</code></pre>
<p>without involving the list comprehension.</p>
| 0 | 2016-09-22T17:02:12Z | [
"python",
"complex-numbers"
] |
How to convert the string '1.000,0.001' to the complex number (1+0.001j)? | 39,644,848 | <p>The best I could come up with is</p>
<pre><code>s = '1.000,0.001'
z = [float(w) for w in s.split(',')]
x = complex(z[0],z[1])
</code></pre>
<p>Is there a shorter, cleaner, nicer way?</p>
| 1 | 2016-09-22T16:59:01Z | 39,644,903 | <p>What you have is fine. The only improvement I could suggest is to use </p>
<pre><code>complex(*z)
</code></pre>
<p>If you want to one-liner it:</p>
<pre><code>>>> complex(*map(float, s.split(',')))
(1+0.001j)
</code></pre>
| 2 | 2016-09-22T17:02:22Z | [
"python",
"complex-numbers"
] |
How to convert the string '1.000,0.001' to the complex number (1+0.001j)? | 39,644,848 | <p>The best I could come up with is</p>
<pre><code>s = '1.000,0.001'
z = [float(w) for w in s.split(',')]
x = complex(z[0],z[1])
</code></pre>
<p>Is there a shorter, cleaner, nicer way?</p>
| 1 | 2016-09-22T16:59:01Z | 39,644,904 | <p>There's a more concise way, but it's not really any cleaner and it's certainly not clearer.</p>
<pre><code>x = complex(*[float(w) for w in '1.000,.001'.split(',')])
</code></pre>
| 2 | 2016-09-22T17:02:30Z | [
"python",
"complex-numbers"
] |
How to convert the string '1.000,0.001' to the complex number (1+0.001j)? | 39,644,848 | <p>The best I could come up with is</p>
<pre><code>s = '1.000,0.001'
z = [float(w) for w in s.split(',')]
x = complex(z[0],z[1])
</code></pre>
<p>Is there a shorter, cleaner, nicer way?</p>
| 1 | 2016-09-22T16:59:01Z | 39,645,633 | <p>If you can trust the data to not be dangerous or want this for code golf:</p>
<pre><code>>>> eval('complex(%s)' % s)
(1+0.001j)
</code></pre>
| -1 | 2016-09-22T17:45:58Z | [
"python",
"complex-numbers"
] |
python: best way convey missing value count | 39,644,866 | <p>I currently have a data frame with 9 features and some features have missing values. I do the following to get the <code>count</code> of missing values in each feature:</p>
<pre><code>df.isnull().sum()
</code></pre>
<p>which gives me:</p>
<pre><code>A 0
B 0
C 15844523
D 717
E ... | 1 | 2016-09-22T17:00:39Z | 39,645,171 | <p>You can visualize the count of the missing values with vertical bars.</p>
<p>Use the pandas.DataFrame.plot() method :</p>
<pre><code>df.isnull().sum().plot(kind='bar')
</code></pre>
<p>For more fancy plots you can use the python library
<a href="https://plot.ly/python/" rel="nofollow"> <strong>plot.ly</strong></a... | 1 | 2016-09-22T17:19:24Z | [
"python",
"python-2.7",
"pandas",
"visualization",
"data-visualization"
] |
python: best way convey missing value count | 39,644,866 | <p>I currently have a data frame with 9 features and some features have missing values. I do the following to get the <code>count</code> of missing values in each feature:</p>
<pre><code>df.isnull().sum()
</code></pre>
<p>which gives me:</p>
<pre><code>A 0
B 0
C 15844523
D 717
E ... | 1 | 2016-09-22T17:00:39Z | 39,645,233 | <p>I think you can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.log.html" rel="nofollow"><code>numpy.log</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.plot.bar.html" rel="nofollow"><code>Series.plot.bar</code></a>:</p>
<pre><code>import matplotli... | 2 | 2016-09-22T17:22:42Z | [
"python",
"python-2.7",
"pandas",
"visualization",
"data-visualization"
] |
django validation error message get displayed twice | 39,644,875 | <p>I just want to have an error message when user failed to login due to invalid username or password. Is there any preferable why to have it than overriding clean method. I found that django have login_failed signals but i am unsure it best to use that.</p>
<p>Here is the print screen
<a href="http://i.stack.imgur.co... | 0 | 2016-09-22T17:01:04Z | 39,645,206 | <p>The <code>clean</code> method needs to use <code>super()</code>:</p>
<pre><code>def clean(self):
cleaned_data = super(AuthorLogin, self).clean() #insert this line
username = cleaned_data.get('username')
...
</code></pre>
| 0 | 2016-09-22T17:21:12Z | [
"python",
"django"
] |
django validation error message get displayed twice | 39,644,875 | <p>I just want to have an error message when user failed to login due to invalid username or password. Is there any preferable why to have it than overriding clean method. I found that django have login_failed signals but i am unsure it best to use that.</p>
<p>Here is the print screen
<a href="http://i.stack.imgur.co... | 0 | 2016-09-22T17:01:04Z | 39,651,617 | <p>you can try this as is described in the documentation:</p>
<pre><code>def clean(self):
super(AuthorLogin, self).clean()
...
# not return anything
</code></pre>
| 0 | 2016-09-23T02:25:23Z | [
"python",
"django"
] |
Generic binary operation in a class definition? | 39,644,885 | <p>I am writing a tiny linear algebra module in Python 3, and there are a number of binary operators to define. Since each definition of a binary operator is essentially the same with only the operator itself changed, I would like to save some work by writing a generic binary operator definition only once.</p>
<p>For ... | 2 | 2016-09-22T17:01:28Z | 39,645,057 | <p>You <em>can</em> do magical things with <code>__getattr__</code>, but if you can avoid doing so then I would - it starts to get complicated! In this situation you'd likely need to overwrite <code>__getattribute__</code>, but please don't because you will bite yourself in the seat of your own pants if you start messi... | 0 | 2016-09-22T17:11:20Z | [
"python",
"class"
] |
Generic binary operation in a class definition? | 39,644,885 | <p>I am writing a tiny linear algebra module in Python 3, and there are a number of binary operators to define. Since each definition of a binary operator is essentially the same with only the operator itself changed, I would like to save some work by writing a generic binary operator definition only once.</p>
<p>For ... | 2 | 2016-09-22T17:01:28Z | 39,645,129 | <p>You can do this with the <code>operator</code> module, which gives you functional versions of the operators. For example, <code>operator.and_(a, b)</code> is the same as <code>a & b</code>.</p>
<p>So <code>return Vector(a + x for a in self)</code> becomes <code>return Vector(op(a, x) for a in self)</code> and y... | 1 | 2016-09-22T17:16:35Z | [
"python",
"class"
] |
Generic binary operation in a class definition? | 39,644,885 | <p>I am writing a tiny linear algebra module in Python 3, and there are a number of binary operators to define. Since each definition of a binary operator is essentially the same with only the operator itself changed, I would like to save some work by writing a generic binary operator definition only once.</p>
<p>For ... | 2 | 2016-09-22T17:01:28Z | 39,645,305 | <p>You could use a class decorator to mutate your class and add them all in with the help of a factory function:</p>
<pre><code>import operator
def natural_binary_operators(cls):
for name, op in {
'__add__': operator.add,
'__sub__': operator.sub,
'__mul__': operator.mul,
'__truediv... | 2 | 2016-09-22T17:27:15Z | [
"python",
"class"
] |
Generic binary operation in a class definition? | 39,644,885 | <p>I am writing a tiny linear algebra module in Python 3, and there are a number of binary operators to define. Since each definition of a binary operator is essentially the same with only the operator itself changed, I would like to save some work by writing a generic binary operator definition only once.</p>
<p>For ... | 2 | 2016-09-22T17:01:28Z | 39,645,463 | <h2>Update:</h2>
<p>This might be super-slow, but you can create an abstract class with all of the binary methods and inherit from it.</p>
<pre><code>import operator
def binary_methods(cls):
operator_list = (
'__add__', '__sub__', '__mul__', '__truediv__',
'__floordiv__', '__and__', '__or__', '_... | 1 | 2016-09-22T17:36:47Z | [
"python",
"class"
] |
Errors using sys from Python Embedded in C++ | 39,644,907 | <p>I am using Eclipse to run C++. In my code,I use a High Level Embedding of Python to run a function. When I try to use sys and import it. I get the error:</p>
<p><em>Fatal Python error: no mem for sys.argv</em></p>
<p>CODE:</p>
<pre><code>#include <python3.4m/Python.h>
#include <iostream>
#include <... | 0 | 2016-09-22T17:02:46Z | 39,645,493 | <p>The error was that Python expected an **argv to point to a set of unicode values. Instead argv was pointing to chars.</p>
<p>To solve this:</p>
<pre><code>wchar_t **wargv;
wargv = (wchar_t**)malloc(1*sizeof(wchar_t *));
*wargv = (wchar_t*)malloc(6*sizeof(wchar_t));
**wargv = L'argv1';
Py_Initialize();
PySys_SetAr... | 0 | 2016-09-22T17:38:55Z | [
"python",
"c++",
"unicode",
"sys",
"python-embedding"
] |
Ability to read and eval() any arbitrary function / lambda from JSON config file | 39,645,014 | <p>I am looking for a way to a user to enter any arbitrary python formula, store the formula in a text file or a JSON file, then have Python read the formula and apply the transformation to a data frame. My original requirement is to have a frontend web UI where the user can specify any transformation rules / scripts ... | 0 | 2016-09-22T17:08:28Z | 39,645,122 | <p>The <code>eval</code> function in Python isn't a method attached to strings; it's a globally available function. You should be able to call it like:</p>
<pre><code>eval(..)
</code></pre>
<p>If you're trying to transform <code>df['state_abbrev']</code> according to the contents of <code>lambda_transform_str</code>,... | 1 | 2016-09-22T17:16:03Z | [
"python",
"json",
"lambda"
] |
Value Error: x and y must have the same first dimension | 39,645,020 | <p>Let me quickly brief you first, I am working with a .txt file with 5400 data points. Each is a 16 second average over a 24 hour period (24 hrs * 3600 s/hr = 86400...86400/16 = 5400). In short this is the average magnetic strength in the z direction for an inbound particle field curtsy of the Advanced Composition Exp... | 0 | 2016-09-22T17:08:56Z | 39,647,130 | <p>The problem was the selection of array creation. Instead of linspace, I should have used arange. </p>
<pre><code>Mag_time = np.arange(0,86400, 16, dtype = float)
</code></pre>
| 0 | 2016-09-22T19:10:47Z | [
"python",
"numpy",
"matplotlib"
] |
Dynamic database selection based on URL in Django | 39,645,043 | <p>Let's say the first page of the app has two links. Is it possible to pick the database depending on which link is clicked? The databases both have the same models, but different data. For example, let's say the application contains students for different colleges <code>A</code> and <code>B</code>. If link for <code>... | 0 | 2016-09-22T17:10:14Z | 39,645,212 | <p>So you need to store the chosen database in <code>session</code> or smth and you can easily pick the database. From the <a href="https://docs.djangoproject.com/en/1.10/topics/db/multi-db/#manually-selecting-a-database-for-a-queryset" rel="nofollow">docs</a></p>
<pre><code>>>> # This will run on the 'defaul... | 1 | 2016-09-22T17:21:28Z | [
"python",
"django",
"django-models"
] |
LabelEncoder().fit_transform vs. pd.get_dummies for categorical coding | 39,645,125 | <p>It was recently brought to my attention that if you have a dataframe <code>df</code> like this:</p>
<pre><code> A B C
0 0 Boat 45
1 1 NaN 12
2 2 Cat 6
3 3 Moose 21
4 4 Boat 43
</code></pre>
<p>You can encode the categorical data automatically with <code>pd.get_dummies</code>:</p>
<p... | 3 | 2016-09-22T17:16:11Z | 39,649,124 | <p>Yes, you can skip the use of <code>LabelEncoder</code> if you only want to encode string features. On the other hand if you have a categorical column of integers (instead of strings) then <code>pd.get_dummies</code> will leave as it is (see your A or C column for example). In that case you should use <a href="http:/... | 3 | 2016-09-22T21:25:38Z | [
"python",
"pandas",
"scikit-learn",
"sklearn-pandas"
] |
How to access a .txt file at a secured url? | 39,645,127 | <p>I want to read a file from a secured url.</p>
<p>For example: <a href="https://foo.net/test.txt" rel="nofollow">https://foo.net/test.txt</a></p>
<p>when I use: </p>
<pre><code>readtext = urllib.urlopen('https://foo.net/test.txt').read()
</code></pre>
<p>I get a request for username and password. After entering t... | 0 | 2016-09-22T17:16:23Z | 39,645,393 | <p>I'm sure it's almost as trivial to do in urllib as it is in requests, but requests is just so darn pretty:</p>
<pre><code>import requests
from requests.auth import HTTPBasicAuth
r = requests.get('https://foo.net/test.txt', auth=HTTPBasicAuth('user', 'pass'))
</code></pre>
| 2 | 2016-09-22T17:31:38Z | [
"python"
] |
The area of the intersection of two ovals (ellipses)? | 39,645,153 | <p>I need to calculate the amount of two oval intersects in a python program.
I know in <a href="https://pypi.python.org/pypi/Shapely" rel="nofollow">shaply</a> there is a function that return true if two object has intersects. As like as this:</p>
<pre><code>from shapely.geometry import Polygon
p1=Polygon([(0,0),(1,1... | 2 | 2016-09-22T17:17:44Z | 39,645,243 | <p>Is this what you are looking for? (the polygon that results from the intersection)</p>
<pre><code>x = p1.intersection(p2)
x.area
</code></pre>
<p>Find more information in the documentation <a href="http://toblerity.org/shapely/manual.html" rel="nofollow">here</a></p>
| 3 | 2016-09-22T17:23:31Z | [
"python",
"geometry",
"polygon",
"shapely.geometry"
] |
Mapping sums of defaultdict(list) to one list | 39,645,290 | <p>I have a large collection of data formatted somewhat like the <code>d.items()</code> of a <code>defaultdict(list)</code>. See below:</p>
<pre><code>products = [(('blue'), ([2, 4, 2, 4, 2, 4, 2, 4, 2, 4], [2, 4, 2, 4, 2, 4, 2, 4, 2, 4], [2, 4, 2, 4, 2, 4, 2, 4, 2, 4])),
(('yellow'), ([1, 3, 1, 3, 1, 3, 1, 3,... | 0 | 2016-09-22T17:26:12Z | 39,645,434 | <p>From what I understand, you need to <em>zip</em> the sublists in the list and sum them up:</p>
<pre><code>>>> sums = [(key, [sum(value) for value in zip(*values)]) for key, values in products]
>>> for s in sums:
... print(s)
...
('blue', [6, 12, 6, 12, 6, 12, 6, 12, 6, 12])
('yellow', [3, 9, ... | 3 | 2016-09-22T17:34:45Z | [
"python",
"list",
"python-3.x",
"mapping",
"defaultdict"
] |
Mapping sums of defaultdict(list) to one list | 39,645,290 | <p>I have a large collection of data formatted somewhat like the <code>d.items()</code> of a <code>defaultdict(list)</code>. See below:</p>
<pre><code>products = [(('blue'), ([2, 4, 2, 4, 2, 4, 2, 4, 2, 4], [2, 4, 2, 4, 2, 4, 2, 4, 2, 4], [2, 4, 2, 4, 2, 4, 2, 4, 2, 4])),
(('yellow'), ([1, 3, 1, 3, 1, 3, 1, 3,... | 0 | 2016-09-22T17:26:12Z | 39,645,939 | <p>As an alternative to @alecxe's answer consider the following using <code>map</code> and a nice list literal-unpack:</p>
<pre><code>res = [(k, [*map(sum, zip(*v))]) for k, v in products]
</code></pre>
<p>This yields:</p>
<pre><code>[('blue', [6, 12, 6, 12, 6, 12, 6, 12, 6, 12]),
('yellow', [3, 9, 3, 9, 3, 9, 3, 9... | 2 | 2016-09-22T18:03:44Z | [
"python",
"list",
"python-3.x",
"mapping",
"defaultdict"
] |
Display Pandas DataFrame in csv format | 39,645,404 | <p>I have a pandas dataframe <code>q2</code> which looks like this:</p>
<pre><code> StudentID Subjects
6 323 History
9 323 Physics
8 999 Chemistry
7 999 History
4 999 Physics
0 1234 Chemistry
5 2834 Physics
1 3455 Che... | 1 | 2016-09-22T17:32:39Z | 39,645,454 | <p>I think you can <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.apply.html" rel="nofollow"><code>apply</code></a> function <code>join</code>. Also for creating <code>DataFrame</code> you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.reset_index.html... | 2 | 2016-09-22T17:35:58Z | [
"python",
"list",
"pandas",
"dataframe",
"unique"
] |
How to upload multiple files in django rest framework | 39,645,410 | <p>In django rest framework, I am able to upload single file using <a href="https://github.com/danialfarid/ng-file-upload" rel="nofollow">danialfarid/ng-file-upload</a> </p>
<p>views.py:</p>
<pre><code>class PhotoViewSet(viewsets.ModelViewSet):
serializer_class = PhotoSerializer
parser_classes = (MultiPartPar... | 0 | 2016-09-22T17:32:48Z | 39,668,395 | <p>I manage to solve this issue and I hope it will help community</p>
<p>serializers.py:</p>
<pre><code>class FileListSerializer ( serializers.Serializer ) :
image = serializers.ListField(
child=serializers.FileField( max_length=100000,
allow_empty_f... | 2 | 2016-09-23T19:39:46Z | [
"python",
"angularjs",
"django",
"django-rest-framework"
] |
Mocking out two redis hgets with different return values in the same python function | 39,645,472 | <p>I have some code like this:</p>
<pre><code>import redis
redis_db = redis.Redis(host=redis_host_ip, port=redis_port, password=redis_auth_password)
def mygroovyfunction():
var_a = redis_db.hget(user, 'something_a')
var_b = redis_db.hget(user, 'something_b')
if var_a == something_a:
return Respon... | 1 | 2016-09-22T17:37:29Z | 39,647,623 | <p>Ok I found the answer here: <a href="http://stackoverflow.com/questions/24897145/python-mock-multiple-return-values">Python mock multiple return values</a></p>
<p>The accepted answer for that question is what I was looking for, which is to use <code>side_effect</code> and make it a list of values and so each patche... | 2 | 2016-09-22T19:42:49Z | [
"python",
"unit-testing",
"mocking",
"python-unittest",
"python-mock"
] |
How to transform nonlinear model to linear? | 39,645,488 | <p>I'm ananlyzing a dataset, and I know that the data should follow a power model:</p>
<pre><code>y = a*x**b
</code></pre>
<p>I transformed it to linear by taking logarithms:</p>
<pre><code>ln(y) = ln(a) + b* ln(x)
</code></pre>
<p>However, the problems arised on adding a trend line to the plot</p>
<pre><code>slop... | 1 | 2016-09-22T17:38:30Z | 39,646,128 | <p>Your green strange plot is what you get when you do a line plot in <code>matplotlib</code>, with the <code>x</code> values unsorted. It's a line plot, but it connects by lines <em>(x, y)</em> pairs jumping right and left (in your specific case, it looks like back to near the x-origin). That gives these strange patte... | 5 | 2016-09-22T18:14:53Z | [
"python",
"matplotlib",
"plot",
"scipy",
"linear-regression"
] |
Clean separation between application thread and Qt thread (Python - PyQt) | 39,645,504 | <p>I prefer to write my application without even thinking about a graphical user interface. Once the application code is working properly, I like to glue a GUI layer on top of it - with a clean interface between the two.</p>
<p>I first tried to make the GUI run in a different <strong>process</strong> from the applicat... | 1 | 2016-09-22T17:39:39Z | 39,694,075 | <p>What I suggest is to do what most others do. Wait until there is code that needs to be run in a separate thread, and then <em>only</em> put that piece of code in a thread. There is no need for your code to be in a separate thread to have good code separation. The way I would do it is the following:</p>
<p>Have your... | 1 | 2016-09-26T02:56:52Z | [
"python",
"multithreading",
"python-3.x"
] |
Python TypeError Traceback (most recent call last) | 39,645,563 | <p>I am trying the build a crawler, and I want to print all the links on that page
I am using Python 3.5</p>
<p>there is my code </p>
<pre><code>import requests
from bs4 import BeautifulSoup
def crawler(link):
source_code = requests.get(link)
source_code_string = str(source_code)
source_code_soup = Beauti... | 0 | 2016-09-22T17:42:35Z | 39,646,332 | <p>If you are intentions are to just print the titles of the link, you are making a small mistake, replace the line :</p>
<pre><code>source_code_string = str(source_code)
</code></pre>
<p>use </p>
<pre><code>source_code_string = source_code.text
</code></pre>
<p>Apart from that the code looks fine and is running.
... | 2 | 2016-09-22T18:26:04Z | [
"python",
"web-crawler"
] |
How to let python function pass more variables than what's accepted in the definition? | 39,645,570 | <p>I have a very generic function call that looks like</p>
<pre><code>result = getattr(class_name, func_name)(result)
</code></pre>
<p>This function call updates <code>result</code>. This function call is very generic such that it can invoke many functions from different classes. Currently, all these functions only t... | 0 | 2016-09-22T17:43:01Z | 39,645,671 | <p>The general solution for this is that when we want to provide a common function name such as this, that it is the responsibility of each class to implement its local definition of that function. This is why you see, for example, a method <strong>__init__</strong> in many different classes. The system standardizes ... | 0 | 2016-09-22T17:47:27Z | [
"python",
"python-2.7"
] |
How to let python function pass more variables than what's accepted in the definition? | 39,645,570 | <p>I have a very generic function call that looks like</p>
<pre><code>result = getattr(class_name, func_name)(result)
</code></pre>
<p>This function call updates <code>result</code>. This function call is very generic such that it can invoke many functions from different classes. Currently, all these functions only t... | 0 | 2016-09-22T17:43:01Z | 39,645,775 | <p>You can add a <code>*</code> within the function call. This will pass <code>result</code> as multiple arguments. Lets say you have two functions:</p>
<pre><code>class YourClass:
def my_first_def(one_arg):
return (1, 2)
def my_second_def(one_arg, second_arg):
return (1, 2, 3)
if not instanceof(r... | 0 | 2016-09-22T17:53:41Z | [
"python",
"python-2.7"
] |
Calling mpmath directly from C | 39,645,580 | <p>I want to access mpmath's special functions from a C code.
I know how to do it via an intermediate python script.
For instance, in order to evaluate the hypergeometric function, the C program:</p>
<pre><code>#include <Python.h>
void main (int argc, char *argv[])
{
int npars= 4;
double a1, a2, b1, x, re... | -1 | 2016-09-22T17:43:19Z | 39,648,752 | <blockquote>
<p>What? No! Literally do the things you did to access
GGauss_2F1.Gauss_2F1, just with the names changed. Why are you trying
to PyRun_SimpleString("from mpmath import *")? â user2357112</p>
</blockquote>
<p>Ok. Following your suggestions:</p>
<pre><code>#include <Python.h>
void main (int ... | 0 | 2016-09-22T20:57:58Z | [
"python",
"c",
"mpmath"
] |
Rounding up a value to next int | 39,645,691 | <p>I need to make a paint program that rounds up to the next gallon, however I am having a problem. When all said in done, lets say height is 96, width is 240, and length is 200, it equals out to 919 feet. Subtract a few walls and windows and I have 832 square feet. Now I divide that by 200 and it gives me 4.3 but I ca... | -1 | 2016-09-22T17:48:23Z | 39,645,979 | <p>I think if you change these lines it will work</p>
<pre><code> primer_needed = float(primer_area + result - door_area - window_area) / 200
primer_needed = float(primer_area + result - door_area - window_area) / 200
</code></pre>
<p>or you can determine the result to be float like</p>
<pre><code>x = float
</code><... | -2 | 2016-09-22T18:05:55Z | [
"python",
"python-3.x"
] |
Python: How do I create effects that apply to variables in classes? | 39,645,707 | <p>I am working on a text-based RPG, and I am trying to create magic spells that affect stats such as base attack, turn order, etc. I am using various classes for the spells in the format:</p>
<pre><code>class BuffSpell(object):
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
</code></pre>
<p>a... | 1 | 2016-09-22T17:49:19Z | 39,646,091 | <p>Use <code>getattr</code> and <code>setattr</code>, and make the attribute reference in the spell a <code>str</code>:</p>
<pre><code>bardSpells = {
1: BuffSpell(name= "Flare", level= 0, stat="baseAttack", value -1)
}
def useBuffSpell(target, spell):
setattr(target, spell.stat,
getattr(target, sp... | 0 | 2016-09-22T18:12:35Z | [
"python",
"class",
"methods"
] |
Open a csv.gz file in Python and print first 100 rows | 39,645,804 | <p>I'm trying to get only the first 100 rows of a csv.gz file that has over 4 million rows in Python. I also want information on the # of columns and the headers of each. How can I do this? </p>
<p>I looked at <a href="http://stackoverflow.com/questions/10566558/python-read-lines-from-compressed-text-files">python: re... | 2 | 2016-09-22T17:55:39Z | 39,645,923 | <p>I think you could do something like this (from the gzip module <a href="https://docs.python.org/3/library/gzip.html#examples-of-usage" rel="nofollow">examples</a>)</p>
<pre><code>import gzip
with gzip.open('/home/joe/file.txt.gz', 'rb') as f:
header = f.readline()
# Read lines any way you want now.
</code>... | 0 | 2016-09-22T18:02:50Z | [
"python",
"csv"
] |
Open a csv.gz file in Python and print first 100 rows | 39,645,804 | <p>I'm trying to get only the first 100 rows of a csv.gz file that has over 4 million rows in Python. I also want information on the # of columns and the headers of each. How can I do this? </p>
<p>I looked at <a href="http://stackoverflow.com/questions/10566558/python-read-lines-from-compressed-text-files">python: re... | 2 | 2016-09-22T17:55:39Z | 39,645,994 | <p>The first answer you linked suggests using <a href="https://docs.python.org/3/library/gzip.html#gzip.GzipFile" rel="nofollow"><code>gzip.GzipFile</code></a> - this gives you a file-like object that decompresses for you on the fly.</p>
<p>Now you just need some way to parse csv data out of a file-like object ... lik... | 1 | 2016-09-22T18:06:50Z | [
"python",
"csv"
] |
Open a csv.gz file in Python and print first 100 rows | 39,645,804 | <p>I'm trying to get only the first 100 rows of a csv.gz file that has over 4 million rows in Python. I also want information on the # of columns and the headers of each. How can I do this? </p>
<p>I looked at <a href="http://stackoverflow.com/questions/10566558/python-read-lines-from-compressed-text-files">python: re... | 2 | 2016-09-22T17:55:39Z | 39,646,258 | <p>Your code is OK;</p>
<p>pandas <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow">read_csv</a></p>
<blockquote>
<p><strong>warn_bad_lines</strong> : boolean, default True </p>
<pre><code>If error_bad_lines is False, and warn_bad_lines is True,
a warning for each... | 1 | 2016-09-22T18:21:59Z | [
"python",
"csv"
] |
Open a csv.gz file in Python and print first 100 rows | 39,645,804 | <p>I'm trying to get only the first 100 rows of a csv.gz file that has over 4 million rows in Python. I also want information on the # of columns and the headers of each. How can I do this? </p>
<p>I looked at <a href="http://stackoverflow.com/questions/10566558/python-read-lines-from-compressed-text-files">python: re... | 2 | 2016-09-22T17:55:39Z | 39,646,318 | <p>Pretty much what you've already done, except <code>read_csv</code> also has <code>nrows</code> where you can specify the number of columns you want from the data set.</p>
<p>Additionally, to prevent the errors you were getting, you can set <code>error_bad_lines</code> to <code>False</code>. You'll still get warning... | 1 | 2016-09-22T18:25:14Z | [
"python",
"csv"
] |
boolean indexing in xarray | 39,645,853 | <p>I have some arrays with dims <code>'time', 'lat', 'lon'</code> and some with just <code>'lat', 'lon'</code>. I often have to do this in order to mask time-dependent data with a 2d (lat-lon) mask:</p>
<pre><code>x.data[:, mask.data] = np.nan
</code></pre>
<p>Of course, computations broadcast as expected. If <code>y... | 0 | 2016-09-22T17:58:47Z | 39,665,384 | <p>Somewhat related question here: <a href="http://stackoverflow.com/questions/38884283/concise-way-to-filter-data-in-xarray">Concise way to filter data in xarray</a></p>
<p>Currently the best approach is a combination of <code>.where</code> and <code>.fillna</code>. </p>
<pre><code>valid = date_by_items.notnull()
po... | 2 | 2016-09-23T16:20:54Z | [
"python",
"numpy",
"python-xarray"
] |
Can I prevent the Cmd dialogue from popping up when using SymPy preview? | 39,645,899 | <p>I have written some code in Python 2.7 that will read a string from a .ini file and generate a .png image of the string in LaTeX format using <code>sympy.preview</code>. The idea is to use this script to generate the images in the background while I am typing them out. The problem is that even when I run the script ... | 0 | 2016-09-22T18:01:06Z | 39,649,148 | <p>I solved my own problem. If I ran the Python script from a previously-existing cmd instance, the windows didn't pop up. My solution then was to start a hidden instance of cmd and send the path location to the hidden cmd window. This enabled the Python code to be executed without the annoying popups from <code>latex.... | 1 | 2016-09-22T21:27:54Z | [
"python",
"latex",
"command-prompt",
"sympy"
] |
Printing formatted floats in nested tuple of mixed type | 39,645,950 | <p>I have a list of tuples where the entries in the tuples are mixed type (int, float, tuple) and want to print each element of the list on one line. </p>
<p>Example list:</p>
<pre><code> [('520',
(0.26699505214910974, 9.530913611077067e-22, 1431,
(0.21819421133984918, 0.31446394340528838), 11981481)),
('1... | 1 | 2016-09-22T18:04:24Z | 39,656,204 | <p>This is not exactly what you need, but very close, and the code is pretty compact.</p>
<pre><code>def truncateFloat(data):
return tuple( ["{0:.4}".format(x) if isinstance(x,float) else (x if not isinstance(x,tuple) else truncateFloat(x)) for x in data])
pprint(truncateFloat(the_list))
</code></pre>
<p>For your... | 1 | 2016-09-23T08:29:49Z | [
"python",
"pretty-print",
"pprint"
] |
Zapier Python Code Error Segment.com (usercode.py, line 9) | 39,645,963 | <p>I'm trying to take Campaign Monitor Open events and pipe the data to Segment.com via POST API using Python code Action on Zapier.</p>
<p>I keep getting the following <strong>error</strong>:</p>
<blockquote>
<p>Bargle. We hit an error creating a run python. :-( Error:
Your code had an error! Traceback (most re... | 1 | 2016-09-22T18:05:04Z | 39,646,072 | <p>Doing this:</p>
<pre><code>payload =
{}
</code></pre>
<p>Is improper syntax. Try:</p>
<pre><code>payload = {}
</code></pre>
<p>I also recommend using a linter - maybe <a href="http://infoheap.com/python-lint-online/" rel="nofollow">http://infoheap.com/python-lint-online/</a> would be helpful to you!</p>
| 0 | 2016-09-22T18:11:16Z | [
"python",
"zapier",
"segment-io"
] |
Zapier Python Code Error Segment.com (usercode.py, line 9) | 39,645,963 | <p>I'm trying to take Campaign Monitor Open events and pipe the data to Segment.com via POST API using Python code Action on Zapier.</p>
<p>I keep getting the following <strong>error</strong>:</p>
<blockquote>
<p>Bargle. We hit an error creating a run python. :-( Error:
Your code had an error! Traceback (most re... | 1 | 2016-09-22T18:05:04Z | 39,646,724 | <p>Thanks to @Bryan Helmig. That syntax, in addition to import json fixed the issue. For those interested, this works...</p>
<pre><code>import json
import requests
url = 'https://api.segment.io/v1/track/'
payload = {
'userId': input_data['email'],
'event': 'Email Opened',
'properties': {
'listid': input_data... | 0 | 2016-09-22T18:47:07Z | [
"python",
"zapier",
"segment-io"
] |
Best way to combine datetime in pandas dataframe when times are close | 39,645,972 | <p>What is the best way to combine times together if they are very close (within 5 seconds).</p>
<pre><code> start end delta
0 2016-01-01 08:00:01 2016-01-01 08:07:53 472.0
1 2016-01-01 08:07:54 2016-01-01 08:09:23 89.0
2 2016-01-01 08:09:24 2016-01-01 08:32:51 1407.0... | 0 | 2016-09-22T18:05:38Z | 39,647,024 | <p>Try this:</p>
<pre><code>timediff = df.start.diff()/np.timedelta64(1, 's')
pd.DataFrame(
{'start': df[(timediff>5) | (timediff.isnull())].start.tolist(),
'end': df[(timediff.shift(-1)>5) | (timediff.shift(-1).isnull())].end.tolist()}
)
</code></pre>
<p>This will give you start and end columns. ... | 0 | 2016-09-22T19:04:36Z | [
"python",
"pandas",
"numpy"
] |
Need help writing code that will automatically write more code? | 39,646,016 | <p>I need help with writing code for a work project. I have written a script that uses pandas to read an excel file. I have a while-loop written to iterate through each row and append latitude/longitude data from the excel file onto a map (Folium, Open Street Map)</p>
<p>The issue I've run into has to do with the GPS ... | 0 | 2016-09-22T18:07:54Z | 39,647,308 | <p>Your while loop looks wonky. You only set j once, outside the loop. Also, I think you want a list of line segments. Did you want something like this;</p>
<pre><code>i = 0
segment = 0
locations = []
while i < len(lat):
locations[segment] = [] # start a new segment
# add points to the current segment u... | 0 | 2016-09-22T19:22:46Z | [
"python",
"automation",
"openstreetmap",
"folium"
] |
How to stop `colorbar` from reshaping `networkx` plot? (Python 3) | 39,646,027 | <p>I am trying to change the <code>colorbar</code> on my <code>networkx</code> plot. The bar gets extra wide and also smooshes my original <code>networkx</code> plot (left) when I add the <code>colorbar</code> on there (right). </p>
<p><strong>How can I make my <code>colorbar</code> thinner and not alter my original ... | 0 | 2016-09-22T18:08:30Z | 39,646,338 | <p>Easiest way should be to plot the colorbar on its own axis and play around with the [left, bottom, width, height] parameters.</p>
<pre><code>cbaxes = fig.add_axes([0.9, 0.1, 0.015, 0.8])
sm = plt.cm.ScalarMappable(cmap=ListedColormap(color_palette),
norm=plt.Normalize(vmin=0, vmax=3))
sm.... | 2 | 2016-09-22T18:26:23Z | [
"python",
"matplotlib",
"colors",
"networkx",
"colorbar"
] |
Sublime3 text can't ignore PEP8 formatting for Python | 39,646,060 | <p>I installed Sublime for Python programming but I found that PEP8 error detection is pretty annoying and I couldn't get rid of it.</p>
<p>I tried this but it's not working:</p>
<p><a href="http://i.stack.imgur.com/119l5.png" rel="nofollow"><img src="http://i.stack.imgur.com/119l5.png" alt="enter image description h... | -1 | 2016-09-22T18:10:29Z | 39,646,370 | <p>Try to add <code>"pep8": false,</code>. </p>
<p>If it does not work, add <code>"sublimelinter_disable":["python"],</code> to disable python's inspections completely. </p>
<p>And you would like to look <a href="https://github.com/SublimeLinter/SublimeLinter-pep8" rel="nofollow">https://github.com/SublimeLinter/Sub... | 0 | 2016-09-22T18:28:11Z | [
"python",
"sublimetext",
"pep8"
] |
pandas histogram: plot histogram for each column as subplot of a big figure | 39,646,070 | <p>I am using the following code, trying to plot the histogram of every column of a my pandas data frame df_in as subplot of a big figure.</p>
<pre><code>%matplotlib notebook
from itertools import combinations
import matplotlib.pyplot as plt
fig, axes = plt.subplots(len(df_in.columns) // 3, 3, figsize=(12, 48))
for x... | 0 | 2016-09-22T18:11:05Z | 39,646,226 | <p>You need to specify which axis you are plotting to. This should work:</p>
<pre><code>fig, axes = plt.subplots(len(df_in.columns)//3, 3, figsize=(12, 48))
for col, axis in zip(df_in.columns, axes):
df_in.hist(column = col, bins = 100, ax=axis)
</code></pre>
| 0 | 2016-09-22T18:20:15Z | [
"python",
"pandas",
"histogram"
] |
How to read a .py file after I install Anaconda? | 39,646,077 | <p>I have installed <code>Anaconda</code>, but I do not know how to open a <code>.py</code> file..</p>
<p>If it is possible, please explain plainly, I browsed several threads, but I understood none of them..</p>
<p>Thanks a lot for your helps..</p>
<p>Best,</p>
| -2 | 2016-09-22T18:11:26Z | 39,646,217 | <p>You can use any text editor to open a .py file, e.g. TextMate, TextWrangler, TextEdit, PyCharm, AquaMacs, etc.</p>
| 0 | 2016-09-22T18:19:31Z | [
"python",
"anaconda"
] |
How to read a .py file after I install Anaconda? | 39,646,077 | <p>I have installed <code>Anaconda</code>, but I do not know how to open a <code>.py</code> file..</p>
<p>If it is possible, please explain plainly, I browsed several threads, but I understood none of them..</p>
<p>Thanks a lot for your helps..</p>
<p>Best,</p>
| -2 | 2016-09-22T18:11:26Z | 39,646,328 | <p>In the menu structure of your operating system, you should see a folder for Anaconda. In that folder is an icon for Spyder. Click that icon.</p>
<p>After a while (Spyder loads slowly) you will see the Spyder integrated environment. You can choose File then Open from the menu, or just click the Open icon that looks ... | 0 | 2016-09-22T18:25:38Z | [
"python",
"anaconda"
] |
Bundling C++ extension headers with a Python package source distribution | 39,646,097 | <p>I'm writing a Cython wrapper to a C++ library that I would like to distribute as a Python package. I've come up with a dummy version of my package that looks like this (full source <a href="https://github.com/standage/packagetest" rel="nofollow">here</a>).</p>
<pre><code>$ tree
.
âââ bogus.pyx
âââ inc
â... | 4 | 2016-09-22T18:13:08Z | 39,735,501 | <h2>Short answer</h2>
<p>Put <code>include inc/*.hpp</code> in the <code>MANIFEST.in</code> file.</p>
<h2>Long answer</h2>
<p>Based on various blog posts and SO threads, I had tried the suggestion of declaring the files in a <code>MANIFEST.in</code> file. Following <a href="https://docs.python.org/2/distutils/source... | 1 | 2016-09-27T22:47:31Z | [
"python",
"packaging",
"python-extensions",
"python-packaging"
] |
Looking up Pandas dataFrame | 39,646,134 | <p>I have created a data frame by reading a text file. I am interested in knowing if few values exist in a particular column and if they do, I want to print the entire row. </p>
<p>This is my input file(analyte_map.txt):</p>
<pre><code>Analyte_id mass Intensity
A34579 101.2 786788
B12345 99.... | 1 | 2016-09-22T18:15:12Z | 39,646,164 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing"><code>boolean indexing</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.isin.html"><code>isin</code></a>:</p>
<pre><code>array=['A34579','B943470','D583730']
print (df[df.anal... | 5 | 2016-09-22T18:17:01Z | [
"python",
"pandas",
"indexing",
"dataframe",
"condition"
] |
Looking up Pandas dataFrame | 39,646,134 | <p>I have created a data frame by reading a text file. I am interested in knowing if few values exist in a particular column and if they do, I want to print the entire row. </p>
<p>This is my input file(analyte_map.txt):</p>
<pre><code>Analyte_id mass Intensity
A34579 101.2 786788
B12345 99.... | 1 | 2016-09-22T18:15:12Z | 39,646,265 | <p>using <code>.query()</code> method:</p>
<pre><code>In [9]: look_up=['A34579','B943470','D583730']
In [10]: df.query('Analyte_id in @look_up')
Out[10]:
Analyte_id mass Intensity
0 A34579 101.20 786788
2 B943470 103.89 986443
In [11]: df.query('Analyte_id in @look_up')[['mass','Intensity']]
O... | 2 | 2016-09-22T18:22:08Z | [
"python",
"pandas",
"indexing",
"dataframe",
"condition"
] |
Python 2.7 BeautifulSoup, website addresses scraping | 39,646,144 | <p>Hope you are all well. I'm new in Python and using python 2.7. </p>
<p>I'm trying to extract only the websites from this public website business directory: <a href="https://www.dmcc.ae/business-directory" rel="nofollow">https://www.dmcc.ae/business-directory</a><br>
the websites i'm looking for are the websites me... | 1 | 2016-09-22T18:15:47Z | 39,646,378 | <p>As somebody has written into comments:</p>
<p>The web page is build by client using JavaScript. What your Python script gets is only a (relatively) short HTML website, that loads other scripts to load the right data. Unfortunately, BeautifulSoup can't execute the website so let it load all of its resources and then... | -1 | 2016-09-22T18:28:27Z | [
"python",
"python-2.7",
"web-scraping",
"beautifulsoup"
] |
Python 2.7 BeautifulSoup, website addresses scraping | 39,646,144 | <p>Hope you are all well. I'm new in Python and using python 2.7. </p>
<p>I'm trying to extract only the websites from this public website business directory: <a href="https://www.dmcc.ae/business-directory" rel="nofollow">https://www.dmcc.ae/business-directory</a><br>
the websites i'm looking for are the websites me... | 1 | 2016-09-22T18:15:47Z | 39,646,593 | <p>The data is dynamically generate using Jquery though an ajax request, you can do a get request to the url to get the dynamically loaded data:</p>
<pre><code>from requests import Session
from time import time
data = {
"page_num": "1", # set it to whatever page you like
"query_type": "activities",
... | 2 | 2016-09-22T18:40:40Z | [
"python",
"python-2.7",
"web-scraping",
"beautifulsoup"
] |
Why does logging not work when running a Flask app with werkzeug? | 39,646,236 | <p>So here is a copy paste example that reproduces the problem.</p>
<pre><code>import logging
from flask import Flask
from werkzeug.serving import run_simple
from werkzeug.wsgi import DispatcherMiddleware
def app_builder(app_name, log_file):
app = Flask(app_name)
app.debug = True
handler = logging.File... | 4 | 2016-09-22T18:20:56Z | 39,701,542 | <p>I found a <a href="https://gist.github.com/ibeex/3257877" rel="nofollow">gist</a> which talks about logging in flask. The comment by andyxning (commented on Apr 18, 2015) mentions this - <code>if app.debug is True then all log level above DEBUG will be logged to stderr(StreamHandler)</code>. </p>
<p>The comment als... | 1 | 2016-09-26T11:23:56Z | [
"python",
"flask",
"wsgi",
"werkzeug"
] |
Why does logging not work when running a Flask app with werkzeug? | 39,646,236 | <p>So here is a copy paste example that reproduces the problem.</p>
<pre><code>import logging
from flask import Flask
from werkzeug.serving import run_simple
from werkzeug.wsgi import DispatcherMiddleware
def app_builder(app_name, log_file):
app = Flask(app_name)
app.debug = True
handler = logging.File... | 4 | 2016-09-22T18:20:56Z | 39,701,662 | <p>The normal exception handler is not called when <code>app.debug = True</code>. Looking
in the code of <code>app.py</code> in Flask:</p>
<pre><code>def log_exception(self, exc_info):
"""Logs an exception. This is called by :meth:`handle_exception`
if debugging is disabled and right before the handler is cal... | 1 | 2016-09-26T11:30:05Z | [
"python",
"flask",
"wsgi",
"werkzeug"
] |
Adding column from one CSV file to another CSV file | 39,646,296 | <p>I have 2 CSV files that I need to merge together based on a key i created ( the purpose was to mask ID's then join the ids on the key later ) I can do this in SSIS, but im have an error runing the batch script from my python script (something to do with SSIS not running packages outside SSIS. Working with software t... | -2 | 2016-09-22T18:24:14Z | 39,649,263 | <pre><code>a = pd.read_csv("import.csv")
b = pd.read_csv("entity_ids.csv")
merge = a.merge(b, how='left', on='input_id')
merge.to_csv("test2.csv", index = False)
</code></pre>
| -1 | 2016-09-22T21:36:10Z | [
"python",
"csv",
"ssis"
] |
Pandas DataFrame slicing based on logical conditions? | 39,646,300 | <p>I have this dataframe called data:</p>
<pre><code> Subjects Professor StudentID
8 Chemistry Jane 999
1 Chemistry Jane 3455
0 Chemistry Joseph 1234
2 History Jane 3455
6 History Smith 323
7 History Smith 999
... | 1 | 2016-09-22T18:24:31Z | 39,647,126 | <pre><code>students_and_subjects = df.groupby(
['Professor', 'Subjects']
).StudentID.nunique().ge(2) \
.groupby(level='Professor').sum().ge(2)
df[df.Professor.map(students_and_subjects)]
</code></pre>
<p><a href="http://i.stack.imgur.... | 2 | 2016-09-22T19:10:40Z | [
"python",
"mysql",
"pandas"
] |
Pandas DataFrame slicing based on logical conditions? | 39,646,300 | <p>I have this dataframe called data:</p>
<pre><code> Subjects Professor StudentID
8 Chemistry Jane 999
1 Chemistry Jane 3455
0 Chemistry Joseph 1234
2 History Jane 3455
6 History Smith 323
7 History Smith 999
... | 1 | 2016-09-22T18:24:31Z | 39,653,653 | <p>Solution with <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html#filtration" rel="nofollow"><code>filter</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.value_counts.html" rel="nofollow"><code>value_counts</code></a>:</p>
<pre><code>df1 = df.groupby('Profes... | 1 | 2016-09-23T06:05:50Z | [
"python",
"mysql",
"pandas"
] |
Convert string type array to array | 39,646,400 | <p>I have this:</p>
<pre><code>[s[8] = 5,
s[4] = 3,
s[19] = 2,
s[17] = 8,
s[16] = 8,
s[2] = 8,
s[9] = 7,
s[1] = 2,
s[3] = 9,
s[15] = 7,
s[11] = 0,
s[10] = 9,
s[12] = 3,
s[18] = 1,
s[0] = 4,
s[14] = 5,
s[7] = 4,
s[6] = 2,
s[5] = 7,
s[13] = 9]
</code></pre>
<p>How can I turn this ... | 0 | 2016-09-22T18:29:42Z | 39,646,730 | <pre><code>import re
data = """[s[8] = 5,
s[4] = 3,
s[19] = 2,
s[17] = 8,
s[16] = 8,
s[2] = 8,
s[9] = 7,
s[1] = 2,
s[3] = 9,
s[15] = 7,
s[11] = 0,
s[10] = 9,
s[12] = 3,
s[18] = 1,
s[0] = 4,
s[14] = 5,
s[7] = 4,
s[6] = 2,
s[5] = 7,
s[13] = 9]"""
d = {int(m.group(1)): int(m.group(2... | 4 | 2016-09-22T18:47:29Z | [
"python",
"python-2.7"
] |
Convert string type array to array | 39,646,400 | <p>I have this:</p>
<pre><code>[s[8] = 5,
s[4] = 3,
s[19] = 2,
s[17] = 8,
s[16] = 8,
s[2] = 8,
s[9] = 7,
s[1] = 2,
s[3] = 9,
s[15] = 7,
s[11] = 0,
s[10] = 9,
s[12] = 3,
s[18] = 1,
s[0] = 4,
s[14] = 5,
s[7] = 4,
s[6] = 2,
s[5] = 7,
s[13] = 9]
</code></pre>
<p>How can I turn this ... | 0 | 2016-09-22T18:29:42Z | 39,646,814 | <p>Assuming this is one giant string, if you want <code>print s[0]</code> to print <code>4</code>, then you need to split this up by the commas, then iterate through each item.</p>
<pre><code>inputArray = yourInput[1:-1].replace(' ','').split(',\n\n')
endArray = [0]*20
for item in inputArray:
endArray[int(item[ite... | 1 | 2016-09-22T18:51:37Z | [
"python",
"python-2.7"
] |
Convert string type array to array | 39,646,400 | <p>I have this:</p>
<pre><code>[s[8] = 5,
s[4] = 3,
s[19] = 2,
s[17] = 8,
s[16] = 8,
s[2] = 8,
s[9] = 7,
s[1] = 2,
s[3] = 9,
s[15] = 7,
s[11] = 0,
s[10] = 9,
s[12] = 3,
s[18] = 1,
s[0] = 4,
s[14] = 5,
s[7] = 4,
s[6] = 2,
s[5] = 7,
s[13] = 9]
</code></pre>
<p>How can I turn this ... | 0 | 2016-09-22T18:29:42Z | 39,646,873 | <p>An easy way, although less efficient than Kevin's solution (without using regular expressions), would be the following (where <code>some_array</code> is your string):</p>
<pre><code>sub_list = some_array.split(',')
some_dict = {}
for item in sub_list:
sanitized_item = item.strip().rstrip().lstrip().replace('='... | 0 | 2016-09-22T18:55:09Z | [
"python",
"python-2.7"
] |
Convert string type array to array | 39,646,400 | <p>I have this:</p>
<pre><code>[s[8] = 5,
s[4] = 3,
s[19] = 2,
s[17] = 8,
s[16] = 8,
s[2] = 8,
s[9] = 7,
s[1] = 2,
s[3] = 9,
s[15] = 7,
s[11] = 0,
s[10] = 9,
s[12] = 3,
s[18] = 1,
s[0] = 4,
s[14] = 5,
s[7] = 4,
s[6] = 2,
s[5] = 7,
s[13] = 9]
</code></pre>
<p>How can I turn this ... | 0 | 2016-09-22T18:29:42Z | 39,647,086 | <p>If you want the array to have the same name that is in the input string, you could use exec. This is not very pythonic, but it works for simple stuff</p>
<pre><code>string = ("[s[8] = 5, s[4] = 3, s[19] = 2,"
"s[17] = 8, s[16] = 8, s[2] = 8,"
"s[9] = 7, s[1] = 2, s[3] = 9,"
"s[15] = 7, s[11] = 0, s[10] =... | 2 | 2016-09-22T19:08:29Z | [
"python",
"python-2.7"
] |
How to merge the elements in a list sequentially in python | 39,646,401 | <p>I have a list <code>[ 'a' , 'b' , 'c' , 'd']</code>. How do I get the list which joins two letters sequentially i.e the ouptut should be <code>[ 'ab', 'bc' , 'cd']</code> in python easily instead of manually looping and joining</p>
| 3 | 2016-09-22T18:29:43Z | 39,646,555 | <p>Use <code>zip</code> within a list comprehension:</p>
<pre><code>In [13]: ["".join(seq) for seq in zip(lst, lst[1:])]
Out[13]: ['ab', 'bc', 'cd']
</code></pre>
<p>Or since you just want to concatenate two character you can also use <code>add</code> operator, by using <a href="https://docs.python.org/3/library/iter... | 4 | 2016-09-22T18:38:54Z | [
"python",
"python-2.7"
] |
How to merge the elements in a list sequentially in python | 39,646,401 | <p>I have a list <code>[ 'a' , 'b' , 'c' , 'd']</code>. How do I get the list which joins two letters sequentially i.e the ouptut should be <code>[ 'ab', 'bc' , 'cd']</code> in python easily instead of manually looping and joining</p>
| 3 | 2016-09-22T18:29:43Z | 39,646,594 | <p>Just one line of code is enough :</p>
<pre><code>a = ['a','b','c','d']
output = [a[i] + a[i+1] for i in xrange(len(a)) if i < len(a)-1]
print output
</code></pre>
| 0 | 2016-09-22T18:40:49Z | [
"python",
"python-2.7"
] |
How to make a function loop through multiple dictionaries in Python | 39,646,403 | <p>I am looking to create a function in Python that will move between multiple dictionaries that are within a class. There will be several dictionaries that the user will go through in order, and I want the function to be able to go through each one and select a random pair from the dictionary. The user will then submi... | 1 | 2016-09-22T18:29:44Z | 39,646,510 | <p>Well, if you've got a list of dictionaries in the class, something like:</p>
<pre><code>import random
for d in dict_list:
random_pair = random.choice(d.items())
# Then do whatever you were going to do with that pair
# then it goes on to the next dictionary in the list
</code></pre>
<p>If you don't alre... | 4 | 2016-09-22T18:36:19Z | [
"python",
"dictionary"
] |
Python Requests vs Curl Requests on Mac Terminal to Fetch Code Content via Github API | 39,646,573 | <p>I want to get the decrypted content of a code file in a Jquery project on Github. If I do curl request, the returned code content is decrypted. </p>
<p>But using the same parameter on Python requests, the encrypted exists. Why is that and what can I do to get the decrypted version? </p>
<p>Here's my curl command:<... | 0 | 2016-09-22T18:39:42Z | 39,646,624 | <pre><code>>>> import base64
>>> base64.b64decode('PD9waHAKCSMgTG9hZCBhbmQgcnVuIHRoZSB0ZXN0IHN1aXRlIGFzIGEgcH
Jv\ncGVyIFhIVE1MIHBhZ2UKCWhlYWRlcigiQ29udGVudC10eXBlOiBhcHBsaWNh\ndGlvbi94aHRtbC
t4bWwiKTsKCXJlYWRmaWxlKCJpbmRleC5odG1sIik7Cj8+\nCg==')
'<?php\n\t# Load and run the test suite as a proper X... | 2 | 2016-09-22T18:42:41Z | [
"python",
"curl",
"github"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.