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 |
|---|---|---|---|---|---|---|---|---|---|
Time Inaccuracy or Inefficient Code? | 39,842,201 | <p>I'm currently working on a program that will display the amount of time that has passed since a specific point. A stopwatch, if you will.</p>
<p>I've finally gotten my code working, but as it turns out, it's not very accurate. It falls behind very quickly, being 1 or even 2 seconds off within just the first 10 seco... | 1 | 2016-10-03T23:54:04Z | 39,842,416 | <p>Well as it turns out the solution was as simple as changing from <code>time.clock()</code> to <code>time.time()</code> as suggested by <em>tdelaney</em>. </p>
<p>Looks like I need to more thoroughly read up on modules as I use them. Thanks for the wisdom.</p>
| 2 | 2016-10-04T00:24:01Z | [
"python",
"datetime",
"time",
"stopwatch"
] |
Bundling application and dependencies with pynsist | 39,842,237 | <p>I'm a python newbie so please bear with me.</p>
<p>I'm trying to bundle a PyQt4 application with pynsist. I want to import module A which depends on module B, C, and D, but specifying module A in the installer.cfg file does not bundle B, C, and D. Do I need to specify <strong>ALL</strong> the modules my application... | 0 | 2016-10-03T23:59:42Z | 40,087,914 | <p>You need to specify all of the modules or packages to be bundled.</p>
<p>If these are modules you are writing yourself, you can put them all in one package, so you import them as <code>import mypkg.A</code> or <code>import mypkg.B</code>. Then you can ask it to bundle <code>mypkg</code> as a whole.</p>
<p>You can ... | 0 | 2016-10-17T13:37:11Z | [
"python",
"python-packaging",
"pynsist"
] |
Go exec external python script and get the returned output | 39,842,242 | <p>In my Go file i use exec to run the external script:</p>
<pre><code>cmd := exec.Command("test.py")
out, err := cmd.CombinedOutput()
if err != nil {
fmt.Println(err)
}
fmt.Println(string(out))
</code></pre>
<p>The python script it's executed fine, but the go <code>fmt.Println(string(out))</code> prints nothing.... | -2 | 2016-10-04T00:00:10Z | 39,842,421 | <p>I think i found the bug, you need to put the full path to "test.py"</p>
<p><strong>Test</strong></p>
<p>I have two files in a directory:
test.py
test.go</p>
<p>The <code>test.py</code> is:</p>
<pre><code>#!/usr/bin/env python3
print("Hello from python")
</code></pre>
<p>and <code>test.go</code> is:</p>... | 0 | 2016-10-04T00:24:37Z | [
"python",
"go"
] |
Traversing subfolder files? | 39,842,253 | <p>I have wrote a script to erase a given word from docx files and am at my last hurdle of it checking subfolder items as well. Can someone help me in figuring out where I am failing in my execution. It works with all the files within the same directory but it won't also check subfolder items right now. Thanks for your... | 3 | 2016-10-04T00:00:54Z | 39,842,733 | <p><a href="https://docs.python.org/3/library/os.html#os.walk" rel="nofollow">os.walk</a> iterates through subdirectories yielding a 3-tuple <code>(dirpath, dirnames, filenames)</code> for each subdirectory visited. When you do:</p>
<pre><code>for dirs, folders, files in os.walk('.'):
for subDirs in dirs:
</code><... | 3 | 2016-10-04T01:06:02Z | [
"python",
"python-3.x"
] |
Python Pillow: Add transparent gradient to an image | 39,842,286 | <p>I need to add transparent gradient to an image like on the image below , I tried this:</p>
<pre><code>def test(path):
im = Image.open(path)
if im.mode != 'RGBA':
im = im.convert('RGBA')
width, height = im.size
gradient = Image.new('L', (width, 1), color=0xFF)
for x in range(width):
... | 1 | 2016-10-04T00:06:48Z | 39,857,434 | <p>Your code actually does what it says it does. However, if your image background is not black but white, then the image will appear lighter. The following code merges the original image with a black image, such that you have the dark gradient effect irrespective of background.</p>
<pre><code>def test(path):
im =... | 1 | 2016-10-04T16:28:23Z | [
"python",
"python-imaging-library",
"pillow"
] |
Dataframe groupby.apply with multiple arguments pandas python | 39,842,329 | <p>I have a dataframe like the one below and i'm trying to calculate the distance between two points in multiple gps trips using a haversine formula that has 4 inputs. So basically grouping on trip_id and applying the haversine formula. </p>
<p>I had thought something like <code>df['distance'] = df.groupby('trip_id').... | 0 | 2016-10-04T00:11:55Z | 39,842,388 | <p>I would use numpy vectorize method such has</p>
<pre><code>import numpy as np
np.vectorize(haversine)(df.lng, df.lat, df.lnglag_, df.latlag_)
</code></pre>
| 0 | 2016-10-04T00:20:29Z | [
"python",
"pandas"
] |
Python: function to alter a global variable that is also parameter | 39,842,332 | <pre><code>def fxn(L):
"""
"""
global L = 2
L = 1
fxn(L)
print(L)
</code></pre>
<p>I have a function like the one above. Assume I need the function to alter the global variable from within the function so that when I print L after calling fxn(L). I end up with the 2 rather than 1. </p>
<p>Is there any w... | 0 | 2016-10-04T00:12:05Z | 39,842,415 | <p>You should not use the same variable as global variable and the functional argument to the function using that global variable. </p>
<p>But since you have asked, you can do it using the <a href="https://docs.python.org/2/library/functions.html#globals" rel="nofollow"><code>globals()</code></a> and <a href="https://... | 0 | 2016-10-04T00:24:00Z | [
"python",
"function",
"global"
] |
Python: function to alter a global variable that is also parameter | 39,842,332 | <pre><code>def fxn(L):
"""
"""
global L = 2
L = 1
fxn(L)
print(L)
</code></pre>
<p>I have a function like the one above. Assume I need the function to alter the global variable from within the function so that when I print L after calling fxn(L). I end up with the 2 rather than 1. </p>
<p>Is there any w... | 0 | 2016-10-04T00:12:05Z | 39,842,503 | <p>This is a bad idea, but there are ways, for example:</p>
<pre><code>a = 5
def f(a):
def change_a(value):
global a
a = value
change_a(7)
f(0)
print(a) # prints 7
</code></pre>
<p>In reality, there is seldom any need for writing to global variables. And then there is little chance that t... | 0 | 2016-10-04T00:34:27Z | [
"python",
"function",
"global"
] |
Django - Simple search form | 39,842,386 | <p>Using Django 1.9 with Python 3.5, I would like to make a simple search form:</p>
<p><strong>views.py</strong> </p>
<pre><code>from django.views import generic
from django.shortcuts import render
from .models import Movie, Genre
class IndexView(generic.ListView):
template_name = 'movies/index.html'
page_te... | 2 | 2016-10-04T00:20:20Z | 39,842,412 | <p>That error does not come from your template as you seem to think. It comes from your view </p>
<pre><code>def get_queryset(self):
query = request.GET.get('q')
</code></pre>
<p>It should be</p>
<pre><code> query = self.request.GET.get('q')
</code></pre>
| 1 | 2016-10-04T00:23:36Z | [
"python",
"django"
] |
How does one use the VSCode debugger to debug a Gunicorn worker process? | 39,842,422 | <p>I have a GUnicorn/Falcon web service written in Python 3.4 on Ubuntu 14.04. I'd like to use the VSCode debugger to debug this service. I currently start the process with the command </p>
<pre><code>/usr/local/bin/gunicorn --config /webapps/connects/routerservice_config.py routerservice:api
</code></pre>
<p>which s... | 0 | 2016-10-04T00:25:00Z | 39,848,241 | <p>I'm the author of the extension.
You could try the following:
<a href="https://github.com/DonJayamanne/pythonVSCode/wiki/Debugging:-Remote-Debuging" rel="nofollow">https://github.com/DonJayamanne/pythonVSCode/wiki/Debugging:-Remote-Debuging</a></p>
<ul>
<li>Add the following code into your routerservice_config.py (... | 1 | 2016-10-04T09:03:04Z | [
"python",
"debugging",
"vscode",
"gunicorn"
] |
How to write a python function that ShellCommand, in the Lancent library, can execute? | 39,842,481 | <p><a href="https://github.com/ioam/lancet" rel="nofollow">Lancet</a> is a Python library to explore parameter spaces. It can launch jobs, organize the output, and dissect the results.</p>
<p>I'm having trouble getting the Quickstart example, in the documentation <a href="http://ioam.github.io/lancet/" rel="nofollow">... | -1 | 2016-10-04T00:31:35Z | 39,877,536 | <p>I copied the example code and did not remember to change the executable name to an absolute path for factor.py.</p>
<p>On my computer it should be:</p>
<pre><code>factor_cmd = lancet.ShellCommand(executable='/Users/klm/Devel/factor.py', posargs=['integer'])
</code></pre>
| 0 | 2016-10-05T15:01:57Z | [
"python"
] |
get index value from merged pandas time series? | 39,842,623 | <p>I have various time series pandas data frames which look like:</p>
<p>data['F_NQ'] = </p>
<p><code>OPEN HIGH LOW CLOSE VOL OI P R RINFO
DATE<br>
1996-04-10 12450 12494 12200 12275 2282 627 0 0 0
1996-04-11 12200 12360 12000 12195 1627 920 0 0 0</code></p>
<p>I... | 0 | 2016-10-04T00:49:51Z | 39,842,678 | <p>This helped me find the solution... <a href="http://stackoverflow.com/questions/18327624/find-elements-index-in-pandas-series">post</a></p>
<p>I basically need to call: <code>timeSlice.index[-1]</code> to get the last date from whichever time block I've selected.</p>
| 0 | 2016-10-04T00:57:31Z | [
"python",
"pandas",
"time-series"
] |
get index value from merged pandas time series? | 39,842,623 | <p>I have various time series pandas data frames which look like:</p>
<p>data['F_NQ'] = </p>
<p><code>OPEN HIGH LOW CLOSE VOL OI P R RINFO
DATE<br>
1996-04-10 12450 12494 12200 12275 2282 627 0 0 0
1996-04-11 12200 12360 12000 12195 1627 920 0 0 0</code></p>
<p>I... | 0 | 2016-10-04T00:49:51Z | 39,842,686 | <p>since <code>.iloc[n]</code> return a pandas series with the index has the name, you could get the name of that series doing this :</p>
<pre><code>date = timeSlice.iloc[n].name
</code></pre>
| 0 | 2016-10-04T00:58:43Z | [
"python",
"pandas",
"time-series"
] |
boolean expression doesn't match | 39,842,634 | <p>I having a simple issue which I don't seem to understand why,<code>force_edl</code> variable value is 'False" (its an option to my python script and user enters True or False)but the conditions <code>if force_edl == False:</code> and <code>if not force_edl</code> doesnt seem to match,how do I debug this p... | 0 | 2016-10-04T00:51:18Z | 39,842,734 | <p><strong>You cannot concatenate 'str' and 'bool'.</strong> So if this</p>
<pre><code>print "force_edl " + force_edl
</code></pre>
<p>is not giving you an error <em>then your force_edl is definitely not a bool.</em> </p>
<p>That's why <strong>your if prints True</strong>. </p>
<pre><code>force_edl = False
if for... | 0 | 2016-10-04T01:06:08Z | [
"python"
] |
boolean expression doesn't match | 39,842,634 | <p>I having a simple issue which I don't seem to understand why,<code>force_edl</code> variable value is 'False" (its an option to my python script and user enters True or False)but the conditions <code>if force_edl == False:</code> and <code>if not force_edl</code> doesnt seem to match,how do I debug this p... | 0 | 2016-10-04T00:51:18Z | 39,842,809 | <p>Try setting it to a string, int or boolean when needed. Right now your trying to use a boolean as a string which wont work.</p>
<pre><code>enter code here
force_edl = int(False)
print "force_edl " + str(force_edl)
if force_edl == False:
print "False"
else:
print "True"
</code></pre>
| 0 | 2016-10-04T01:17:48Z | [
"python"
] |
python How to call ob1.fun1.fun2 and handle ob1.fun1 as none? | 39,842,674 | <p>I tried to use the following code, but looks like ugly</p>
<pre><code>tmp = ob1.fun1
result = None
if tmp is not None:
global result
result = tmp.fun2
</code></pre>
<p>Is there a better way to do this?</p>
| 0 | 2016-10-04T00:56:57Z | 39,842,697 | <p>Use the <a href="http://stackoverflow.com/questions/11360858/what-is-the-eafp-principle-in-python">EAFP</a> (Easier to ask for forgiveness than permission) approach. Wrap it in a try/except and handle your exception accordingly: </p>
<pre><code>result = None
try:
result = ob1.fun1.fun2
except AttributeError:
... | 0 | 2016-10-04T00:59:47Z | [
"python"
] |
python How to call ob1.fun1.fun2 and handle ob1.fun1 as none? | 39,842,674 | <p>I tried to use the following code, but looks like ugly</p>
<pre><code>tmp = ob1.fun1
result = None
if tmp is not None:
global result
result = tmp.fun2
</code></pre>
<p>Is there a better way to do this?</p>
| 0 | 2016-10-04T00:56:57Z | 39,842,782 | <p>If you just want <code>result</code> to be <code>None</code> if <code>ob1.fun1</code> is <code>None</code> or if <code>fun2</code> doesn't exist as an attribute, you could use <a href="https://docs.python.org/3/library/functions.html#getattr" rel="nofollow"><code>getattr</code></a> and use <code>None</code> as a def... | 1 | 2016-10-04T01:13:00Z | [
"python"
] |
python How to call ob1.fun1.fun2 and handle ob1.fun1 as none? | 39,842,674 | <p>I tried to use the following code, but looks like ugly</p>
<pre><code>tmp = ob1.fun1
result = None
if tmp is not None:
global result
result = tmp.fun2
</code></pre>
<p>Is there a better way to do this?</p>
| 0 | 2016-10-04T00:56:57Z | 39,849,366 | <p>How about:</p>
<pre><code>if t.fun1 is not None:
result = t.fun1.fun2
else:
result = None
</code></pre>
| 0 | 2016-10-04T09:58:34Z | [
"python"
] |
How to have a Custom User model for my app while keeping the admins working as default in Django? | 39,842,758 | <p>Here is what I am trying to accomplish: <br/></p>
<p> - Have admins login to the admin page using the default way (username and password).</p>
<p> - Have users register/login to my web app using a custom User Model which uses email instead of password. They can also have other data associated that I don't need fo... | 3 | 2016-10-04T01:09:12Z | 39,843,275 | <p>After couple more hours of digging, I think it is best to keep a single User model and use permissions and roles for regulations. </p>
<p>There are ways that can make multiple different user model authentications work, such as describe in here: <a href="http://stackoverflow.com/questions/3206856/how-to-have-2-diffe... | 0 | 2016-10-04T02:30:01Z | [
"python",
"django"
] |
How to have a Custom User model for my app while keeping the admins working as default in Django? | 39,842,758 | <p>Here is what I am trying to accomplish: <br/></p>
<p> - Have admins login to the admin page using the default way (username and password).</p>
<p> - Have users register/login to my web app using a custom User Model which uses email instead of password. They can also have other data associated that I don't need fo... | 3 | 2016-10-04T01:09:12Z | 39,843,324 | <p>The recommended Django practice is to create a OneToOne field pointing to the User, rather than extending the User object - this way you build on top of Django's User by decorating only the needed new model properties (for example):</p>
<pre><code>class Profile(models.Model):
user = models.OneToOneField(User,pa... | 2 | 2016-10-04T02:36:34Z | [
"python",
"django"
] |
How can I print a webpage line by line in Python 3.x | 39,842,762 | <p>All I want to do is print the HTML text of a simple website. When I try printing, I get the text below in raw format with newline characters (<code>\n</code>) instead of actual new lines.</p>
<p><strong>This is my code:</strong></p>
<pre><code>import urllib.request
page = urllib.request.urlopen('http://www.york.a... | -1 | 2016-10-04T01:09:37Z | 39,842,794 | <p>One way to do it is by using pythons requests module. You can obtain it by doing pip install requests (you may have to use sudo if you're not using a virtualenv). </p>
<pre><code>import requests
res = requests.get('http://www.york.ac.uk/teaching/cws/wws/webpage1.html')
if res.status_code == 200: # check that the ... | 0 | 2016-10-04T01:14:24Z | [
"python",
"python-3.x",
"web"
] |
How can I print a webpage line by line in Python 3.x | 39,842,762 | <p>All I want to do is print the HTML text of a simple website. When I try printing, I get the text below in raw format with newline characters (<code>\n</code>) instead of actual new lines.</p>
<p><strong>This is my code:</strong></p>
<pre><code>import urllib.request
page = urllib.request.urlopen('http://www.york.a... | -1 | 2016-10-04T01:09:37Z | 39,863,583 | <p>Your byte string appears to have hard-coded <code>\n</code> in it. </p>
<p>For example, can't split on the value initially. </p>
<pre><code>In [1]: s = b'<HMTL>\n<HEAD>\n'
In [2]: s.split('\n')
---------------------------------------------------------------------------
TypeError ... | 0 | 2016-10-05T00:13:11Z | [
"python",
"python-3.x",
"web"
] |
How can I print a webpage line by line in Python 3.x | 39,842,762 | <p>All I want to do is print the HTML text of a simple website. When I try printing, I get the text below in raw format with newline characters (<code>\n</code>) instead of actual new lines.</p>
<p><strong>This is my code:</strong></p>
<pre><code>import urllib.request
page = urllib.request.urlopen('http://www.york.a... | -1 | 2016-10-04T01:09:37Z | 39,868,126 | <p>Whet you have is not text but bytes. If you want text just decode it.</p>
<pre><code>b = b'<HMTL>\n<HEAD>\n<TITLE>webpage1</TITLE>\n</HEAD>\n<BODY BGCOLOR="FFFFFf" LINK="006666" ALINK="8B4513" VLINK="006666">\n'
s = b.decode() # might need to specify an encoding
print(s)
</code>... | 0 | 2016-10-05T07:42:56Z | [
"python",
"python-3.x",
"web"
] |
More efficient way to create JSON from Python | 39,842,766 | <p>I'd like to write an API that reads from a CSV on disk (with x, y coordinates) and outputs them in JSON format to be rendered by a web front end. The issue is that there are lots of data points (order of 30k) and so going from numpy arrays of x and y into JSON is really slow.</p>
<p>This is my current function to g... | 1 | 2016-10-04T01:10:00Z | 39,842,777 | <p>You could use list comprehension like:</p>
<pre><code>def to_json(xdata, ydata):
return [{"x": x, "y": y} for x, y in zip(xdata, ydata)]
</code></pre>
<p>Eliminates use of unnessacary variable, and is cleaner.</p>
<p>You can also use generators like:</p>
<pre><code>def to_json(xdata, ydata):
return ({"... | 1 | 2016-10-04T01:12:30Z | [
"python",
"json",
"rest"
] |
More efficient way to create JSON from Python | 39,842,766 | <p>I'd like to write an API that reads from a CSV on disk (with x, y coordinates) and outputs them in JSON format to be rendered by a web front end. The issue is that there are lots of data points (order of 30k) and so going from numpy arrays of x and y into JSON is really slow.</p>
<p>This is my current function to g... | 1 | 2016-10-04T01:10:00Z | 39,842,841 | <p>Your method seems reasonable enough. Here are a few changes I might make to it. The itertools module has lots of handy tools that can make your life easier. I used izip, which you can read up on <a href="https://docs.python.org/2/library/itertools.html#itertools.izip" rel="nofollow">here</a> </p>
<pre><code>import... | 0 | 2016-10-04T01:23:17Z | [
"python",
"json",
"rest"
] |
Proper way to populate model with one-to-one relationship with User model - Django | 39,842,818 | <p>I am using Djangos basic User model. There are some fields that I wanted to add to the User model for my own needs. I created a new model named <code>Profile</code> and made it have a one-to-one relationship with the User model. I can now create a user and then populate the <code>Profile</code> model that is associa... | 0 | 2016-10-04T01:19:01Z | 39,843,180 | <p>You could make it a bit more concise</p>
<pre><code>def create(self, validated_data):
user = User.objects.create_user(
username=validated_data['email'],
email=validated_data['email'],
)
user.set_password(validated_data.pop('password'))
profile = UserProfile(user=user, **validated_da... | 0 | 2016-10-04T02:15:32Z | [
"python",
"django"
] |
How do I call a list or object defined in another instance into another instance? | 39,842,830 | <pre><code>class Sieve:
def __init__(self, digit):
self.digit = []
numbers = [True]*digit
if digit <= -1:
raise RuntimeError("Cannot use negative values.")
numbers[0] = False
numbers[1] = False
def findPrimes(self):
for i in range(len(self.digit)):
if numbers[i]:
... | 0 | 2016-10-04T01:21:09Z | 39,842,856 | <p>According to your post, your functions are unindented, so they're defined outside of your class.</p>
<p>Remember python relies heavily on indenting due to the lack of things like braces.</p>
<p>Also, your variable are local to your functions, and aren't properties of your class. You need to add them to your class ... | 0 | 2016-10-04T01:24:38Z | [
"python",
"sieve"
] |
Way to accomplish task using list comphrehension | 39,842,831 | <p>Is there a way to accomplish the following using a <code>list comprehension</code>? Or is there a more Pythonic way of accomplishing this? </p>
<pre><code>count = 0
x = 'uewoiquewqoiuinkcnsjk'
for letter in x:
if letter in ['a', 'e', 'i', 'o', 'u']:
count += 1
</code></pre>
<p>Just trying to learn th... | 1 | 2016-10-04T01:21:13Z | 39,842,845 | <p>Use the combination of list_comprehension and len function.</p>
<pre><code>>>> x = 'uewoiquewqoiuinkcnsjk'
>>> len([i for i in x if i in 'aeiou'])
10
>>>
</code></pre>
| 4 | 2016-10-04T01:23:52Z | [
"python",
"list-comprehension"
] |
Way to accomplish task using list comphrehension | 39,842,831 | <p>Is there a way to accomplish the following using a <code>list comprehension</code>? Or is there a more Pythonic way of accomplishing this? </p>
<pre><code>count = 0
x = 'uewoiquewqoiuinkcnsjk'
for letter in x:
if letter in ['a', 'e', 'i', 'o', 'u']:
count += 1
</code></pre>
<p>Just trying to learn th... | 1 | 2016-10-04T01:21:13Z | 39,842,875 | <p>Since <code>in</code> generates a <code>True</code> or <code>False</code> and <code>True</code> and <code>False</code> <a href="http://legacy.python.org/dev/peps/pep-0285/" rel="nofollow">can reliably be used</a> as <code>1</code> and <code>0</code> you can use <code>sum</code> with a generator:</p>
<pre><code>sum... | 4 | 2016-10-04T01:27:30Z | [
"python",
"list-comprehension"
] |
Python Leibniz summation | 39,842,873 | <p><a href="http://i.stack.imgur.com/baHSG.png" rel="nofollow">Leibniz summation</a></p>
<p>I'm trying to get leibniz summation with python, but, with my code, I'm getting slightly different value. I can't find why it's not giving me the right answer.</p>
<pre><code>import math
def estimate_pi( iterations ):
pi =... | 1 | 2016-10-04T01:27:00Z | 39,842,962 | <p>The summation does not estimate <code>pi</code>, it estimates <code>pi/4</code>. So change the code to something like:</p>
<pre><code>def estimate_pi( iterations ):
sum = 0.0
for n in range(iterations):
sum += (math.pow(-1,n)/((2*n)+1))
# sum now estimates pi/4, so return sum * 4 ~ (pi/4) * 4 ~ ... | 1 | 2016-10-04T01:40:35Z | [
"python"
] |
Extracting pdf attachment from IMAP account -- python 3.5.2 | 39,842,902 | <p>Ok, so I'm trying to save pdf attachments sent to a specific account to a specific network folder but I'm stuck at the attachment part. I've got the following code to pull in the unseen messages, but I'm not sure how to get the "parts" to stay intact. I think I can maybe figure this out if I can figure out how to k... | 0 | 2016-10-04T01:30:59Z | 39,843,526 | <p>You can use part.get_content_type() to get the full content type and part.get_payload() to get the payload as follows:
</p>
<pre><code>for part in msg.walk():
if part.get_content_type() == 'application/pdf':
# When decode=True, get_payload will return None if part.is_multipart()
# and the decode... | 0 | 2016-10-04T03:04:52Z | [
"python",
"email",
"imap"
] |
Creating 2 strings out of 1 recursively | 39,842,918 | <p>I'm trying to write a program that takes a string(stringg) apart and creates 1 string with all uppercase letters in stringg and 1 string with all lowercase letters in stringg. </p>
<p>result should be something like this:</p>
<pre><code>split_rec('HsaIm') = ('HI', 'sam')
</code></pre>
<p>This is how I have tried ... | 0 | 2016-10-04T01:33:38Z | 39,843,006 | <p>There is issue with you recursion logic and it can easily be done without recursion like:</p>
<pre><code>def split_rec(stringg):
alphas = [x for x in stringg if x.isalpha()]
lower = [x for x in alphas if not x.isupper() ]
upper = [x for x in alphas if x.isupper() ]
return (''.join(upper), ''.join(lo... | 0 | 2016-10-04T01:46:52Z | [
"python",
"string",
"tuples"
] |
Creating 2 strings out of 1 recursively | 39,842,918 | <p>I'm trying to write a program that takes a string(stringg) apart and creates 1 string with all uppercase letters in stringg and 1 string with all lowercase letters in stringg. </p>
<p>result should be something like this:</p>
<pre><code>split_rec('HsaIm') = ('HI', 'sam')
</code></pre>
<p>This is how I have tried ... | 0 | 2016-10-04T01:33:38Z | 39,843,013 | <p>First avoid test like so:</p>
<pre><code>if condition == True:
</code></pre>
<p>and write simply</p>
<pre><code>if condition:
</code></pre>
<p>Then you need to return a tuple and access the result as a tuple in all cases:</p>
<pre><code>def split_rec(stringg):
if not stringg:
return ('','')
el... | 1 | 2016-10-04T01:48:32Z | [
"python",
"string",
"tuples"
] |
Creating 2 strings out of 1 recursively | 39,842,918 | <p>I'm trying to write a program that takes a string(stringg) apart and creates 1 string with all uppercase letters in stringg and 1 string with all lowercase letters in stringg. </p>
<p>result should be something like this:</p>
<pre><code>split_rec('HsaIm') = ('HI', 'sam')
</code></pre>
<p>This is how I have tried ... | 0 | 2016-10-04T01:33:38Z | 39,843,148 | <pre><code>split_rec = lambda x: tuple(map(''.join, zip(*[(a,'') if a.isupper() else ('',a) for a in x if a.isalpha()])))
>>> split_rec('HsaIm')
('HI', 'sam')
</code></pre>
<p>This takes your string and sorts each letter as upper or lower case by putting it on the right or left side of a tuple. Then it unzip... | 1 | 2016-10-04T02:09:19Z | [
"python",
"string",
"tuples"
] |
Python / pandas - SettingWithCopyWarning using DatetimeIndex().day | 39,842,955 | <p>I have code given the SettingWithCopy Warning and I can't figure out to recode it properly. </p>
<pre><code>dataframe['day'] = pandas.DatetimeIndex(dataframe['date_time']).day
</code></pre>
<p>I am trying to make columns in the original dataframe holidng the day, year, etc.</p>
| -1 | 2016-10-04T01:40:01Z | 39,842,994 | <p>you can do this simply by calling day:</p>
<pre><code>df['day'] = df['date_time'].day
</code></pre>
<p>but I doubt this where the warning is coming from.</p>
| 0 | 2016-10-04T01:45:07Z | [
"python",
"pandas"
] |
Python / pandas - SettingWithCopyWarning using DatetimeIndex().day | 39,842,955 | <p>I have code given the SettingWithCopy Warning and I can't figure out to recode it properly. </p>
<pre><code>dataframe['day'] = pandas.DatetimeIndex(dataframe['date_time']).day
</code></pre>
<p>I am trying to make columns in the original dataframe holidng the day, year, etc.</p>
| -1 | 2016-10-04T01:40:01Z | 39,847,895 | <p>You need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.day.html" rel="nofollow"><code>Series.dt.day</code></a>, <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.year.html" rel="nofollow"><code>Series.dt.year</code></a>:</p>
<pre><code>df['day'] = df['... | 0 | 2016-10-04T08:46:17Z | [
"python",
"pandas"
] |
How can I convert a vector in string form to tuple form with each vector component being a tuple element? | 39,842,959 | <p>I'm writing a Python script to parse an XML file. When I get to the following part of the XML file,</p>
<pre><code> <H.1>
(1.00000000000000, 0.000000000000000E+000)
</H.1>
</code></pre>
<p>the script uses the following to parse the text</p>
<pre><code> H1 = H.find('H.1')
tokens... | 0 | 2016-10-04T01:40:31Z | 39,842,998 | <p>You can use <a href="https://docs.python.org/3/library/ast.html#ast.literal_eval" rel="nofollow">literal_eval</a> from <a href="https://docs.python.org/3/library/ast.html" rel="nofollow">ast</a>:</p>
<pre><code>>>> s = '(1.00000000000000,0.000000000000000E+000)'
>>> from ast import literal_eval
&g... | 1 | 2016-10-04T01:45:41Z | [
"python",
"xml",
"list",
"vector"
] |
Creating a triangle of characters from a users input | 39,843,022 | <p>For an assignment I'm suppose to make a triangle using the users input if the characters are equal to an even number. The triangle is suppose to print up to 5 lines in height and the left of it should be the left half of the string and the right side of the triangle should be the right side of the string. </p>
<p><... | 0 | 2016-10-04T01:49:28Z | 39,843,234 | <p>Here's how you can do this:</p>
<pre><code>def print_next(st, index):
if index < 6: # have not reached 5 - print offset and string
offset = 6-index
print ' '*offset+st
index=index+1 # increase counter
print_next((st[0:2]+st[-2:len(st)])*index,index) # recursively go next
print_... | 2 | 2016-10-04T02:24:56Z | [
"python"
] |
Creating a triangle of characters from a users input | 39,843,022 | <p>For an assignment I'm suppose to make a triangle using the users input if the characters are equal to an even number. The triangle is suppose to print up to 5 lines in height and the left of it should be the left half of the string and the right side of the triangle should be the right side of the string. </p>
<p><... | 0 | 2016-10-04T01:49:28Z | 39,843,359 | <p>I think you can use a stack to save each line so you can easily get a triangle-like output. Also because you can't use loop so my suggestion would be recursive.</p>
<pre><code>public_stack = []
def my_func(original_str, line_count, space_num):
if(line_count == 0):
return
times = line_count * 2
... | 0 | 2016-10-04T02:41:33Z | [
"python"
] |
Having an issue with Python's unittest | 39,843,124 | <p>I am learning Python and trying to test a Polynomial class I wrote using unittest. It seems like I am getting different results from directly running a test in Python and running a test using unittest and I don't understand what's going on.</p>
<pre><code>import unittest
from w4_polynomial import Polynomial
class ... | 1 | 2016-10-04T02:04:33Z | 39,846,639 | <p>I think the issue is with the implementation with <code>def __ne__</code> function in Polynomial class.
assertNotEqual when called, expects a True value when the values passed are not equal. But in this class, you are directly sending the output of temp1 != temp3 and temp2 != temp4.</p>
<p>So, the function should b... | 0 | 2016-10-04T07:33:14Z | [
"python",
"unit-testing",
"python-3.x",
"python-unittest"
] |
Google Cloud Endpoints: Endpoint Request Parameters (Resource Containers) Empty when Deployed | 39,843,178 | <p>I have an app for Google App Engine. The backend uses Python and the front-end uses JavaScript. The app works as expected locally and the API Explorer works as expected when deployed.</p>
<p>However, the API does not work with the front-end as expected when deployed. The issue is that the cloud endpoint methods ... | 0 | 2016-10-04T02:15:08Z | 39,844,060 | <p>I got it working. The main fix was based on <a href="https://cloud.google.com/appengine/docs/python/endpoints/create_api" rel="nofollow">this documentation</a>. I "defined a message class that has all the arguments that will be passed in the request body", then defined the resource container used in the request me... | 0 | 2016-10-04T04:13:32Z | [
"javascript",
"python",
"google-app-engine",
"google-cloud-endpoints"
] |
Command line arguments not being passed in sbatch | 39,843,230 | <p>I am trying to submit a job using the SLURM job scheduler and am finding that when I use the <code>--export=VAR=VALUE</code> syntax then some of my variables are not being passed (often the variable in the first instance of <code>export</code>). My understanding is that I need to specify <code>--export=...</code> fo... | 0 | 2016-10-04T02:24:27Z | 39,843,397 | <p>Yes, looks like I had the syntax incorrect. I missed in the documentation that additional variables should be comma separated and specified with a single <code>export</code> flag, e.g.</p>
<pre><code>> sbatch --export=build=true,param=p100_256 run.py
</code></pre>
<p>So previous instances of <code>export</code... | 0 | 2016-10-04T02:47:38Z | [
"python",
"command-line-arguments",
"slurm"
] |
Pandas remove rows which any string | 39,843,279 | <p>A very basic qs guys - thans vm for taking a look. I want to remove rows in <code>Col1</code> which contain any string - care about only numeric values in <code>Col1</code>.</p>
<p>Input:</p>
<pre><code> Col1 Col2 Col3
0 123 48.0 ABC
1 45 85.0 DEF
2 A.789 66.0 PQR
3 RN.35 9.0 PQR
4 ... | 1 | 2016-10-04T02:30:27Z | 39,843,374 | <p>do like this:</p>
<pre><code>import re
regex = re.compile("[a-zA-Z]+")
df.ix[df.col1.map(lambda x: regex.search(x) is None)]
</code></pre>
| 4 | 2016-10-04T02:43:47Z | [
"python",
"string",
"pandas",
"indexing",
"numeric"
] |
Pandas remove rows which any string | 39,843,279 | <p>A very basic qs guys - thans vm for taking a look. I want to remove rows in <code>Col1</code> which contain any string - care about only numeric values in <code>Col1</code>.</p>
<p>Input:</p>
<pre><code> Col1 Col2 Col3
0 123 48.0 ABC
1 45 85.0 DEF
2 A.789 66.0 PQR
3 RN.35 9.0 PQR
4 ... | 1 | 2016-10-04T02:30:27Z | 39,844,743 | <p>Another faster solution with <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>boolean indexing</code></a> and condition with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_numeric.html" rel="nofollow"><code>to_numeric</code></a> where... | 1 | 2016-10-04T05:26:53Z | [
"python",
"string",
"pandas",
"indexing",
"numeric"
] |
python/django: deployment to heroku fails | 39,843,305 | <p>I am trying to deploy an app to heroku.
It's a python/django app, and it runs fine on my local machine.</p>
<p>When deploying, heroku downloads the packages defined in requirements.txt, but then stops complaining about <code>qpython</code> not being able to be built, because it can't find <code>numpy</code>. But fr... | 0 | 2016-10-04T02:34:15Z | 39,844,081 | <p>Like it says, you need to have numpy installed (it doesn't install on heroku with pip).</p>
<p>You have to use a buildpack to install numpy on your heroku app:</p>
<p><a href="https://github.com/thenovices/heroku-buildpack-scipy" rel="nofollow">https://github.com/thenovices/heroku-buildpack-scipy</a></p>
| 0 | 2016-10-04T04:16:44Z | [
"python",
"django",
"numpy",
"heroku",
"qpython"
] |
Updating Each Row with Minutes Since First Row | 39,843,394 | <p>I have a file with a million tweets. The first tweet occurred <code>2013-04-15 20:17:18 UTC</code>. I want to update each tweet row afterward with the minutes since <code>minsSince</code> that first tweet. </p>
<p>I have found help with datetime <a href="http://stackoverflow.com/questions/2788871/python-date-diff... | 1 | 2016-10-04T02:47:12Z | 39,843,629 | <pre><code>#Import stuff
from datetime import datetime
import time
import pandas as pd
from pandas import DataFrame
#Read the csv file
tweets = pd.read_csv('sample.csv')
tweets.head()
#The first tweet's published_at time
starttime = tweets.published_at.values[0]
starttime = datetime.strptime(starttime, '%Y-%m-%d %H:%... | 0 | 2016-10-04T03:20:31Z | [
"python",
"datetime",
"twitter",
"time"
] |
How to make an integer larger than any other integer? | 39,843,488 | <p>Note: while the accepted answer achieves the result I wanted, and @ecatmur answer provides a more comprehensive option, I feel it's very important to emphasize that my use case is a bad idea in the first place. This is explained very well in <a href="http://stackoverflow.com/a/39856605/336527">@Jason Orendorff answe... | 41 | 2016-10-04T03:00:56Z | 39,843,523 | <p>Since python integers are unbounded, you have to do this with a custom class:</p>
<pre><code>import functools
@functools.total_ordering
class NeverSmaller(object):
def __le__(self, other):
return False
class ReallyMaxInt(NeverSmaller, int):
def __repr__(self):
return 'ReallyMaxInt()'
</cod... | 61 | 2016-10-04T03:04:16Z | [
"python",
"python-3.x"
] |
How to make an integer larger than any other integer? | 39,843,488 | <p>Note: while the accepted answer achieves the result I wanted, and @ecatmur answer provides a more comprehensive option, I feel it's very important to emphasize that my use case is a bad idea in the first place. This is explained very well in <a href="http://stackoverflow.com/a/39856605/336527">@Jason Orendorff answe... | 41 | 2016-10-04T03:00:56Z | 39,853,886 | <p>It seems to me that this would be fundamentally impossible. Let's say you write a function that returns this RBI ("really big int"). If the computer is capable of storing it, then someone else could write a function that returns the same value. Is your RBI greater than itself?</p>
<p>Perhaps you can achieve the des... | 1 | 2016-10-04T13:40:28Z | [
"python",
"python-3.x"
] |
How to make an integer larger than any other integer? | 39,843,488 | <p>Note: while the accepted answer achieves the result I wanted, and @ecatmur answer provides a more comprehensive option, I feel it's very important to emphasize that my use case is a bad idea in the first place. This is explained very well in <a href="http://stackoverflow.com/a/39856605/336527">@Jason Orendorff answe... | 41 | 2016-10-04T03:00:56Z | 39,855,605 | <p>Konsta Vesterinen's <a href="https://github.com/kvesteri/infinity"><code>infinity.Infinity</code></a> would work (<a href="https://pypi.python.org/pypi/infinity/">pypi</a>), except that it doesn't inherit from <code>int</code>, but you can subclass it:</p>
<pre><code>from infinity import Infinity
class IntInfinity(... | 23 | 2016-10-04T14:57:45Z | [
"python",
"python-3.x"
] |
How to make an integer larger than any other integer? | 39,843,488 | <p>Note: while the accepted answer achieves the result I wanted, and @ecatmur answer provides a more comprehensive option, I feel it's very important to emphasize that my use case is a bad idea in the first place. This is explained very well in <a href="http://stackoverflow.com/a/39856605/336527">@Jason Orendorff answe... | 41 | 2016-10-04T03:00:56Z | 39,856,605 | <blockquote>
<p>Use case: library function expects an integer, and the only easy way to force a certain behavior is to pass a very large integer.</p>
</blockquote>
<p>This sounds like a flaw in the library that should be fixed in its interface. Then all its users would benefit. What library is it?</p>
<p>Creating a... | 15 | 2016-10-04T15:45:43Z | [
"python",
"python-3.x"
] |
How to make an integer larger than any other integer? | 39,843,488 | <p>Note: while the accepted answer achieves the result I wanted, and @ecatmur answer provides a more comprehensive option, I feel it's very important to emphasize that my use case is a bad idea in the first place. This is explained very well in <a href="http://stackoverflow.com/a/39856605/336527">@Jason Orendorff answe... | 41 | 2016-10-04T03:00:56Z | 39,857,811 | <p>Another way to do this (very much inspired by wim's answer) might be an object that isn't infinite, but increases on the fly as needed. </p>
<p>Here's what I have in mind: </p>
<pre><code>from functools import wraps
class AlwaysBiggerDesc():
'''A data descriptor that always returns a value bigger than instanc... | -4 | 2016-10-04T16:52:24Z | [
"python",
"python-3.x"
] |
How to make an integer larger than any other integer? | 39,843,488 | <p>Note: while the accepted answer achieves the result I wanted, and @ecatmur answer provides a more comprehensive option, I feel it's very important to emphasize that my use case is a bad idea in the first place. This is explained very well in <a href="http://stackoverflow.com/a/39856605/336527">@Jason Orendorff answe... | 41 | 2016-10-04T03:00:56Z | 39,921,621 | <blockquote>
<p><strong>In Python 3.5, you can do:</strong></p>
<p><code>import math
test = math.inf</code></p>
<p>And then:</p>
<p><code>test > 1
test > 10000
test > x</code></p>
<p>Will always be true. Unless of course, as pointed out, x is also infinity or "nan" ("not a number").... | 1 | 2016-10-07T16:08:53Z | [
"python",
"python-3.x"
] |
How to make an integer larger than any other integer? | 39,843,488 | <p>Note: while the accepted answer achieves the result I wanted, and @ecatmur answer provides a more comprehensive option, I feel it's very important to emphasize that my use case is a bad idea in the first place. This is explained very well in <a href="http://stackoverflow.com/a/39856605/336527">@Jason Orendorff answe... | 41 | 2016-10-04T03:00:56Z | 39,924,210 | <p>You should not be inheriting from <code>int</code> unless you want both its <em>interface</em> and its <em>implementation</em>. (Its implementation is an automatically-widening set of bits representing a finite number. You clearly dont' want that.) Since you only want the <em>interface</em>, then inherit from the... | 0 | 2016-10-07T19:04:35Z | [
"python",
"python-3.x"
] |
I'm wondering how to assign a a few different files to different corresponding numbers in python | 39,843,491 | <p>I'm wondering how a assign the file to just one of the numbers in the list, and if they make another file it will assign it to the next corresponding number.</p>
<pre><code>number = [1, 2, 3, 4, 5]
while True:
with open(number, "w") as w:
number.write(input(""))
user_answer = input("1 to start anot... | 0 | 2016-10-04T03:01:11Z | 39,845,085 | <pre><code># An integer denoting the name of the file to be generated.
# The name of the first file generated would be "1" (excluding the extension format)
i = 0
while True:
# Create the path of the file to be generated
file_path = str(i) + ".txt"
with open(file_path, "w") as my_file_handle:
print("... | 0 | 2016-10-04T05:56:25Z | [
"python",
"python-3.x"
] |
I'm wondering how to assign a a few different files to different corresponding numbers in python | 39,843,491 | <p>I'm wondering how a assign the file to just one of the numbers in the list, and if they make another file it will assign it to the next corresponding number.</p>
<pre><code>number = [1, 2, 3, 4, 5]
while True:
with open(number, "w") as w:
number.write(input(""))
user_answer = input("1 to start anot... | 0 | 2016-10-04T03:01:11Z | 39,845,465 | <p>Let's take your program line by line.</p>
<pre><code>number = [1, 2, 3, 4, 5]
</code></pre>
<p>The only problem here is that <code>number</code> is not quite the right name for your variable.</p>
<p><code>[1, 2, 3, 4, 5]</code> isn't a single number, but a list of five numbers. Choosing good names for variables i... | 1 | 2016-10-04T06:25:18Z | [
"python",
"python-3.x"
] |
Python - Append items to a list while making https requests inside a loop | 39,843,560 | <p>I am making requests to <code>SPotify API</code> inside a <code>for loop</code>, like so:</p>
<pre><code>track_ids = []
#get track_ids
for track in random.sample(pitchfork_tracks, 10):
results = sp.search(q=track, type='track') #here I call Spotify endpoint
items = results['tracks']['items']
for t in it... | 0 | 2016-10-04T03:09:04Z | 39,843,669 | <p><code>track_ids</code> scope is inside your function. To print list you can do like this </p>
<pre><code>track_ids = yourfunction()
print track_ids
</code></pre>
<p>OR </p>
<p>you can make <code>track_ids</code> list global and declare it outside of your function. </p>
| 2 | 2016-10-04T03:25:35Z | [
"python",
"for-loop",
"python-requests",
"spotipy"
] |
Schema - Ability to change email address (primary user id) in Django | 39,843,618 | <p>Currently my user table looks like this - (all fields are not null)</p>
<pre><code>display_name = CharField # string
email_address = EmailField (primary key) # string
password = CharField # string
</code></pre>
<p>However, I have decided to add additional functionality an... | 1 | 2016-10-04T03:18:44Z | 39,844,369 | <p>The standard practice in this sort of situation is to create a separate table for email addresses. That allows users to have more than one email address at a given time and one of them can be marked as default. </p>
<p>This is what <a href="https://github.com/pennersr/django-allauth/blob/master/allauth/account/mode... | 1 | 2016-10-04T04:50:38Z | [
"python",
"django",
"database",
"user",
"schema"
] |
postgresql insert timestamp error with python | 39,843,631 | <p>I use psycopg2 for postgresql. Here is my snippet:</p>
<pre><code>a = "INSERT INTO tweets (Time) VALUES (%s);" % (datetime.now(),)
cursor.execute(a)
</code></pre>
<p>this won't work and gives me an error:</p>
<pre><code>ProgrammingError: syntax error at or near "20"
LINE 1: INSERT INTO tweets (Time) VALUES (2016... | 1 | 2016-10-04T03:20:53Z | 39,847,509 | <p>If you check the first query, it states <code>INSERT INTO tweets (Time) VALUES (2016-10-03 20:14:49.065092...</code>, that means, it tries to use unquoted value as a time and this won't work.</p>
<p>If you really want to use your first approach, you have to quote the value:</p>
<pre><code>a = "INSERT INTO tweets (... | 2 | 2016-10-04T08:25:05Z | [
"python",
"postgresql",
"timestamp",
"psycopg2"
] |
how to have multiple arguments in a input fuction in python | 39,843,660 | <p><strong>This function throws an error at the input function claiming that the arguments are invalid.. any resolutions?</strong></p>
<pre><code>def assignSquareValues():
square=[[0,0,0],
[0,0,0],
[0,0,0]]
count=0
try:
for r in range(3):
... | 0 | 2016-10-04T03:24:30Z | 39,843,834 | <p><code>input()</code> expects one argument - displayed text - so you have to concatenate all arguments in to one text</p>
<p>ie.</p>
<pre><code>input("Enter a number(1-9) for square #" + str(count) + ":")
</code></pre>
<p>or</p>
<pre><code>input("Enter a number(1-9) for square #{}:".format(count))
</code></pre>
| 1 | 2016-10-04T03:46:43Z | [
"python"
] |
Selection Sort Algorithm Python | 39,843,663 | <p>Working on implementing this algorithm using Python. I thought my logic was okay but apparently not as Python is complaining. The while loop is causing issues. If I remove that it works as expected but obviously doesn't sort the whole list. My thought process -> Use Linear Search to find the smallest number -> Appen... | 0 | 2016-10-04T03:24:46Z | 39,843,739 | <p>It looks like <strong>you're not re-initializing</strong> the <code>smallest_number</code> variable, so after the first execution of your <code>while</code> loop - you look for a value smaller than the previous value which you just <code>pop</code>ed from the list.</p>
<p>When you don't find a value smaller than th... | 2 | 2016-10-04T03:34:35Z | [
"python",
"algorithm",
"list",
"sorting"
] |
Selection Sort Algorithm Python | 39,843,663 | <p>Working on implementing this algorithm using Python. I thought my logic was okay but apparently not as Python is complaining. The while loop is causing issues. If I remove that it works as expected but obviously doesn't sort the whole list. My thought process -> Use Linear Search to find the smallest number -> Appen... | 0 | 2016-10-04T03:24:46Z | 39,843,785 | <p>After every while loop, you should assign <code>items_to_sort[0]</code> to <code>smallest_number</code></p>
<pre><code>current_number = 0
sorted_items = []
item_len = len(items_to_sort)
while item_len > 0:
smallest_number = items_to_sort[0]
for item in items_to_sort[:]:
if item < smallest_num... | 1 | 2016-10-04T03:41:26Z | [
"python",
"algorithm",
"list",
"sorting"
] |
Python class instance variables disappear | 39,843,697 | <p>I define the response class like this:</p>
<pre><code>class Response(object):
def __index__(self):
self.country = ""
self.time_human = ""
self.time_utc = ""
self.text = ""
self.time_object = None
self.clean_word_list = []
def parse_line(self, line):
i... | -1 | 2016-10-04T03:29:48Z | 39,843,769 | <p>It has to be <code>__init__</code> instead of <code>__index__</code> in your <code>Response</code> class</p>
| 0 | 2016-10-04T03:37:36Z | [
"python",
"class"
] |
why my links not writing in my file | 39,843,798 | <pre><code>import urllib
from bs4 import BeautifulSoup
import requests
import readability
import time
import http.client
seed_url = "https://en.wikipedia.org/wiki/Sustainable_energy"
root_url = "https://en.wikipedia.org"
max_limit=5
#file = open("file_crawled.txt", "w")
def get_urls(seed_url):
r = requests.get(seed_u... | 2 | 2016-10-04T03:42:31Z | 39,845,004 | <p>You have to open and close file only once - open before first <code>crawl_dfs()</code> and close after first <code>crawl_dfs()</code></p>
<p>Tested:</p>
<pre><code>import urllib
from bs4 import BeautifulSoup
import requests
#import readability
import time
import http.client
# --- functions ---
def get_urls(seed_... | 1 | 2016-10-04T05:50:28Z | [
"python",
"python-3.x",
"web",
"web-crawler",
"depth-first-search"
] |
Django - Splitting admin.py | 39,843,825 | <p>I tried to split admin.py with the following steps but failed.<br>
- Remove admin.py<br>
- Create folder named "admin"<br>
- Create files in folder "admin". modela.py, modelb.py<br>
- Create "_ <em>init</em> _.py" and leave it empty<br>
- In the "modela.py" file</p>
<pre><code>from django.contrib import admin
from ... | 0 | 2016-10-04T03:45:24Z | 39,845,519 | <p>Firstly, the file is called <code>__init__.py</code>, with two underscores each side. Secondly, leaving it empty won't do anything at all; you would need to import your admin classes into that file.</p>
| 1 | 2016-10-04T06:28:54Z | [
"python",
"django"
] |
JupyterHub openssl self signed cert "Error: error:0906D06C:PEM routines:PEM_read_bio:no start line" | 39,843,909 | <p>Trying to configure at JupyterHub on a AWS instance using a self signed OPENSSL key/cert pair. I have tried several openssl configurations, and continued to have this same error.</p>
<pre><code>jupyterhub
[I 2016-10-04 03:38:24.090 JupyterHub app:622] Loading cookie_secret from /home/ubuntu/jupyterhub_coo... | 0 | 2016-10-04T03:55:12Z | 39,852,086 | <p>Your config has your certificate and key reversed:</p>
<p>You have this:</p>
<pre><code>c.JupyterHub.ssl_cert = '/home/ubuntu/mykey.pem'
c.JupyterHub.ssl_key = '/home/ubuntu/mycert.pem'
</code></pre>
<p>but you should have this:</p>
<pre><code>c.JupyterHub.ssl_cert = '/home/ubuntu/mycert.pem'
c.JupyterHub.ssl_ke... | 0 | 2016-10-04T12:16:21Z | [
"python",
"ssl",
"jupyter",
"jupyter-notebook",
"jupyterhub"
] |
Running a Function That Updates Array While Matplotlib Plots it | 39,843,925 | <p>I have a Python program (<em>main.py</em>) that has a constant stream of data that is handled by a class RTStreamer which basically gets the data -- via a live stream -- and appends it to a numpy array. However I would like to actually visualize the data as it is coming in which is where tkinter and matplotlib come ... | 0 | 2016-10-04T03:57:17Z | 39,856,802 | <p>To make your code work, you need to draw the artist on each frame, not just show the canvas. However, that will be effing slow. What you really want to do, is to only update the data, and keep as much of the canvas constant. For that you use blit. Minimum working example below.</p>
<pre><code>import numpy as np
imp... | 0 | 2016-10-04T15:54:16Z | [
"python",
"python-3.x",
"matplotlib",
"tkinter"
] |
python dynamic object query | 39,844,041 | <p>I have a python object structured like:</p>
<pre><code>tree = {
"a": {
"aa": {
"aaa": {},
"aab": {},
"aac": {}
},
"ab": {
"aba": {},
"abb": {}
}
},
"b": {
"ba": {}
},
"c": {}
}
</code></pre>
<p>A... | 1 | 2016-10-04T04:11:37Z | 39,844,125 | <p>I think the easiest way to do this is to utilize recursion. Every sub-tree is a tree and every sub-path is a path, so we can look at whether or not the first element in the path is valid then continue on from there.</p>
<pre><code>def is_valid(tree, path):
# base case. Any path would be valid for any tree
... | 3 | 2016-10-04T04:22:32Z | [
"python",
"arrays",
"object",
"dictionary"
] |
Union of node and function on node in XPath | 39,844,061 | <p>I am using Scrapy to crawl some webpages. I want to write an XPath query that will, within a parent <code><div></code>, append a couple of characters of text to any child <code><a></code> nodes, while extracting the text of the div's <code>self</code> node normally. Essentially it is like a normal <code... | 0 | 2016-10-04T04:14:16Z | 39,848,222 | <p>I think it doesn't work because concat is doesn't actually return a path, and <code>|</code> is used to select multiple <em>paths</em></p>
<blockquote>
<p>By using the | operator in an XPath expression you can select several paths. </p>
</blockquote>
<p>as per <a href="http://www.w3schools.com/xsl/xpath_syntax.... | 0 | 2016-10-04T09:01:39Z | [
"python",
"xpath",
"scrapy"
] |
Union of node and function on node in XPath | 39,844,061 | <p>I am using Scrapy to crawl some webpages. I want to write an XPath query that will, within a parent <code><div></code>, append a couple of characters of text to any child <code><a></code> nodes, while extracting the text of the div's <code>self</code> node normally. Essentially it is like a normal <code... | 0 | 2016-10-04T04:14:16Z | 39,856,552 | <p>In XPath 1.0, a <a href="https://www.w3.org/TR/xpath/#location-paths" rel="nofollow"><em>location path</em></a> returns a <a href="https://www.w3.org/TR/xpath/#node-sets" rel="nofollow"><em>node-set</em></a>. The <a href="https://www.w3.org/TR/xpath/#function-concat" rel="nofollow"><code>concat</code></a> function ... | 0 | 2016-10-04T15:42:58Z | [
"python",
"xpath",
"scrapy"
] |
Union of node and function on node in XPath | 39,844,061 | <p>I am using Scrapy to crawl some webpages. I want to write an XPath query that will, within a parent <code><div></code>, append a couple of characters of text to any child <code><a></code> nodes, while extracting the text of the div's <code>self</code> node normally. Essentially it is like a normal <code... | 0 | 2016-10-04T04:14:16Z | 39,860,611 | <p>Update: this is what I did:</p>
<pre class="lang-py prettyprint-override"><code>item['div_text'] = []
div_nodes = definition.xpath('div[@class="my_class"]/a | div[@class="my_class"]/text()')
for n in div_nodes:
if n.xpath('self::a'):
item['div_text'].append("@%s" % n.xpath('text()').extract_first())
... | 0 | 2016-10-04T19:48:32Z | [
"python",
"xpath",
"scrapy"
] |
How can I write a C function that takes either an int or a float? | 39,844,100 | <p>I want to create a function in C that extends Python that can take inputs of either float or int type. So basically, I want <code>f(5)</code> and <code>f(5.5)</code> to be acceptable inputs.</p>
<p>I don't think I can use <code>if (!PyArg_ParseTuple(args, "i", $value))</code> because it only takes only int or only ... | 9 | 2016-10-04T04:19:43Z | 39,844,489 | <p>You can check type of input value like this:</p>
<pre><code> PyObject* check_type(PyObject*self, PyObject*args) {
PyObject*any;
if (!PyArg_ParseTuple(args, "O", &any)) {
PyErr_SetString(PyExc_TypeError, "Nope.");
return NULL;
}
if (PyFloat_Check(any)) {
printf("indee... | 1 | 2016-10-04T05:03:01Z | [
"python",
"c",
"python-extensions"
] |
How can I write a C function that takes either an int or a float? | 39,844,100 | <p>I want to create a function in C that extends Python that can take inputs of either float or int type. So basically, I want <code>f(5)</code> and <code>f(5.5)</code> to be acceptable inputs.</p>
<p>I don't think I can use <code>if (!PyArg_ParseTuple(args, "i", $value))</code> because it only takes only int or only ... | 9 | 2016-10-04T04:19:43Z | 39,845,432 | <p>If you declare a C function to accept floats, the compiler won't complain if you hand it an int. For instance, this program produces the answer 2.000000:</p>
<pre><code>#include <stdio.h>
float f(float x) {
return x+1;
}
int main() {
int i=1;
printf ("%f", f(i));
}
</code></pre>
<p>A python module ve... | 5 | 2016-10-04T06:23:21Z | [
"python",
"c",
"python-extensions"
] |
How can I write a C function that takes either an int or a float? | 39,844,100 | <p>I want to create a function in C that extends Python that can take inputs of either float or int type. So basically, I want <code>f(5)</code> and <code>f(5.5)</code> to be acceptable inputs.</p>
<p>I don't think I can use <code>if (!PyArg_ParseTuple(args, "i", $value))</code> because it only takes only int or only ... | 9 | 2016-10-04T04:19:43Z | 39,846,368 | <p>Floats are (usually) passed in via registers while ints are (usually) passed in via the stack. This means that you literally cannot, inside the function, check whether the argument is a float or an int.</p>
<p>The only workaround is to use variadic arguments, with the first argument specifying the type as either in... | 1 | 2016-10-04T07:18:03Z | [
"python",
"c",
"python-extensions"
] |
PermissionError: [Errno 13] Permission denied @ PYTHON | 39,844,123 | <p>i am trying to copy a file from one folder to another, but i am getting "PermissionError: [Errno 13] Permission denied". I am working within my home directory and i am the administrator of the PC. Went through many other previous posts .. tried all the options that are to my knowledge (newbie to programming) ... nee... | -1 | 2016-10-04T04:22:24Z | 39,844,477 | <p>Perhaps try to use shutil.copyfile instead:</p>
<pre><code>shutil.copyfile(src, dst)
</code></pre>
<p>Similar old topic on <a href="http://stackoverflow.com/questions/11835833/why-would-shutil-copy-raise-a-permission-exception-when-cp-doesnt">Why would shutil.copy() raise a permission exception when cp doesn't... | 1 | 2016-10-04T05:02:12Z | [
"python",
"shutil"
] |
Find common values in dictionary that has keys with multiple values | 39,844,141 | <p>I am new to python and I have a problem. I am trying to find keys with a value; however, the keys have multiple values.</p>
<pre><code>d = {
'a': ['john', 'doe', 'jane'],
'b': ['james', 'danny', 'john'],
'C':['john', 'scott', 'jane'],
}
</code></pre>
<p>I want to find the value <code>john</code> in d... | 0 | 2016-10-04T04:24:26Z | 39,844,174 | <p>This can easily be done using a <a href="https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions" rel="nofollow">list comprehension</a>. It iterates over every key/value pair from the dict's items list, which contains all key/value pairs (<code>for key,val in d.items()</code>) and selects only the... | 1 | 2016-10-04T04:29:05Z | [
"python",
"python-2.7",
"dictionary"
] |
Find common values in dictionary that has keys with multiple values | 39,844,141 | <p>I am new to python and I have a problem. I am trying to find keys with a value; however, the keys have multiple values.</p>
<pre><code>d = {
'a': ['john', 'doe', 'jane'],
'b': ['james', 'danny', 'john'],
'C':['john', 'scott', 'jane'],
}
</code></pre>
<p>I want to find the value <code>john</code> in d... | 0 | 2016-10-04T04:24:26Z | 39,844,227 | <p>So you have to go through the dictionary items and if the find keyword is in the item list then the corresponding key has to be stored in a list and this list has to be displayed.</p>
<pre><code>d = {'a':['john', 'doe', 'jane'], 'b': ['james', 'danny', 'john'], 'C':['john', 'scott', 'jane'],}
find ='jane'
</code></... | 1 | 2016-10-04T04:35:23Z | [
"python",
"python-2.7",
"dictionary"
] |
In Django, how do I order_by() when reaching across tables? | 39,844,200 | <p>I'm trying to filter my Friendships objects and then order_by user.first_name, but it's not working. Can anyone tell me what I'm doing wrong?</p>
<p>Here's my models:</p>
<pre><code>class Friendships(models.Model):
user = models.ForeignKey('Users', models.DO_NOTHING, related_name="usersfriend")
friend = mo... | 1 | 2016-10-04T04:32:13Z | 39,844,333 | <p>It's not your order by that's wrong but what you do with the results. Let us digest the following, particularly line 3</p>
<pre><code>ordered_friends = Friendships.objects.filter(user__id=1).order_by('user__first_name')
for ordered_friend in ordered_friends:
print ordered_friend.friend.first_name, ordered_frien... | 2 | 2016-10-04T04:45:49Z | [
"python",
"django",
"orm"
] |
Python AST to dictionary structure | 39,844,212 | <p>I am using the Python <code>ast</code> module to parse expressions like <code>X >= 13 and Y == W</code>. What I need is to transform this expression in a pre-order dictionary found below:</p>
<pre><code>{
"function": "and",
"args": [
{
"function": ">=",
"args": [
{
"varia... | 1 | 2016-10-04T04:33:42Z | 39,848,149 | <p>Consider these small changes - I've added <code>'</code>s and commas:</p>
<pre><code>import ast
class ExclusionParser(ast.NodeVisitor):
tree = ''
def append(self, expr):
self.tree += expr
def visit_And(self, node):
self.append("'func:and', ")
def visit_Lt(self, node):
self... | 1 | 2016-10-04T08:58:18Z | [
"python",
"json",
"abstract-syntax-tree"
] |
Keras convolution filter size issue | 39,844,273 | <p>I'm <em>very</em> new to Keras, and in my early experiments I've been encountering an error when I create convolutional layers. When I run this code (found <a href="https://keras.io/getting-started/functional-api-guide/#more-examples" rel="nofollow" title="here">here</a>; "Shared vision model" section)</p>
<pre><co... | 0 | 2016-10-04T04:39:51Z | 39,847,099 | <p>'image_dim_ordering' : 'tf' is setting the input's third dimension as the channel input to the 2D Convolution: ie you've currently put a 1x27 input with 27 channels in to be convolved with a 3x3 kernel and no padding.</p>
<p>You should be able to switch 'image_dim_ordering' to 'th' and have this code immediately wo... | 0 | 2016-10-04T07:58:49Z | [
"python",
"neural-network",
"tensorflow",
"convolution",
"keras"
] |
Checking if string contains valid Python code | 39,844,350 | <p>I am writing some sort of simple web-interpreter for vk.com . I look for messages, check if they are valid Python code, and then I want to execute that code, and return any <code>stdout</code> to code sender. I have implemented anything but code checker.</p>
<pre><code>import ast
def is_valid(code):
try:
... | 0 | 2016-10-04T04:48:40Z | 39,844,402 | <p>Keep in mind, the difference between a runtime error and a parser error is significant in your case and example. The statement:</p>
<pre><code>test
</code></pre>
<p>is <em>valid</em> code. Even though this statement will throw a <code>NameError</code> when the Python VM executes the code, the parser will not know ... | 1 | 2016-10-04T04:54:34Z | [
"python"
] |
Find the subset of a set of integers that has the maximum product | 39,844,473 | <p>Let A be a non-empty set of integers. Write a function <strong>find</strong> that outputs a non-empty subset of A that has the maximum product. For example, <strong>find([-1, -2, -3, 0, 2]) = 12 = (-2)*(-3)*2</strong></p>
<p>Here's what I think: divide the list into a list of positive integers and a list of negativ... | 8 | 2016-10-04T05:01:53Z | 39,844,702 | <p>You can simplify this problem with <code>reduce</code> (in <code>functools</code> in Py3)</p>
<pre><code>import functools as ft
from operator import mul
def find(ns):
if len(ns) == 1 or len(ns) == 2 and 0 in ns:
return str(max(ns))
pos = filter(lambda x: x > 0, ns)
negs = sorted(filter(lambd... | 1 | 2016-10-04T05:22:16Z | [
"python",
"algorithm"
] |
Find the subset of a set of integers that has the maximum product | 39,844,473 | <p>Let A be a non-empty set of integers. Write a function <strong>find</strong> that outputs a non-empty subset of A that has the maximum product. For example, <strong>find([-1, -2, -3, 0, 2]) = 12 = (-2)*(-3)*2</strong></p>
<p>Here's what I think: divide the list into a list of positive integers and a list of negativ... | 8 | 2016-10-04T05:01:53Z | 39,844,742 | <p>Here is another solution that doesn't require libraries :</p>
<pre><code>def find(l):
if len(l) <= 2 and 0 in l: # This is the missing case, try [-3,0], it should return 0
return max(l)
l = [e for e in l if e != 0] # remove 0s
r = 1
for e in l: # multiply all
r *= e
if r ... | 0 | 2016-10-04T05:26:38Z | [
"python",
"algorithm"
] |
Find the subset of a set of integers that has the maximum product | 39,844,473 | <p>Let A be a non-empty set of integers. Write a function <strong>find</strong> that outputs a non-empty subset of A that has the maximum product. For example, <strong>find([-1, -2, -3, 0, 2]) = 12 = (-2)*(-3)*2</strong></p>
<p>Here's what I think: divide the list into a list of positive integers and a list of negativ... | 8 | 2016-10-04T05:01:53Z | 39,846,442 | <pre><code>from functools import reduce
from operator import mul
def find(array):
negative = []
positive = []
zero = None
removed = None
def string_product(iterable):
return str(reduce(mul, iterable, 1))
for number in array:
if number < 0:
negative.append(number... | 1 | 2016-10-04T07:22:22Z | [
"python",
"algorithm"
] |
Find the subset of a set of integers that has the maximum product | 39,844,473 | <p>Let A be a non-empty set of integers. Write a function <strong>find</strong> that outputs a non-empty subset of A that has the maximum product. For example, <strong>find([-1, -2, -3, 0, 2]) = 12 = (-2)*(-3)*2</strong></p>
<p>Here's what I think: divide the list into a list of positive integers and a list of negativ... | 8 | 2016-10-04T05:01:53Z | 39,876,069 | <p>Here's a solution in one loop:</p>
<pre><code>def max_product(A):
"""Calculate maximal product of elements of A"""
product = 1
greatest_negative = float("-inf") # greatest negative multiplicand so far
for x in A:
product = max(product, product*x, key=abs)
if x <= -1:
... | 1 | 2016-10-05T14:00:41Z | [
"python",
"algorithm"
] |
"'CXXABI_1.3.8' not found" in tensorflow-gpu - install from source | 39,844,772 | <p>I have re-installed Anaconda2.
And I got the following error when 'python -c 'import tensorflow''</p>
<blockquote>
<p>ImportError: /home/jj/anaconda2/bin/../lib/libstdc++.so.6: version `CXXABI_1.3.8' not found (required by /home/jj/anaconda2/lib/python2.7/site-packages/tensorflow/python/_pywrap_tensorflow.so)</p... | 1 | 2016-10-04T05:30:04Z | 39,856,855 | <p>I solved this problem by copying the <code>libstdc++.so.6</code> file which contains version <code>CXXABI_1.3.8</code>. </p>
<p>Try run the following search command first:</p>
<p><code>$ strings /usr/lib/x86_64-linux-gnu/libstdc++.so.6 | grep CXXABI_1.3.8</code></p>
<p>If it returns <code>CXXABI_1.3.8</code>. The... | 1 | 2016-10-04T15:56:55Z | [
"python",
"tensorflow",
"cudnn"
] |
using variable name within list as string for file save python | 39,844,823 | <p>I have a python list which contains 4 elements, each of which is a time-series dataset.
e.g., </p>
<pre><code>full_set = [Apple_px, Banana_px, Celery_px]
</code></pre>
<p>I am charting them via matplotlib and I want to save the charts individually using the variable names. </p>
<pre><code>for n in full_set:
*pe... | 0 | 2016-10-04T05:34:38Z | 39,844,999 | <p>In Python names and values are two very different things, stored and dealt with in different ways - and more practically one value can have multiple names assigned to it.</p>
<p>So, instead of trying to get the name of some data value, use a tuple where you assign a title to the dataset in your list of datasets, so... | 0 | 2016-10-04T05:50:09Z | [
"python",
"matplotlib"
] |
How to add prefix to files' names, replace a character, and move to new directory? | 39,844,829 | <p>For example, the files will look like <code>FG-4.jpg</code> <code>FG-5.jpg</code>, etc. and need to be copied to a new directory and named <code>test_FG_4.jpg</code> <code>test_FG_5.jpg</code>, etc. </p>
<p>Here is the updated code:</p>
<pre><code>import shutil
import glob
import os
InFolder = r"C:\test_in"
OutFo... | 0 | 2016-10-04T05:35:29Z | 39,845,097 | <p>I am not sure about what you want. So this program checks for any file with extension .jpg and then copies them into a new folder("NewDir") by adding "Test_" to the file name. If the folder doesn't exist, the program creates the folder. Maybe you can make the changes you need based on this program.</p>
<pre><code>i... | 0 | 2016-10-04T05:57:44Z | [
"python",
"replace",
"rename"
] |
Pandas slow on data frame replace | 39,844,967 | <p>I have an Excel file (.xlsx) with about 800 rows and 128 columns with pretty dense data in the grid. There are about 9500 cells that I am trying to replace the cell values of using Pandas data frame:</p>
<pre><code>xlsx = pandas.ExcelFile(filename)
frame = xlsx.parse(xlsx.sheet_names[0])
media_frame = frame[media_h... | 4 | 2016-10-04T05:48:04Z | 39,846,474 | <p><strong><em>strategy</em></strong><br>
create <code>pd.Series</code> representing a <code>map</code> from filenames to filenames.<br>
<code>stack</code> our dataframe, <code>map</code>, then <code>unstack</code></p>
<p><strong><em>setup</em></strong> </p>
<pre><code>import pandas as pd
import numpy as np
from str... | 4 | 2016-10-04T07:24:28Z | [
"python",
"excel",
"pandas",
"dataframe"
] |
Pandas slow on data frame replace | 39,844,967 | <p>I have an Excel file (.xlsx) with about 800 rows and 128 columns with pretty dense data in the grid. There are about 9500 cells that I am trying to replace the cell values of using Pandas data frame:</p>
<pre><code>xlsx = pandas.ExcelFile(filename)
frame = xlsx.parse(xlsx.sheet_names[0])
media_frame = frame[media_h... | 4 | 2016-10-04T05:48:04Z | 39,847,753 | <p>I got the 60 second task to complete in 10 seconds by removing <code>replace()</code> altogether and using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_value.html" rel="nofollow">set_value()</a> one element at a time.</p>
| 1 | 2016-10-04T08:38:29Z | [
"python",
"excel",
"pandas",
"dataframe"
] |
Sorting a string to make a new one | 39,845,025 | <p>Here I had to remove the most frequent alphabet of a string(if frequency of two alphabets is same, then in alphabetical order) and put it into new string.</p>
<p>Input:</p>
<pre><code>abbcccdddd
</code></pre>
<p>Output:</p>
<pre><code>dcdbcdabcd
</code></pre>
<p>The code I wrote is:</p>
<pre><code>s = list(sor... | 2 | 2016-10-04T05:52:19Z | 39,871,672 | <p>What about this?
I am making use of in-built python functions to eliminate loops and improve efficiency.</p>
<pre><code>test_str = 'abbcccdddd'
remaining_letters = [1] # dummy initialisation
# sort alphabetically
unique_letters = sorted(set(test_str))
frequencies = [test_str.count(letter) for letter in unique_le... | 0 | 2016-10-05T10:36:26Z | [
"python",
"string",
"python-2.7",
"sorting",
"nested-loops"
] |
Sorting a string to make a new one | 39,845,025 | <p>Here I had to remove the most frequent alphabet of a string(if frequency of two alphabets is same, then in alphabetical order) and put it into new string.</p>
<p>Input:</p>
<pre><code>abbcccdddd
</code></pre>
<p>Output:</p>
<pre><code>dcdbcdabcd
</code></pre>
<p>The code I wrote is:</p>
<pre><code>s = list(sor... | 2 | 2016-10-04T05:52:19Z | 39,873,115 | <p>Since the alphabet will always be a constant 26 characters,
this will work in O(N) and only takes a constant amount of space of 26</p>
<pre><code>from collections import Counter
from string import ascii_lowercase
def sorted_alphabet(text):
freq = Counter(text)
alphabet = filter(freq.get, ascii_lowercase) #... | 1 | 2016-10-05T11:46:12Z | [
"python",
"string",
"python-2.7",
"sorting",
"nested-loops"
] |
Sorting a string to make a new one | 39,845,025 | <p>Here I had to remove the most frequent alphabet of a string(if frequency of two alphabets is same, then in alphabetical order) and put it into new string.</p>
<p>Input:</p>
<pre><code>abbcccdddd
</code></pre>
<p>Output:</p>
<pre><code>dcdbcdabcd
</code></pre>
<p>The code I wrote is:</p>
<pre><code>s = list(sor... | 2 | 2016-10-04T05:52:19Z | 39,873,264 | <p>Your solution involves 26 linear scans of the string and a bunch of unnecessary
conversions to count the frequencies. You can save some work by replacing all those linear scans with a linear count step, another linear repetition generation, then a sort to order your letters and a final linear pass to strip counts: ... | 1 | 2016-10-05T11:54:47Z | [
"python",
"string",
"python-2.7",
"sorting",
"nested-loops"
] |
Pandas groupby - grouping users and counting the type of subscription | 39,845,028 | <p>I'm attempting to use pandas to group members, to count the number of subscription types that a member has purchased and get a total spent per member. Once loaded the data resembles:</p>
<pre><code>df =
Member Nbr Member Name-First Member Name-Last Date-Joined Member Type Amount Add... | 1 | 2016-10-04T05:52:34Z | 39,845,310 | <p>You can first <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html" rel="nofollow"><code>map</code></a> values of column <code>Member Type</code> by dict <code>d</code> and then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.fillna.html" rel="nofollow"><... | 2 | 2016-10-04T06:14:12Z | [
"python",
"pandas",
"group-by",
"pivot-table",
"reshape"
] |
How to make regex that matches a number with commas for every three digits? | 39,845,034 | <p>I am a beginner in Python and in regular expressions and now I try to deal with one exercise, that sound like that:</p>
<blockquote>
<p>How would you write a regex that matches a number with commas for
every three digits? It must match the following:</p>
<p>'42'</p>
<p>'1,234'</p>
<p>'6,368,745'<... | -2 | 2016-10-04T05:53:22Z | 39,845,105 | <p>You can go with this (which is a slightly improved version of what the book specifies):</p>
<pre><code>^\d{1,3}(?:,\d{3})*$
</code></pre>
<p><a href="https://regex101.com/r/amGFa4/2" rel="nofollow">Demo on Regex101</a></p>
| 0 | 2016-10-04T05:58:23Z | [
"python",
"regex"
] |
How to make regex that matches a number with commas for every three digits? | 39,845,034 | <p>I am a beginner in Python and in regular expressions and now I try to deal with one exercise, that sound like that:</p>
<blockquote>
<p>How would you write a regex that matches a number with commas for
every three digits? It must match the following:</p>
<p>'42'</p>
<p>'1,234'</p>
<p>'6,368,745'<... | -2 | 2016-10-04T05:53:22Z | 39,845,263 | <p>The answer in your book seems correct for me. It works on the test cases you have given also. </p>
<pre><code>(^\d{1,3}(,\d{3})*$)
</code></pre>
<p>The <code>'^'</code> symbol tells to search for integers at the start of the line. <code>d{1,3}</code> tells that there should be at least one integer but not more th... | 1 | 2016-10-04T06:10:01Z | [
"python",
"regex"
] |
What is the . symbol in matlab, how to change it to python | 39,845,102 | <pre><code>Xnorm = (X-repmat(mu,m,1))./repmat(sigma,m,1);
</code></pre>
<p>what does the . here do? And if I want to change it to the python, what should I do? </p>
| 0 | 2016-10-04T05:58:08Z | 39,845,186 | <p>IN MATLAB it's called <a href="https://www.mathworks.com/help/fixedpoint/ref/rdivide.html" rel="nofollow"><code>rdivide</code> - right array element-wise division</a>.</p>
<pre><code>>> [1,2;3,4]./[5,6;7,8]
ans =
0.2000 0.3333
0.4286 0.5000
</code></pre>
<p>Python equivalent is <a href="http:... | 0 | 2016-10-04T06:04:09Z | [
"python",
"matlab"
] |
What is the . symbol in matlab, how to change it to python | 39,845,102 | <pre><code>Xnorm = (X-repmat(mu,m,1))./repmat(sigma,m,1);
</code></pre>
<p>what does the . here do? And if I want to change it to the python, what should I do? </p>
| 0 | 2016-10-04T05:58:08Z | 39,845,223 | <p>It means element wise division
Matlab Example</p>
<p><a href="http://in.mathworks.com/help/fixedpoint/ref/rdivide.html;jsessionid=e4b080e387b57aaf3b1e526a26d9" rel="nofollow">http://in.mathworks.com/help/fixedpoint/ref/rdivide.html;jsessionid=e4b080e387b57aaf3b1e526a26d9</a></p>
<p>Divide elementwise Python Equiva... | 0 | 2016-10-04T06:06:30Z | [
"python",
"matlab"
] |
What is the . symbol in matlab, how to change it to python | 39,845,102 | <pre><code>Xnorm = (X-repmat(mu,m,1))./repmat(sigma,m,1);
</code></pre>
<p>what does the . here do? And if I want to change it to the python, what should I do? </p>
| 0 | 2016-10-04T05:58:08Z | 39,845,591 | <p>In MATLAB you would explicitly replicate elements with that <code>repmat</code> and then do elementwise division with <code>./</code> as also stated in the comments. You could have also used <a href="https://www.mathworks.com/help/matlab/ref/bsxfun.html" rel="nofollow"><code>bsxfun</code></a> for under-the-hood repl... | 1 | 2016-10-04T06:33:44Z | [
"python",
"matlab"
] |
What is the . symbol in matlab, how to change it to python | 39,845,102 | <pre><code>Xnorm = (X-repmat(mu,m,1))./repmat(sigma,m,1);
</code></pre>
<p>what does the . here do? And if I want to change it to the python, what should I do? </p>
| 0 | 2016-10-04T05:58:08Z | 39,852,823 | <p>Element division instead of the default matrix division.</p>
| 0 | 2016-10-04T12:50:39Z | [
"python",
"matlab"
] |
Receiving AssertionError using Flask sqlalchemy and restful | 39,845,187 | <p>I have been stumped and can't seem to figure out why I am receiving an AssertionError. I am currently working on a rest api using the flask_restful lib. I am querying by:</p>
<pre><code>@staticmethod
def find_by_id(id, user_id):
f = File.query.filter_by(id=id).first() #Error is happening here
if f is not ... | 0 | 2016-10-04T06:04:11Z | 39,848,104 | <p>Are you sure you want to have an assignment operator instead of comparison in your filter. Try replacing = with == and see if it solves your problem. </p>
<pre><code>f = File.query.filter_by(id == id).first()
</code></pre>
<p>Hannu</p>
| 0 | 2016-10-04T08:56:25Z | [
"python",
"flask",
"sqlalchemy",
"flask-sqlalchemy",
"flask-restful"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.