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 |
|---|---|---|---|---|---|---|---|---|---|
Obtaining latitude and longitude of multiple locations using Geopy | 37,608,811 | <p>I have been importing a csv dataset containing multiple addresses. I want to get the latitude and longitude of these places and write those to a new csv file along with the original address. I have been trying to use Geopy from python to achieve this. Given below is the code:</p>
<pre><code>import csv
##from time i... | 1 | 2016-06-03T07:47:50Z | 37,609,101 | <p>You are forgetting that location can be None at times due to various reasons including the geocoding service not having geo spatial data for the given address.</p>
<p>simpley do</p>
<pre><code>location = geolocator.geocode(address_new)
if location:
lat=location.latitude
lon=location.longitude
else :
la... | 1 | 2016-06-03T08:03:07Z | [
"python",
"csv",
"geopy"
] |
flask can't connect sqlalchemy | 37,608,830 | <p>I want to connect sql using sqlalchemy on flask</p>
<p>but it can't</p>
<p>there is a error</p>
<pre><code>sqlalchemy.exc.OperationalError: (_mysql_exceptions.OperationalError) (1049, "Unknown database 'alchemy_new'")
</code></pre>
<p>I can't solve this problem.</p>
<pre><code># -*- coding:utf-8 -*-
from flask... | -2 | 2016-06-03T07:48:58Z | 37,609,585 | <p>First of all I have no idea why password shall be unique ;)
Secondly it looks like sqlalchemy doesn't recognize you connection string.
Try:</p>
<pre><code>app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql:////root:12345@localhost/catchat'
</code></pre>
| 0 | 2016-06-03T08:30:32Z | [
"python",
"flask",
"sqlalchemy",
"flask-sqlalchemy"
] |
flask can't connect sqlalchemy | 37,608,830 | <p>I want to connect sql using sqlalchemy on flask</p>
<p>but it can't</p>
<p>there is a error</p>
<pre><code>sqlalchemy.exc.OperationalError: (_mysql_exceptions.OperationalError) (1049, "Unknown database 'alchemy_new'")
</code></pre>
<p>I can't solve this problem.</p>
<pre><code># -*- coding:utf-8 -*-
from flask... | -2 | 2016-06-03T07:48:58Z | 37,615,460 | <p>According to the following codeï¼
<code>app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:12345@localhost/catchat'
</code>
Your database is 'catchat'.Please create it.</p>
<p><code>mysql -u root -p12345
create database catchat;
</code></p>
<p>And create table before use it.</p>
<p><code>db.create_all()
</cod... | 0 | 2016-06-03T13:17:07Z | [
"python",
"flask",
"sqlalchemy",
"flask-sqlalchemy"
] |
How to assign to ManytoMany None object? | 37,608,938 | <p>I have a task to modify queryset after that a recieved its from DB and before context.
I do the next:</p>
<pre><code>products = list(qs) #create a copy of qs to avoid modifiyng in DB
for product in products:
access_table = FieldAccess.objects.filter(user=user, product=product.pk).values_list('access', flat=True... | 0 | 2016-06-03T07:54:00Z | 37,609,159 | <p>The way to reset a <code>ManyToManyField</code> field is to use <code>clear</code>. <a href="https://docs.djangoproject.com/en/1.9/topics/db/examples/many_to_many/" rel="nofollow">Django docs</a></p>
<pre><code>value = getattr(product, fields[0], None)
if value and isinstance(value, ManyToManyField): value.clear()... | -1 | 2016-06-03T08:05:45Z | [
"python",
"django",
"django-models"
] |
How to assign to ManytoMany None object? | 37,608,938 | <p>I have a task to modify queryset after that a recieved its from DB and before context.
I do the next:</p>
<pre><code>products = list(qs) #create a copy of qs to avoid modifiyng in DB
for product in products:
access_table = FieldAccess.objects.filter(user=user, product=product.pk).values_list('access', flat=True... | 0 | 2016-06-03T07:54:00Z | 37,609,259 | <p>ManyToManyFields perform some magic under the hood. You cannot simply assign <code>None</code>, because it expects an Iterable. You would have to assign an empty list <code>[]</code> to ManyToManyFields instead, but this actually performs a database query and is probably not what you want!</p>
<p>You could try to w... | -1 | 2016-06-03T08:11:13Z | [
"python",
"django",
"django-models"
] |
Python ToDo-app GUI with text clear | 37,609,009 | <p>I've already did a cool little CLI To-Do app in python, and now I'm trying to build a basic GUI around it. The main buttons, field in place, and yesterday I've figured out how to redirect the return string from my Todo class to the text area.
My problem now is how to clear the text area? Currently if I press the 'Vi... | 0 | 2016-06-03T07:57:18Z | 37,612,483 | <p>The contents you are trying to delete is not <code>Text</code>'s contents. It's your <code>Entry</code> widget.</p>
<pre><code>def entry(self):
entry_field = tk.Entry(self.mainframe, bd=2)
entry_field.grid(row=1, column=0, sticky='nwse', padx=10, pady=10)
entry_field.insert(0, 'Enter task OR number of a... | 1 | 2016-06-03T10:53:13Z | [
"python",
"user-interface",
"text",
"tkinter",
"clear"
] |
python svgwrite can't add class attribute? | 37,609,321 | <p>I'm trying to correct the following code:</p>
<pre><code>import svgwrite
dwg = svgwrite.Drawing('test.svg', profile='tiny')
dwg.add(dwg.circle((10, 0), 20 , fill='rgb(0,0,255)', id='rrr', class='#t'))
dwg.save()
</code></pre>
<p>I get the following error:</p>
<pre><code>dwg.add(dwg.circle((10, 0), 20 , fill='rgb(... | 1 | 2016-06-03T08:15:08Z | 37,609,847 | <p>According to the <a href="http://pythonhosted.org/svgwrite/classes/base.html" rel="nofollow">svgwrite documentation</a> you must add a trailing underscore to attributes which are python keywords. So the correct code would be:</p>
<pre><code>dwg.add(dwg.circle((10, 0), 20 , fill='rgb(0,0,255)', id='rrr', class_='#t'... | 1 | 2016-06-03T08:44:39Z | [
"python",
"svg",
"svgwrite"
] |
Python async socket recv not working | 37,609,332 | <p>Here is a simple client which connects and sends a text message:</p>
<pre><code>class Client(asyncore.dispatcher):
def __init__(self, host, port):
asyncore.dispatcher.__init__(self)
self.create_socket()
self.connect( (host, port) )
self.buffer = bytes("hello world", 'ascii')
... | 1 | 2016-06-03T08:15:47Z | 37,609,872 | <p>First of all, you need two handlers: One for the server socket (where you expect only <code>accept</code>), and one for the actual communication sockets. In addition, you can only call <code>read</code> once in <code>handle_read</code>; if you call it twice, the second call may block, and that's not allowed in async... | 1 | 2016-06-03T08:45:47Z | [
"python",
"sockets",
"python-3.x",
"asyncsocket"
] |
python load TFS dll's | 37,609,471 | <p>I try to load the Microsoft.TeamFundation dlls to check out a file with the python script</p>
<pre><code>import os
import sys
import clr
clr.AddReference("Microsoft.TeamFoundation.VersionControl.Client")
clr.AddReference("Microsoft.TeamFoundation.Client")
clr.AddReference('TfsCheckout')
from Microsoft.TeamFound... | 0 | 2016-06-03T08:23:37Z | 37,650,199 | <p>A TFS server can be accessed via the team foundation client which is shipped with Visual Studio and Team Explorer. You can have a look at the <a href="https://help.timecockpit.com/html/a4c60754-23c4-47a9-91c6-bf99652ccd7d.htm#Prerequisites" rel="nofollow">TFS signal tracker prerequisites</a> should you require addit... | 0 | 2016-06-06T05:38:08Z | [
"python",
"dll",
"tfs"
] |
python load TFS dll's | 37,609,471 | <p>I try to load the Microsoft.TeamFundation dlls to check out a file with the python script</p>
<pre><code>import os
import sys
import clr
clr.AddReference("Microsoft.TeamFoundation.VersionControl.Client")
clr.AddReference("Microsoft.TeamFoundation.Client")
clr.AddReference('TfsCheckout')
from Microsoft.TeamFound... | 0 | 2016-06-03T08:23:37Z | 37,652,099 | <p>I have solved the problem in that way:</p>
<p>I have added an assembly resolve in the TfsCheckout.dll what is a self written helper dll from me. In the Phyton script I only load the TfsCheckout and the dll itself loads the needed references. The assembly resolve from .net site is no problem...</p>
| 0 | 2016-06-06T07:47:32Z | [
"python",
"dll",
"tfs"
] |
Nested if's - what's more Pythonic? | 37,609,505 | <p>Both functions do the same thing. </p>
<pre><code>def function1(self):
a = self.get_a()
b = self.get_b()
c = self.get_c()
r = None
if a:
r = a
if b:
r = b
if c:
r = c
else:
print("c not set.")
else:
... | 1 | 2016-06-03T08:25:24Z | 37,609,518 | <p>One of the principals of Pythonic code is "flat is better than nested". On this basis, I'll say <code>function2()</code> is objectively more Pythonic. This can be seen in <a href="https://www.python.org/dev/peps/pep-0020/" rel="nofollow">PEP-20: The Zen of Python</a>:</p>
<blockquote>
<p><strong>The Zen of Python... | 4 | 2016-06-03T08:26:30Z | [
"python",
"if-statement",
"nested",
"indentation",
"pep"
] |
Nested if's - what's more Pythonic? | 37,609,505 | <p>Both functions do the same thing. </p>
<pre><code>def function1(self):
a = self.get_a()
b = self.get_b()
c = self.get_c()
r = None
if a:
r = a
if b:
r = b
if c:
r = c
else:
print("c not set.")
else:
... | 1 | 2016-06-03T08:25:24Z | 37,609,669 | <p>As @Will's answer suggests, flat is better. However the code doesn't look very pretty anyways. How about a more compact type of code? </p>
<p>looking at these quotes from @Will's answer:</p>
<blockquote>
<p>Readability counts.</p>
<p>Beautiful is better than ugly.</p>
</blockquote>
<pre><code>from collecti... | 2 | 2016-06-03T08:35:07Z | [
"python",
"if-statement",
"nested",
"indentation",
"pep"
] |
Nested if's - what's more Pythonic? | 37,609,505 | <p>Both functions do the same thing. </p>
<pre><code>def function1(self):
a = self.get_a()
b = self.get_b()
c = self.get_c()
r = None
if a:
r = a
if b:
r = b
if c:
r = c
else:
print("c not set.")
else:
... | 1 | 2016-06-03T08:25:24Z | 37,610,003 | <p>You can use the evaluation rules of the <code>and</code> and <code>or</code> operators, for example:</p>
<pre><code>>>> None or 4 or None or 5
4
>>> 4 and 5
5
</code></pre>
<p>So you'd have something like:</p>
<pre><code>def function3(self):
a = self.get_a()
b = self.get_b()
c = sel... | 1 | 2016-06-03T08:52:23Z | [
"python",
"if-statement",
"nested",
"indentation",
"pep"
] |
Nested if's - what's more Pythonic? | 37,609,505 | <p>Both functions do the same thing. </p>
<pre><code>def function1(self):
a = self.get_a()
b = self.get_b()
c = self.get_c()
r = None
if a:
r = a
if b:
r = b
if c:
r = c
else:
print("c not set.")
else:
... | 1 | 2016-06-03T08:25:24Z | 37,610,518 | <p>I suggest function_4 displayed below together with the questions (non-idetnically working!) functions and one of DomTomCat's answer:</p>
<pre><code>#! /usr/bin/env python
from __future__ import print_function
from collections import OrderedDict # Only used in function_3
def function_4(self):
"""Iterate over ... | 0 | 2016-06-03T09:18:47Z | [
"python",
"if-statement",
"nested",
"indentation",
"pep"
] |
what is this error: 'matrix' object has no attribute 'diff' | 37,609,555 | <p>when i am trying to run this program it gives Attribute error.
I am new to python so please forgive if i miss anything.Thanks</p>
<pre><code>import math
import numpy as np
from sympy import *
from sympy import diff
import sympy as sp
p=np.matrix([[0],[0],[0],[1]])
pdash=p
zi=Matrix(2, 1, lambda i,j: Symbol('z%d' %... | 1 | 2016-06-03T08:28:58Z | 37,628,784 | <p>As was said in comments, symbolic differentiation cannot be applied to a SymPy matrix object. Apply it to each entry separately. Example: </p>
<pre><code>t1 = Symbol('t1')
jacobian = Matrix(*e.shape, lambda i,j: e[i,j].diff(t1))
</code></pre>
<p>The second line constructs a matrix of the same shape as <code>e</co... | 0 | 2016-06-04T09:48:49Z | [
"python",
"sympy",
"differentiation"
] |
Drop row pandas with a list of argument | 37,609,743 | <p>I would like to drop all the row which are not in a list in pandas DataFrame</p>
<p>For instance, consider this dataframe :</p>
<pre><code>data = {'name': ['Jason', 'Molly', 'Tina', 'Jake', 'Amy'],
'year': [2012, 2012, 2013, 2014, 2014],
'reports': [4, 24, 31, 2, 3]}
df = pd.DataFrame(data, index = ['Coc... | 3 | 2016-06-03T08:39:10Z | 37,609,767 | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.isin.html#pandas.Series.isin"><code>isin</code></a> and pass the list as the arg and invert the condition using <code>~</code>:</p>
<pre><code>In [58]:
names = ['Jason', 'Molly']
df[~df['name'].isin(names)]
Out[58]:
... | 5 | 2016-06-03T08:40:24Z | [
"python",
"list",
"pandas",
"dataframe"
] |
Drop row pandas with a list of argument | 37,609,743 | <p>I would like to drop all the row which are not in a list in pandas DataFrame</p>
<p>For instance, consider this dataframe :</p>
<pre><code>data = {'name': ['Jason', 'Molly', 'Tina', 'Jake', 'Amy'],
'year': [2012, 2012, 2013, 2014, 2014],
'reports': [4, 24, 31, 2, 3]}
df = pd.DataFrame(data, index = ['Coc... | 3 | 2016-06-03T08:39:10Z | 37,609,770 | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.isin.html" rel="nofollow"><code>isin</code></a> with inverting boolean mask by <code>~</code>. I think better is use other name of list as <code>List</code>, e.g. <code>l</code> or <code>names</code> as use <code>EdChum</code>:</p>
... | 2 | 2016-06-03T08:40:31Z | [
"python",
"list",
"pandas",
"dataframe"
] |
using functools.lru_cache on functions with constant but non-hashable objects | 37,609,772 | <p>Is it possible to use <code>functools.lru_cache</code> for caching a partial function created by <code>functools.partial</code>?</p>
<p>My problem is a function that takes hashable parameters and contant, non-hashable objects such as numpy arrays.</p>
<p>consider this toy example:</p>
<pre><code>import numpy as n... | 0 | 2016-06-03T08:40:43Z | 37,611,009 | <p>As the array is constant you can use a wrapper around the actual lru cached function and simply pass the key value to it:</p>
<pre><code>from functools import lru_cache, partial
import numpy as np
def lru_wrapper(array=None):
@lru_cache(maxsize=None)
def foo(key):
return '%s:' % key, array
ret... | 1 | 2016-06-03T09:43:45Z | [
"python",
"python-3.x"
] |
How to create an 'contact book' in python using dictionaries? | 37,609,797 | <p>I'm trying to create an contact book indexed by 'nickname' that allows the user to save a persons name, address and number. But I don't quite understand how to do it using dictionaries, if I had it my way I would just use a list.
e.g</p>
<pre><code>myList = [["Tom","1 Fairylane", "911"],["Bob","2 Fairylane", "08008... | 1 | 2016-06-03T08:42:08Z | 37,609,860 | <p>Keys in a dictionary a unique. So if you have a list of contacts with no name twice you can use code like this:</p>
<pre><code>contacts = {}
contacts['Tom'] = ["1 Fairylane", 911]
contacts['Bob'] = ["2 Fairylane", 0800838383]
</code></pre>
<p>so adding data to a dictionary is based on the access operator <code>[]<... | 2 | 2016-06-03T08:45:19Z | [
"python"
] |
How to create an 'contact book' in python using dictionaries? | 37,609,797 | <p>I'm trying to create an contact book indexed by 'nickname' that allows the user to save a persons name, address and number. But I don't quite understand how to do it using dictionaries, if I had it my way I would just use a list.
e.g</p>
<pre><code>myList = [["Tom","1 Fairylane", "911"],["Bob","2 Fairylane", "08008... | 1 | 2016-06-03T08:42:08Z | 37,609,884 | <p>You can start with this: </p>
<pre><code>my_dict = {"Tom": {"name": "Tom Jones", "address": "1 Fairylane", "phone": "911"},
"Bob": {"name": "Bob Marley", "address": "2 Fairylane", "phone": "0800838383"}
}
</code></pre>
<p>then you can simply access records using</p>
<pre><code>my_dict["Tom"... | 3 | 2016-06-03T08:46:11Z | [
"python"
] |
How to create an 'contact book' in python using dictionaries? | 37,609,797 | <p>I'm trying to create an contact book indexed by 'nickname' that allows the user to save a persons name, address and number. But I don't quite understand how to do it using dictionaries, if I had it my way I would just use a list.
e.g</p>
<pre><code>myList = [["Tom","1 Fairylane", "911"],["Bob","2 Fairylane", "08008... | 1 | 2016-06-03T08:42:08Z | 37,609,950 | <p>As mentioned by DomTomCat you could set the dictionary key to be the first name, and the data then contained in a list. One thing to note is that dictionaries are unsorted. So whilst they provide a very fast search (they are essentially a hash table) for a key it will require you to do a bit of work if you wish to ... | 2 | 2016-06-03T08:49:41Z | [
"python"
] |
Python -- Optimize system of inequalities | 37,609,820 | <p>I am working on a program in Python in which a small part involves optimizing a system of equations / inequalities. Ideally, I would have wanted to do as can be done in Modelica, write out the equations and let the solver take care of it. </p>
<p>The operation of solvers and linear programming is a bit out of my co... | 3 | 2016-06-03T08:43:22Z | 37,618,824 | <p>Z3 is the most powerful solver I have found for such flexible systems of equations. Z3 is an excellent choice now that it is released under the MIT license.</p>
<p>There are a lot of different types of tools with overlapping use cases. You mentioned linear programming -- there are also theorem provers, SMT solver... | 1 | 2016-06-03T15:58:23Z | [
"python",
"z3",
"solver",
"z3py"
] |
How do I get indices around certain values in an array | 37,609,914 | <p>So I came accros this tiny but tricky problem.</p>
<p>I have an array of indices of error_images, something like this:</p>
<pre><code>error_frames = [15,27,34,204,205]
</code></pre>
<p>Now I am using a for loop to iterate over these frames and add 10 frames in prior and after the erroneous frames in order to get ... | 0 | 2016-06-03T08:47:42Z | 37,610,066 | <p>Like so maybe:</p>
<pre><code>if any(y in error_frames for y in xrange(x-3, x+4)):
...
</code></pre>
<p>You can consider creating a <code>set</code> out of your <code>error_frames</code> to improve the time complexity of the contains-check:</p>
<pre><code>error_frame_set = set(error_frames)
</code></pre>
<p>... | 1 | 2016-06-03T08:56:08Z | [
"python",
"arrays",
"for-loop"
] |
How do I get indices around certain values in an array | 37,609,914 | <p>So I came accros this tiny but tricky problem.</p>
<p>I have an array of indices of error_images, something like this:</p>
<pre><code>error_frames = [15,27,34,204,205]
</code></pre>
<p>Now I am using a for loop to iterate over these frames and add 10 frames in prior and after the erroneous frames in order to get ... | 0 | 2016-06-03T08:47:42Z | 37,610,104 | <p>Perhaps something like this:</p>
<pre><code>error_frames_set = set(error_frames)
delta = 3
for x in error_sequence:
slow_frames = set(x + offset for offset in range(-delta, delta+1))
if slow_frames.intersection(error_frames_set):
cv2.imshow('Sequence', frames[x])
cv2.putText(frames[x], "Err... | 1 | 2016-06-03T08:58:09Z | [
"python",
"arrays",
"for-loop"
] |
Ignore SonarQube warnings in python | 37,609,940 | <p>How can I ignore SonarQube warnings in Python code</p>
<p>In Java, I can use</p>
<pre><code>@SuppressWarnings("squid:S1166")
</code></pre>
<p>Where the ID is the SonarQube rule ID. But what syntax should I use in Python?</p>
<p>I've tried</p>
<pre><code># noinspection python:S1313
</code></pre>
<p>but it didn'... | 1 | 2016-06-03T08:49:11Z | 37,613,205 | <p>I believe the only syntax supported for Python (assuming it <em>is</em> supported) is the NOSONAR comment, so <code>#NOSONAR</code> at the end of the line where you want to ignore issues.</p>
<p>Unfortunately, this is a global issue suppression: it kills <em>all</em> issues on the line, not just those from a specif... | 1 | 2016-06-03T11:28:11Z | [
"python",
"sonarqube"
] |
python tkinter drawing program | 37,610,001 | <p>ive got 2 seperate programs, both i got from stackoverflow, and both works on their own here is the first:</p>
<pre><code> import tkinter as tk
import os
w, h = 500, 200
# Add a couple widgets. We're going to put pygame in `embed`.
root = tk.Tk()
embed = tk.Frame(root, width=w, height=h)
... | -1 | 2016-06-03T08:52:20Z | 37,643,055 | <p>I have actualy figured the answer out myself, the reason i used pygame is becouse i didnt think you could use tkinter, but i made a program that uses tkinter and actuely draws quite good (maybe better than pygame) i will add this program</p>
<pre><code> from tkinter import *
b1 = "up"
xold, yold = None... | 0 | 2016-06-05T14:33:36Z | [
"python",
"user-interface",
"python-3.x",
"tkinter",
"pygame"
] |
Default value of kwarg 'compression' in create_dataset() of h5py | 37,610,028 | <p>what is the default value of the compression keyword argument of the function create_dataset in h5py, i.e. what value do I have to pass to get no compression?</p>
<p>I'm asking because I would like to have a flag which turns the compression on/off and I'd like to avoid to have a case switch every time I call the fu... | 0 | 2016-06-03T08:53:26Z | 37,844,991 | <p>As <a href="http://stackoverflow.com/questions/37610028/default-value-of-kwarg-compression-in-create-dataset-of-h5py#comment62703712_37610028">Ilja Everilä</a> pointed out, the default compression keyword for no compression is <code>None</code>.</p>
| 0 | 2016-06-15T20:18:08Z | [
"python",
"compression",
"hdf5",
"h5py"
] |
Odoo Automated Actions how can you iterate through One2Many record to add desired values to a new object using python expression? | 37,610,080 | <p>I have a situation like this:</p>
<p>I want to create a Customer Invoice with 3 invoice lines: one for Customer payment, one for payment processing fee and one for a commission.</p>
<p>When the invoice is created, I've got an automated action set up to create 3 separate Supplier invoices, one per invoice line. Tha... | 1 | 2016-06-03T08:56:44Z | 37,610,367 | <p>The "for" declaration is ok, the line below is not.</p>
<p><code>if line.product_id = 2:</code> should be <code>if line.product_id == 2:</code> with 2 <code>=</code> since is a comparison.</p>
<p>Moreover, you could have errors above that line. You should provide the whole code and the whole traceback.</p>
| 0 | 2016-06-03T09:11:26Z | [
"python",
"openerp",
"odoo-8"
] |
Replace certain column with `filter(like = "")` in Pandas | 37,610,140 | <p>Sometimes, I would manipulate some columns of the dataframe and re-change it. </p>
<p>For example, one dataframe <strong>df</strong> has 6 columns like this: </p>
<blockquote>
<p>A, B1, B2, B3, C, D </p>
</blockquote>
<p>And I want to change the values in the columns (B1,B2,B3) transform into (B1*A, B2*A, B... | 1 | 2016-06-03T09:00:32Z | 37,610,215 | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.contains.html" rel="nofollow"><code>str.contains</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>boolean indexing</code></a>:</p>
<pre><code>cols = df.column... | 1 | 2016-06-03T09:04:05Z | [
"python",
"python-2.7",
"pandas",
"filter",
"dataframe"
] |
Replace certain column with `filter(like = "")` in Pandas | 37,610,140 | <p>Sometimes, I would manipulate some columns of the dataframe and re-change it. </p>
<p>For example, one dataframe <strong>df</strong> has 6 columns like this: </p>
<blockquote>
<p>A, B1, B2, B3, C, D </p>
</blockquote>
<p>And I want to change the values in the columns (B1,B2,B3) transform into (B1*A, B2*A, B... | 1 | 2016-06-03T09:00:32Z | 37,610,631 | <p>you have almost done it:</p>
<pre><code>In [136]: df.loc[:, df.filter(regex=r'^B').columns] = df.loc[:, df.filter(regex=r'^B').columns].mul(df.A, axis=0)
In [137]: df
Out[137]:
A B1 B2 B3 B4 F
0 1 4 7 1 5 7
1 2 10 16 6 6 4
2 3 18 27 15 18 3
</code></pre>
| 1 | 2016-06-03T09:24:58Z | [
"python",
"python-2.7",
"pandas",
"filter",
"dataframe"
] |
POST with Python not working | 37,610,146 | <p>I've read many posts on the Internet, but none of them seems to work for me.
I have a web form which requires an username and a password in order to log in. Here's a snippet of code among those I tried so far</p>
<pre><code>params = urllib.parse.urlencode({'login' : 'user', 'password' : 'pwd'})
f = urllib.request.u... | 0 | 2016-06-03T09:01:01Z | 37,610,257 | <p>The correct usage is</p>
<pre><code>f = urllib.request.urlopen("https://example.com/login.php", data=params)
</code></pre>
<p>From <a href="https://docs.python.org/3.0/library/urllib.request.html#urllib.request.urlopen" rel="nofollow"><code>urllib.request</code> documentation</a>:</p>
<blockquote>
<p><em>data</... | 1 | 2016-06-03T09:06:25Z | [
"python",
"post",
"http-post",
"python-3.5"
] |
POST with Python not working | 37,610,146 | <p>I've read many posts on the Internet, but none of them seems to work for me.
I have a web form which requires an username and a password in order to log in. Here's a snippet of code among those I tried so far</p>
<pre><code>params = urllib.parse.urlencode({'login' : 'user', 'password' : 'pwd'})
f = urllib.request.u... | 0 | 2016-06-03T09:01:01Z | 37,610,308 | <p>According to <a href="https://docs.python.org/2.7/library/urllib.html#examples" rel="nofollow">the documentation for urllib</a>, you need to pass keyword argument <code>data</code> (or the second positional argument) to <code>urlopen</code>, instead of adding them to the url:</p>
<pre><code>import urllib
params = u... | 1 | 2016-06-03T09:09:00Z | [
"python",
"post",
"http-post",
"python-3.5"
] |
Python - Get the min coordinate element of a 2d numpy array | 37,610,275 | <p>I have this 2d numpy array: <code>[[0,2],[0,3],[0,1],[1,0]]</code>. These elements represent points in <code>x</code> and <code>y</code> axes. So, for example, in <code>[0,2]</code> 0 is the <code>x</code> and 2 is the <code>y</code>.</p>
<p>I would like to get the point with the min <code>x</code> and min <code>y<... | 0 | 2016-06-03T09:07:16Z | 37,610,337 | <p>You can use the NumPy built-in <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.lexsort.html" rel="nofollow"><code>np.lexsort</code></a> to do such a sorting, like so -</p>
<pre><code>xy[np.lexsort(xy.T[::-1])[0]]
</code></pre>
<p><code>lexsort</code> gets the sorted indices that respects ... | 2 | 2016-06-03T09:10:22Z | [
"python",
"numpy"
] |
Python - Get the min coordinate element of a 2d numpy array | 37,610,275 | <p>I have this 2d numpy array: <code>[[0,2],[0,3],[0,1],[1,0]]</code>. These elements represent points in <code>x</code> and <code>y</code> axes. So, for example, in <code>[0,2]</code> 0 is the <code>x</code> and 2 is the <code>y</code>.</p>
<p>I would like to get the point with the min <code>x</code> and min <code>y<... | 0 | 2016-06-03T09:07:16Z | 37,610,488 | <p>You can first find the min of <code>x</code>, then find the min of <code>y</code> for pair where <code>x</code> equals the min of <code>x</code>:</p>
<pre><code>np.min(xy[xy[:, 0] == np.min(xy[:, 0])], 0)
</code></pre>
<pre><code>In [1]: xy
Out[1]:
array([[0, 2],
[0, 3],
[0, 1],
[1, 0]])
I... | 3 | 2016-06-03T09:17:15Z | [
"python",
"numpy"
] |
Intercest dataframes in python using pandas | 37,610,383 | <p>I have two DataFrames: A and B.
A comtains two columns: Number and Letter, B also contains two columns: Number1 and Number2, and Number contains same data as in both Number1 and Number2.
How can I make a ned dataframe which will have column which contains Number1, Number2 and column with its Letter?</p>
<pre><code>... | 1 | 2016-06-03T09:12:18Z | 37,610,425 | <p>you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.html" rel="nofollow">stack()</a> in conjunction with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.isin.html" rel="nofollow">isin()</a>:</p>
<pre><code>In [109]: A[A['Number'].isin(B.s... | 2 | 2016-06-03T09:14:10Z | [
"python",
"pandas"
] |
Disable python logger output | 37,610,533 | <p>I have python script for <strong>Python 2.7.10</strong> that looks like this:</p>
<pre><code>import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
logger.addHandler(logging.StreamHandler())
logger.info("Hello, world!");
</code></pre>
<p>Is it possible to somehow run this script <strong>from Pow... | 1 | 2016-06-03T09:19:41Z | 37,610,714 | <p>You need to redirect all output to null:</p>
<pre><code>command > nul 2>&1
</code></pre>
<p>or </p>
<p><code>2> nul</code></p>
<p>to kill stderr</p>
<p>Finally to outputfile:</p>
<pre><code>command > a.txt 2>&1
</code></pre>
<p>In powershell:</p>
<pre><code>2>&1>$null
2>&a... | 2 | 2016-06-03T09:28:24Z | [
"python",
"windows",
"logging"
] |
No input possible after tk | 37,610,608 | <p>If have this piece of code:</p>
<pre><code>import Tkinter as tk
import tkFileDialog
menu = tk.Tk()
res = tkFileDialog.askopenfilename() # un-/comment this line
label = tk.Label(None, text="abc")
label.grid(row=0, column=0, sticky=tk.W)
entry = tk.Entry(None)
entry.grid(row=0, column=1, sticky=tk.EW)
res = menu.ma... | -1 | 2016-06-03T09:23:27Z | 37,610,867 | <p><code>askopenfilename</code>has it's own event loop. The programm stops, until you selected a filename, and continues afterwards.</p>
| -1 | 2016-06-03T09:36:35Z | [
"python",
"tkinter",
"entry"
] |
No input possible after tk | 37,610,608 | <p>If have this piece of code:</p>
<pre><code>import Tkinter as tk
import tkFileDialog
menu = tk.Tk()
res = tkFileDialog.askopenfilename() # un-/comment this line
label = tk.Label(None, text="abc")
label.grid(row=0, column=0, sticky=tk.W)
entry = tk.Entry(None)
entry.grid(row=0, column=1, sticky=tk.EW)
res = menu.ma... | -1 | 2016-06-03T09:23:27Z | 37,615,691 | <p>I've seen reports of this before, I think it's a known bug on windows. You need to let mainloop start before you open a dialog.</p>
<p>If you want the dialog to appear when the app first starts up you can use <code>after</code> or <code>after_idle</code> to have it run after <code>mainloop</code> starts up.</p>
<p... | 1 | 2016-06-03T13:28:03Z | [
"python",
"tkinter",
"entry"
] |
Issues with Pandas Timeseries Resample | 37,610,893 | <p>I'm using python 3.5.1 and Pandas 0.18.0 and trying to use this <a href="http://nbviewer.jupyter.org/github/changhiskhan/talks/blob/master/pydata2012/pandas_timeseries.ipynb" rel="nofollow">notebook</a> to modify financial tick data as the exercises are of interest to me:</p>
<p>I'm having issues with some of the c... | 1 | 2016-06-03T09:38:10Z | 37,611,017 | <p>There is problem <code>spaces</code> in column names.</p>
<pre><code>print (data.columns)
Index(['Timestamp', ' Open', ' High', ' Low', ' Last', ' Volume',
' NumberOfTrades', ' BidVolume', ' AskVolume'],
dtype='object')
</code></pre>
<p>You can <a href="http://pandas.pydata.org/pandas-docs/stable/gene... | 1 | 2016-06-03T09:44:04Z | [
"python",
"csv",
"pandas",
"dataframe",
"resampling"
] |
__metaclass__ not worked when create class with type("Test", (Base,), {'__metaclass__':Meta, ...}) | 37,610,894 | <pre><code>cls = type("Test", (Base,), {"__metaclass__": Meta, "a": 1, ...})
</code></pre>
<p>I want to make some check for the attrs in the 3rd argument with Meta class, but this seem not worked, is there any other method?</p>
| -2 | 2016-06-03T09:38:12Z | 37,611,046 | <p><code>Meta</code>-class is a subclass of <code>type</code>. So creating a type of a metaclass is calling the meta class:</p>
<pre><code>cls = Meta("Test", (Base,), {"a": 1, ...})
</code></pre>
| 3 | 2016-06-03T09:45:36Z | [
"python",
"metaclass"
] |
__metaclass__ not worked when create class with type("Test", (Base,), {'__metaclass__':Meta, ...}) | 37,610,894 | <pre><code>cls = type("Test", (Base,), {"__metaclass__": Meta, "a": 1, ...})
</code></pre>
<p>I want to make some check for the attrs in the 3rd argument with Meta class, but this seem not worked, is there any other method?</p>
| -2 | 2016-06-03T09:38:12Z | 37,611,233 | <p>You should create your <code>Test</code> class by calling the <code>Meta</code> (a.k.a. <code>type.__class__.__new__(Meta, "Test", (Base,), {"__metaclass__": Meta, "a": 1})</code>.</p>
<p>If you have a dictionary with possible <code>__metaclass__</code>, you can use the following code:</p>
<pre><code>members = {"_... | 0 | 2016-06-03T09:54:13Z | [
"python",
"metaclass"
] |
3D parametric curve in Matplotlib does not respect zorder. Workaround? | 37,611,023 | <p>I am designing a three-dimensional illustration using Matplotlib. All is working nicely, except that the (red) parametric curve gets the wrong zorder while the (green) parametric surface is drawn completely correctly.</p>
<p>Output generated by code below:
<img src="http://i.stack.imgur.com/78oDL.png" alt="Output ... | 1 | 2016-06-03T09:44:19Z | 37,612,070 | <p><code>Axes3D</code> ignores <code>zorder</code> and draws all artists in the order it thinks they should be. However, you may set <code>zorder=0</code> for red line and <code>zorder=-1</code> for green surface (or vice-versa) to put they behind right blue panel.</p>
<p>My result:</p>
<p><a href="http://i.stack.img... | 2 | 2016-06-03T10:33:40Z | [
"python",
"matplotlib",
"mplot3d"
] |
3D parametric curve in Matplotlib does not respect zorder. Workaround? | 37,611,023 | <p>I am designing a three-dimensional illustration using Matplotlib. All is working nicely, except that the (red) parametric curve gets the wrong zorder while the (green) parametric surface is drawn completely correctly.</p>
<p>Output generated by code below:
<img src="http://i.stack.imgur.com/78oDL.png" alt="Output ... | 1 | 2016-06-03T09:44:19Z | 37,642,319 | <p>After some more trial and error, I found a solution. <em>If</em> the right plane is drawn using <code>plot_surface</code> <em>and</em> I change the zorder on the red curve, matplotlib gets the overall order of objects right. Funny enough, the color of the planes changes slightly whether I draw them via <code>PolyC... | 1 | 2016-06-05T13:13:53Z | [
"python",
"matplotlib",
"mplot3d"
] |
Attempting to click a button in Python using Selenium WebDriver (Firefox) | 37,611,025 | <p>I am attempting to click a button on a html page using Python and selenium web driver.</p>
<p>This is the source code of the page <a href="http://pastebin.com/112g1Gje" rel="nofollow">http://pastebin.com/112g1Gje</a>.</p>
<p>I believe the relevant portion is literally at the end unless I am absolutely mistaken....... | 0 | 2016-06-03T09:44:25Z | 37,611,325 | <p>driver.find_element_by_classname("btn").click() works</p>
| 0 | 2016-06-03T09:58:09Z | [
"python",
"selenium",
"elements",
"clicking"
] |
Attempting to click a button in Python using Selenium WebDriver (Firefox) | 37,611,025 | <p>I am attempting to click a button on a html page using Python and selenium web driver.</p>
<p>This is the source code of the page <a href="http://pastebin.com/112g1Gje" rel="nofollow">http://pastebin.com/112g1Gje</a>.</p>
<p>I believe the relevant portion is literally at the end unless I am absolutely mistaken....... | 0 | 2016-06-03T09:44:25Z | 37,613,605 | <p>Try </p>
<pre><code>driver.find_element_by_xpath("//*[text()='Open Message Modal']").click()
</code></pre>
<p>Happy Coding :)</p>
| 0 | 2016-06-03T11:47:36Z | [
"python",
"selenium",
"elements",
"clicking"
] |
Attempting to click a button in Python using Selenium WebDriver (Firefox) | 37,611,025 | <p>I am attempting to click a button on a html page using Python and selenium web driver.</p>
<p>This is the source code of the page <a href="http://pastebin.com/112g1Gje" rel="nofollow">http://pastebin.com/112g1Gje</a>.</p>
<p>I believe the relevant portion is literally at the end unless I am absolutely mistaken....... | 0 | 2016-06-03T09:44:25Z | 37,613,784 | <p>I think you forgot to code a button that opens that message-modal. Better create that button first like.</p>
<pre><code><button class="btn" id="btn-message-modal" data-toggle="modal" data-target="#message-modal"> Open Message Modal</btn>\
</code></pre>
<p>Then try this:</p>
<p>driver.find_element_by_i... | 0 | 2016-06-03T11:56:48Z | [
"python",
"selenium",
"elements",
"clicking"
] |
Django REST Framework - Adding 2 PKs in URL | 37,611,248 | <p>I am designing a REST API for an application that has both companies and departments. Some number of users can be members of a company. This leads to the following API structure:</p>
<p><code>/companies/</code> - Can GET, POST.</p>
<p><code>/companies/<pk>/</code> - Can GET, POST, PUTCH, PATCH, DELETE.</p>
... | 0 | 2016-06-03T09:54:47Z | 37,612,040 | <p>Use different names for parameters in you url:</p>
<pre><code>/companies/<company_pk>/membership/<membership_pk>/
</code></pre>
<p>And in you ViewSet add <code>lookup_field</code> and <code>lookup_url_kwarg</code> to point to company pk field/parameter:</p>
<pre><code>class CompanyViewSet(viewsets.Mod... | 0 | 2016-06-03T10:32:14Z | [
"python",
"django",
"rest",
"django-rest-framework"
] |
How deal with 2D array in Python? | 37,611,360 | <p>I want to have a 2D array, the first Parametre is the name of student and the second one is his result.</p>
<p>i try this :</p>
<pre><code>listStudentResult = []
listStudentResult.append([])
listStudentResult[0].append("Alex")
listOfasinEan[0].append(20)
lisStudentResult.append([])
listStudentResult[1].append(Pa... | 0 | 2016-06-03T09:59:45Z | 37,611,459 | <p>Use dictionaries:</p>
<pre><code>listStudentResult = []
listStudentResult.append({"Alex": 20})
listStudentResult.append({"Paul": 15})
</code></pre>
| 2 | 2016-06-03T10:05:22Z | [
"python",
"python-2.7",
"multidimensional-array"
] |
How deal with 2D array in Python? | 37,611,360 | <p>I want to have a 2D array, the first Parametre is the name of student and the second one is his result.</p>
<p>i try this :</p>
<pre><code>listStudentResult = []
listStudentResult.append([])
listStudentResult[0].append("Alex")
listOfasinEan[0].append(20)
lisStudentResult.append([])
listStudentResult[1].append(Pa... | 0 | 2016-06-03T09:59:45Z | 37,611,497 | <p>By looking at your requirement, I would suggest you to use dictionary in python.</p>
<p>To explain dictionary, I will take your example</p>
<pre><code>listStudentResult = dict()
listStudentResult['Alex'] = 20
listStudentResult['Paul'] = 15
</code></pre>
<p>You can access the elements using listStudentResult['Alex... | 2 | 2016-06-03T10:07:14Z | [
"python",
"python-2.7",
"multidimensional-array"
] |
How deal with 2D array in Python? | 37,611,360 | <p>I want to have a 2D array, the first Parametre is the name of student and the second one is his result.</p>
<p>i try this :</p>
<pre><code>listStudentResult = []
listStudentResult.append([])
listStudentResult[0].append("Alex")
listOfasinEan[0].append(20)
lisStudentResult.append([])
listStudentResult[1].append(Pa... | 0 | 2016-06-03T09:59:45Z | 37,612,927 | <p>Complex class:</p>
<pre><code>class AutoVivification(dict):
"""Implementation of perl's autovivification feature. Has features from both dicts and lists,
dynamically generates new subitems as needed, and allows for working (somewhat) as a basic type.
"""
def __getitem__(self, item):
if isins... | 1 | 2016-06-03T11:14:47Z | [
"python",
"python-2.7",
"multidimensional-array"
] |
How to iterate over latitude longitude values of a grib2 file? | 37,611,471 | <p>I'm trying to get the <code>uvIndex</code> of all the lat,lng present in a grib2 file.
This is the <a href="ftp://ftpprd.ncep.noaa.gov/pub/data/nccf/com/hourly/prod/uv.20160602/" rel="nofollow">link</a> from where I'm getting the file. The problem is I'm not able to understand the structure of the file so that I can... | 0 | 2016-06-03T10:06:03Z | 37,612,480 | <p>You have to iterate though GRIB file and find desirable record, then get data, like here:</p>
<pre><code>for g in grbs:
print g.shortName, g.typeOfLevel, g.level # print info about all GRIB records and check names
if (g.shortName == shortName and g.typeOfLevel == typeOfLevel and g.level == level):
... | 1 | 2016-06-03T10:53:01Z | [
"python",
"numpy",
"weather",
"grib",
"noaa"
] |
Record is not creating in another model while creating a record in odoo | 37,611,526 | <p>Currently i am creating a custom module, in which i need to create a demo record while a customer invoice is created. </p>
<p>This is my custom model.</p>
<pre><code>class csm(models.Model):
_name= 'csm'
invoice_date = fields.Datetime('Invoice date',readonly=True)
delivery_date = fields.Datetime('De... | 0 | 2016-06-03T10:08:40Z | 37,616,442 | <p>self.env['csm'].<strong>create</strong> , instead of self.env['csm'].<strong>write</strong></p>
<pre><code>@api.multi
def write(self,values):
record = super(invoice_csm, self).write(values)
if 'state' in values and values['state'] == 'paid':
if values.get('date_invoice') and values.get('delivery_... | 1 | 2016-06-03T14:01:54Z | [
"python",
"odoo-8"
] |
Copy a file into a Folder with timestamp | 37,611,640 | <p>I'm stuck now with following problem. (i googled but didn't find a solution for that)</p>
<p>The thing is i want to copy a file in to a folder with a variable in the name of the folder. The variable is a timestamp. How can i do this? </p>
<p>Here is my code:</p>
<pre><code>datetime_ordner = time.strftime("__%d_%m... | 0 | 2016-06-03T10:13:45Z | 37,612,988 | <p>For copy file in a folder with time stamp you need to do string formatting for your path.
Here is the solution for you..</p>
<pre><code>import time
import os
import shutil
# CREATE DATA TIME VARIABLE
datetime_var = time.strftime("__%d_%m_%y-%H-%M")
# THIS IS SOURCE FILE
src_file = r'D:\source.txt'
# LETS CREATE ... | 0 | 2016-06-03T11:18:07Z | [
"python",
"file",
"operating-system"
] |
python convert str to timedelta | 37,611,678 | <p>I want to convert time offsets formatted as <code>str</code> to <code>datetime.timedelta</code> objects, then plot the curve of observations versus time.</p>
<pre><code>'5 days, 4:23:52.480000' ; 17.647166
'5 days, 5:56:09.166000' ; 22.916071
'5 days, 8:21:40.261000' ; 18.922329
'5 days, 9:53:18.... | -4 | 2016-06-03T10:15:01Z | 37,611,860 | <p>There is no parser for timedeltas. So you have to build one yourself:</p>
<pre><code>import re
delta = '5 days, 4:23:52.480000'
days, hours, minutes, seconds = re.match('(?:(\d+) days, )?(\d+):(\d+):([.\d+]+)', delta).groups()
total_seconds = ((int(days or 0) * 24 + int(hours)) * 60 + int(minutes)) * 60 + float(se... | 0 | 2016-06-03T10:23:23Z | [
"python",
"datetime",
"timedelta"
] |
python convert str to timedelta | 37,611,678 | <p>I want to convert time offsets formatted as <code>str</code> to <code>datetime.timedelta</code> objects, then plot the curve of observations versus time.</p>
<pre><code>'5 days, 4:23:52.480000' ; 17.647166
'5 days, 5:56:09.166000' ; 22.916071
'5 days, 8:21:40.261000' ; 18.922329
'5 days, 9:53:18.... | -4 | 2016-06-03T10:15:01Z | 37,616,908 | <p>While I don't know of anything that parses text into <code>timedelta</code>, the format you have specified is understood by the <a href="http://pandas.pydata.org/pandas-docs/stable/timedeltas.html" rel="nofollow"><code>pandas.Timedelta</code></a> constructor, so if you want, you can use that to construct your timede... | 0 | 2016-06-03T14:23:33Z | [
"python",
"datetime",
"timedelta"
] |
Django-Nginx Patch request :405 Method \"METHOD_OTHER\" not allowed | 37,611,742 | <p>I am using django rest framework.</p>
<p>Patch on api endpoint( users/<em>user_id</em>) is working in local django server on my machine. But on nginx development server its showing </p>
<blockquote>
<p>{"detail":"Method \"METHOD_OTHER\" not allowed."}</p>
</blockquote>
<p>Do we need to change some settings in n... | 1 | 2016-06-03T10:17:57Z | 37,630,789 | <p>Ok I tried the access the same code from different network and it worked.
Probably it was firewall issue of that particular wifi network.</p>
| 0 | 2016-06-04T13:28:12Z | [
"python",
"django",
"nginx",
"django-rest-framework"
] |
Python Flask catch multiple Integrity errors = different error messages if user or email throws integrity error | 37,611,746 | <p>I have a simple registration function, where a new user has to give following informations: </p>
<p><strong>Email (is unique)</strong></p>
<p><strong>Username (is unique, primary key)</strong></p>
<p><strong>Password</strong></p>
<p><strong>Confirm Password</strong></p>
<p>Problem:</p>
<p>If the user fills in ... | 1 | 2016-06-03T10:18:15Z | 37,614,514 | <p>if you are using wtf form then you can override the validate method of NewUserForm</p>
<pre><code>class NewUserForm(Form):
username = TextField('Username', [validators.Required()])
def __init__(self, *args, **kwargs):
Form.__init__(self, *args, **kwargs)
self.user = None
def validate(s... | 1 | 2016-06-03T12:33:21Z | [
"python",
"python-2.7",
"error-handling",
"flask",
"sqlalchemy"
] |
Exception with swiftclient on bluemix: import fails in Jupyter notebook on Apache Spark instance | 37,611,803 | <p>I am writing a python code on bluemix which can create and delete files in containers using swiftclient library. But, an exception is raised for the following code. Please note than i am using Notebook on Apache Spark. I can upload this as an app code once the development is complete.
The exception can be seen in t... | 0 | 2016-06-03T10:21:04Z | 37,687,378 | <p>I see that you are using "bluemix_ipythonspark_16" spark service instance with probably environment like this:-</p>
<pre><code>Language
Python 2.7
Notebook (Jupyter)
IPython 3.2.1
Spark as a Service
Apache Spark 1.6
</code></pre>
<p><strong>I can reproduce your issue in this environment but what i think it may be ... | 0 | 2016-06-07T19:05:44Z | [
"python",
"ibm-bluemix",
"object-storage"
] |
Counting and sorting the tags of a user in python | 37,611,840 | <p><a href="http://i.stack.imgur.com/WWpLK.png" rel="nofollow">1</a>I have a data frame of users as index and facebook pages liked by users in column and two different data frame with different tags associated to a particular page. I have to first check in data frame and then in second if not one. store the tags of par... | 1 | 2016-06-03T10:22:34Z | 37,614,306 | <p>Ok let's call <code>df_user_pages</code> the dataframe in which the pages visited are stored per user. Such as this:</p>
<pre><code>In[2]: df_user_pages
Out[2]: name Page 1 Page 2 Page 3
random guy BlackBuck GiveMeSport Analytics Ninja
moknoi nion ... | 0 | 2016-06-03T12:22:43Z | [
"python",
"python-2.7",
"sorting",
"pandas"
] |
python Selenium 'click' command only on first loop | 37,611,863 | <p>I have the following click even within a loop that works but i only want it to be carrie out on the first loop as after that the javascipt has been activated</p>
<pre><code>browser.find_element_by_xpath("//*[@id='re_']/div[2]/a[1]").click()
</code></pre>
<p>any ideas how i can do this?</p>
| 1 | 2016-06-03T10:23:33Z | 37,612,666 | <p>have some counter</p>
<pre><code>count = 0
loop.....
if count == 0:
browser.find_element_by_xpath("//*[@id='re_']/div[2]/a[1]").click()
count = count + 1
rest of the code
</code></pre>
<p>only the first time the loop runs, the button will be clicked</p>
| 2 | 2016-06-03T11:02:37Z | [
"python",
"selenium"
] |
split arcgis string field with mutiple delimiters into new text file in Python | 37,611,876 | <p>I've got a table in ArcGIS 10.2 with a string field. I need to split this field out into a text file with each P_XXXX on a separate line. What is the best method to split the table on multiple delimiters (we have ',' and '&') and write out into a new text file? </p>
<p>Many Thanks
<a href="http://i.stack.imgur.... | 0 | 2016-06-03T10:24:12Z | 37,612,737 | <p>For an example I put some of the text in list, and then used regex for finding relevant tokens.</p>
<pre><code>import re
file_to_write = open('tokens.txt','wb')
attribute = ['P_10490','P_9912,P_9916','P_9914,P_9915,P_9918']
for item in attribute:
tokens = re.findall('(P_[0-9]+)', item)
for t in tokens:
... | 0 | 2016-06-03T11:05:19Z | [
"python",
"string",
"text-files",
"arcgis"
] |
SQL SELECT MAX(Id) | 37,612,043 | <p>I try to make a graph of the 7 last entries of my SQL database.
So I tried to select the maximum (or last entered) id number, but it is not working.</p>
<p>My table:</p>
<pre><code>Id | id_time | temp | RH
2700 | 2706 | 24.187 | 63.0999984741211
2701 | 2707 | 24.25 | 63
2702 | 2708 | 26.562 | 99.9000... | 0 | 2016-06-03T10:32:28Z | 37,612,115 | <p>I am assuming you are looking for sql query, the following query will order by column name in descending fashion and return 7 rows</p>
<pre><code>SELECT * FROM table_name ORDER BY column_name DESC LIMIT 7;
</code></pre>
| 1 | 2016-06-03T10:36:03Z | [
"php",
"python",
"mysql",
"select",
"max"
] |
SQL SELECT MAX(Id) | 37,612,043 | <p>I try to make a graph of the 7 last entries of my SQL database.
So I tried to select the maximum (or last entered) id number, but it is not working.</p>
<p>My table:</p>
<pre><code>Id | id_time | temp | RH
2700 | 2706 | 24.187 | 63.0999984741211
2701 | 2707 | 24.25 | 63
2702 | 2708 | 26.562 | 99.9000... | 0 | 2016-06-03T10:32:28Z | 37,612,185 | <p>mysql_query(); returns a resource, not a result set. you need to fetch data from it:</p>
<pre><code> $res = mysql_query($sql1) or die ("no query");
$max1 = mysql_fetch_array($res);
var_dump($max1);
</code></pre>
<p>And then: don't use mysql_* functions. They are deprecated. </p>
| 0 | 2016-06-03T10:39:34Z | [
"php",
"python",
"mysql",
"select",
"max"
] |
SQL SELECT MAX(Id) | 37,612,043 | <p>I try to make a graph of the 7 last entries of my SQL database.
So I tried to select the maximum (or last entered) id number, but it is not working.</p>
<p>My table:</p>
<pre><code>Id | id_time | temp | RH
2700 | 2706 | 24.187 | 63.0999984741211
2701 | 2707 | 24.25 | 63
2702 | 2708 | 26.562 | 99.9000... | 0 | 2016-06-03T10:32:28Z | 37,612,207 | <p>First check php docs <a href="http://php.net/manual/en/function.mysql-query.php" rel="nofollow">here</a>. mysql_query returns a resource not an object or array. To check the result set from database you need to loop through it like</p>
<pre><code>while ($row = mysql_fetch_assoc($max1)) {
echo $row['Id'];
}
</code><... | 2 | 2016-06-03T10:40:29Z | [
"php",
"python",
"mysql",
"select",
"max"
] |
using python to remove extra characters from strings and remove two decimal places to make it an integer | 37,612,113 | <p>I want to extract the size of a property from a website. Part of the Code I have tried which is concerned with the extracted string is this</p>
<pre><code> try:
size_result= str(value)
print "Size of the property: ",size_result
except StandardError as e:
size_resul... | -2 | 2016-06-03T10:35:56Z | 37,612,151 | <p>You can do </p>
<pre><code>a = '7332.00 SqFt '
int(a[:a.find('.')])
</code></pre>
<p>The <code>find</code> parts looks for the dot (<code>.</code>), and it slices until that point, leaving only the value. Then cast it to an int by calling <code>int()</code>.</p>
| 1 | 2016-06-03T10:37:46Z | [
"python",
"string",
"python-2.7",
"python-3.x",
"replace"
] |
using python to remove extra characters from strings and remove two decimal places to make it an integer | 37,612,113 | <p>I want to extract the size of a property from a website. Part of the Code I have tried which is concerned with the extracted string is this</p>
<pre><code> try:
size_result= str(value)
print "Size of the property: ",size_result
except StandardError as e:
size_resul... | -2 | 2016-06-03T10:35:56Z | 37,612,168 | <p>Split it on the point and convert to integer:</p>
<pre><code>area = int(size_result.split('.')[0])
</code></pre>
| 4 | 2016-06-03T10:38:42Z | [
"python",
"string",
"python-2.7",
"python-3.x",
"replace"
] |
I cannot reach Entry's values from tkinter, the last one corrupt others | 37,612,239 | <p>I am a new Python user. I try to make a serie of entries identified by labels and gets the values inserted. The callback functions seem well done but it's allways the third entry's value which I reach.
I am Python/Linux user, version 2.7.6
It seem to be lambda's declaration issue, can you help me ?</p>
<pre><code>i... | 1 | 2016-06-03T10:41:55Z | 37,614,675 | <p>You are correct, it comes from a lambda declaration issue.</p>
<p>The <code>i</code> in your loop is not actually changing, as <a href="http://stackoverflow.com/questions/7514093/lambda-function-dont-closure-the-parameter-in-python">lambdas don't closure the parameter</a>. As such, you can make a simple adjustment ... | 0 | 2016-06-03T12:41:15Z | [
"python",
"lambda",
"tkinter",
"bind"
] |
I cannot reach Entry's values from tkinter, the last one corrupt others | 37,612,239 | <p>I am a new Python user. I try to make a serie of entries identified by labels and gets the values inserted. The callback functions seem well done but it's allways the third entry's value which I reach.
I am Python/Linux user, version 2.7.6
It seem to be lambda's declaration issue, can you help me ?</p>
<pre><code>i... | 1 | 2016-06-03T10:41:55Z | 37,615,361 | <p>One problem is this line of code:</p>
<pre><code>self.ents[i].entry["textvariable"] = self.ents[i].val
</code></pre>
<p>The <code>textvariable</code> attribute must be set to an instance of <code>StringVar</code> (or one of the other tkinter variables), <em>not</em> the value of such an instance. You need to remov... | 2 | 2016-06-03T13:12:43Z | [
"python",
"lambda",
"tkinter",
"bind"
] |
How to create executable with Python 3.5 on Windows? | 37,612,339 | <p>I'm starting with Python so I downloaded the 3.5 version on my Windows 7 (64), and developped a small app in Eclipse Luna (4.4.1) with PyDev and the Tkinter library. It has only 4 modules and a text file.</p>
<p>I'd like to know how I could export an executable version of my project, like when you do <em>File</em>>... | 1 | 2016-06-03T10:46:07Z | 37,612,375 | <p><a href="http://www.pyinstaller.org/" rel="nofollow">PyInstaller</a> (version 3.2) works for Python 3.5, according to their website. </p>
| 1 | 2016-06-03T10:47:31Z | [
"python",
"eclipse",
"py2exe",
"python-3.5"
] |
Index of matching rows in Pandas DataFrame [Python] | 37,612,366 | <p>I have two Pandas DataFrames (<code>A</code> and <code>B</code>) with 2 columns and different number of rows.<br>
They used to be numpy 2D matrices and they both contain integer values.<br>
Is there any way to retrieve the indices of matching rows between those two?</p>
<p>I've been trying <code>isin()</code> or <c... | 1 | 2016-06-03T10:47:13Z | 37,612,551 | <p>i would do it this way:</p>
<pre><code>In [199]: df1.reset_index().merge(df2.reset_index(), on=['a','b'])
Out[199]:
index_x a b index_y
0 1 9 1 17
1 3 4 0 4
</code></pre>
<p>or like this:</p>
<pre><code>In [211]: pd.merge(df1.reset_index(), df2.reset_index(), on=['a','b'], suf... | 1 | 2016-06-03T10:56:21Z | [
"python",
"pandas",
"dataframe"
] |
Index of matching rows in Pandas DataFrame [Python] | 37,612,366 | <p>I have two Pandas DataFrames (<code>A</code> and <code>B</code>) with 2 columns and different number of rows.<br>
They used to be numpy 2D matrices and they both contain integer values.<br>
Is there any way to retrieve the indices of matching rows between those two?</p>
<p>I've been trying <code>isin()</code> or <c... | 1 | 2016-06-03T10:47:13Z | 37,612,642 | <p>Without merging, you can use <code>==</code> and then look if on each row there is <code>False</code>.</p>
<pre><code>df1 = pd.DataFrame({'a':[0,1,2,3,4],'b':[0,1,2,3,4]})
df2 = pd.DataFrame({'a':[0,1,2,3,4],'b':[2,1,2,2,4]})
test = pd.DataFrame(index = df1.index,columns = ['test'])
for row in df1.index:
if Fal... | 0 | 2016-06-03T11:01:10Z | [
"python",
"pandas",
"dataframe"
] |
Packaging a Python script that can be run on a computer that doesn't have Python installed? | 37,612,440 | <p>I have a Python script (that manipulates files on a shared drive). I would like to turn that script into a file (maybe .exe?) that perhaps can be double-clicked and run on a machine that doesn't have Python installed. Is that possible/easy to do?</p>
| 0 | 2016-06-03T10:50:56Z | 37,613,575 | <p>You can try <code>py2exe</code>.</p>
<p>Tutorials can be found at <a href="http://www.py2exe.org/index.cgi/Tutorial" rel="nofollow">http://www.py2exe.org/index.cgi/Tutorial</a></p>
| 1 | 2016-06-03T11:46:26Z | [
"python",
"ipython"
] |
Packaging a Python script that can be run on a computer that doesn't have Python installed? | 37,612,440 | <p>I have a Python script (that manipulates files on a shared drive). I would like to turn that script into a file (maybe .exe?) that perhaps can be double-clicked and run on a machine that doesn't have Python installed. Is that possible/easy to do?</p>
| 0 | 2016-06-03T10:50:56Z | 37,614,321 | <p>I use and recommend pyinstaller. If you need only <strong>one executable file</strong>, you need to install pyinstaller and call executable passing these arguments:</p>
<pre><code>pyinstaller.exe your_script.py --onefile --windowed
</code></pre>
<p>This options can be used when you generate the executable file: <a... | 1 | 2016-06-03T12:23:16Z | [
"python",
"ipython"
] |
When is hash(n) == n in Python? | 37,612,524 | <p>I've been playing with Python's <a href="https://docs.python.org/3/library/functions.html#hash">hash function</a>. For small integers, it appears <code>hash(n) == n</code> always. However this does not extend to large numbers:</p>
<pre><code>>>> hash(2**100) == 2**100
False
</code></pre>
<p>I'm not surpri... | 94 | 2016-06-03T10:55:04Z | 37,612,722 | <p>The <a href="https://hg.python.org/cpython/file/c6880edaf6f3/Objects/intobject.c#l448" rel="nofollow">implementation for the int type in cpython can be found here.</a> </p>
<p>It just returns the value, except for <code>-1</code>, than it returns <code>-2</code>:</p>
<pre class="lang-c prettyprint-override"><code>... | -1 | 2016-06-03T11:04:52Z | [
"python",
"python-2.7",
"python-3.x",
"hash"
] |
When is hash(n) == n in Python? | 37,612,524 | <p>I've been playing with Python's <a href="https://docs.python.org/3/library/functions.html#hash">hash function</a>. For small integers, it appears <code>hash(n) == n</code> always. However this does not extend to large numbers:</p>
<pre><code>>>> hash(2**100) == 2**100
False
</code></pre>
<p>I'm not surpri... | 94 | 2016-06-03T10:55:04Z | 37,613,404 | <p>Hash function returns <strong>plain int</strong> that means that returned value is greater than <code>-sys.maxint</code> and lower than <code>sys.maxint</code>, which means if you pass <code>sys.maxint + x</code> to it result would be <code>-sys.maxint + (x - 2)</code>.</p>
<pre><code>hash(sys.maxint + 1) == sys.ma... | 7 | 2016-06-03T11:38:23Z | [
"python",
"python-2.7",
"python-3.x",
"hash"
] |
When is hash(n) == n in Python? | 37,612,524 | <p>I've been playing with Python's <a href="https://docs.python.org/3/library/functions.html#hash">hash function</a>. For small integers, it appears <code>hash(n) == n</code> always. However this does not extend to large numbers:</p>
<pre><code>>>> hash(2**100) == 2**100
False
</code></pre>
<p>I'm not surpri... | 94 | 2016-06-03T10:55:04Z | 37,614,051 | <p><code>2305843009213693951</code> is <code>2^61 - 1</code>. It's the largest Mersenne prime that fits into 64 bits.</p>
<p>If you have to make a hash just by taking the value mod some number, then a large Mersenne prime is a good choice -- it's easy to compute and ensures an even distribution of possibilities. (Alth... | 76 | 2016-06-03T12:10:07Z | [
"python",
"python-2.7",
"python-3.x",
"hash"
] |
When is hash(n) == n in Python? | 37,612,524 | <p>I've been playing with Python's <a href="https://docs.python.org/3/library/functions.html#hash">hash function</a>. For small integers, it appears <code>hash(n) == n</code> always. However this does not extend to large numbers:</p>
<pre><code>>>> hash(2**100) == 2**100
False
</code></pre>
<p>I'm not surpri... | 94 | 2016-06-03T10:55:04Z | 37,614,182 | <p>Based on python documentation in <a href="https://github.com/python/cpython/blob/master/Python/pyhash.c"><code>pyhash.c</code></a> file:</p>
<blockquote>
<p>For numeric types, the hash of a number x is based on the reduction
of x modulo the prime <code>P = 2**_PyHASH_BITS - 1</code>. It's designed so that
... | 64 | 2016-06-03T12:16:11Z | [
"python",
"python-2.7",
"python-3.x",
"hash"
] |
Python MultiProcessing | 37,612,535 | <p>I'm using Python Python Multiprocessing for a RabbitMQ Consumers.
On Application Start I create 4 WorkerProcesses.</p>
<pre><code>def start_workers(num=4):
for i in xrange(num):
process = WorkerProcess()
process.start()
</code></pre>
<p>Below you find my WorkerClass.
The Logic works so far, I c... | 0 | 2016-06-03T10:55:35Z | 37,613,794 | <p>In the main process, keep track of your subprocesses (in a <code>list</code>) and loop over them with <code>.join(timeout=50)</code> (<a href="https://docs.python.org/2/library/multiprocessing.html#multiprocessing.Process.join" rel="nofollow">https://docs.python.org/2/library/multiprocessing.html#multiprocessing.Pro... | 1 | 2016-06-03T11:57:31Z | [
"python",
"multithreading",
"multiprocessing",
"python-multithreading",
"pika"
] |
Python MultiProcessing | 37,612,535 | <p>I'm using Python Python Multiprocessing for a RabbitMQ Consumers.
On Application Start I create 4 WorkerProcesses.</p>
<pre><code>def start_workers(num=4):
for i in xrange(num):
process = WorkerProcess()
process.start()
</code></pre>
<p>Below you find my WorkerClass.
The Logic works so far, I c... | 0 | 2016-06-03T10:55:35Z | 37,614,059 | <p>I would not handle the process pool management myself. Instead, I would use the <code>ProcessPoolExecutor</code> from the <code>concurrent.future</code> module. </p>
<p>No need to inherit the <code>WorkerProcess</code> to inherit the <code>Process</code> class. Just write your actual code in the class and then subm... | 1 | 2016-06-03T12:10:29Z | [
"python",
"multithreading",
"multiprocessing",
"python-multithreading",
"pika"
] |
Python: copying chosen rows form list to another | 37,612,571 | <p>I'm trying to write a function that copies chosen rows from list to another, basing on third list that points which should be taken. "1" - copy row with this stuff, "0" omitt.
Here is my code:</p>
<pre><code>stuff = [
[1, 2, 3],
[10, 20, 30],
[100, 200, 300],
[1000, 2000, 3000],
[10000, 20000, 30000],
]
chooseThes... | 1 | 2016-06-03T10:57:46Z | 37,612,709 | <p>A more simple approach is to either use an <em>indexed list</em> instead of a 0/1 list, to create an <em>indexed comprehension using <code>enumerate</code></em> or to use a combined list using <code>zip</code>: </p>
<pre><code>stuff = [
[1, 2, 3],
[10, 20, 30],
[100, 200, 300],
[1000, 2000, 3000],
[10000, 20... | 0 | 2016-06-03T11:04:20Z | [
"python",
"list",
"copying"
] |
Python: copying chosen rows form list to another | 37,612,571 | <p>I'm trying to write a function that copies chosen rows from list to another, basing on third list that points which should be taken. "1" - copy row with this stuff, "0" omitt.
Here is my code:</p>
<pre><code>stuff = [
[1, 2, 3],
[10, 20, 30],
[100, 200, 300],
[1000, 2000, 3000],
[10000, 20000, 30000],
]
chooseThes... | 1 | 2016-06-03T10:57:46Z | 37,612,971 | <p>You should keep track of the index of the list that you're trying to append from. </p>
<pre><code>stuff = [
[1, 2, 3],
[10, 20, 30], ... | 0 | 2016-06-03T11:16:57Z | [
"python",
"list",
"copying"
] |
Spark unionAll multiple dataframes | 37,612,622 | <p>For a set of dataframes</p>
<pre><code>val df1 = sc.parallelize(1 to 4).map(i => (i,i*10)).toDF("id","x")
val df2 = sc.parallelize(1 to 4).map(i => (i,i*100)).toDF("id","y")
val df3 = sc.parallelize(1 to 4).map(i => (i,i*1000)).toDF("id","z")
</code></pre>
<p>to union all of them I do</p>
<pre><code>df1.... | 3 | 2016-06-03T11:00:04Z | 37,612,978 | <p>The simplest solution is to <code>reduce</code> with <code>unionAll</code>:</p>
<pre><code>val dfs = Seq(df1, df2, df3)
dfs.reduce(_ unionAll _)
</code></pre>
<p>This is relatively concise and shouldn't move data from off-heap storage but extends lineage with each union what can be a problem if you try to merge la... | 6 | 2016-06-03T11:17:17Z | [
"python",
"scala",
"apache-spark",
"apache-spark-sql",
"spark-dataframe"
] |
How to convert Double dict from file and use it | 37,612,654 | <p>I have double dict which i want read using json, but i don't really know how. Im running Python 3</p>
<pre><code>{ "www.svetaine.lt":{ "true": "111.111.222.11" }}
{ "www.svetaine2.lt":{ "true": "111.111.222.11" }}
</code></pre>
<p>I know only how to make simple <code>dict</code></p>
<pre><code>def openfile():
... | 0 | 2016-06-03T11:01:46Z | 37,613,480 | <pre><code>import json
def openfile():
d={}
with open('s.json', 'r') as f:
for line in f:
line_ = json.loads(line)
name = line_.keys()[0]
status = line_[name].keys()[0]
ip = line_[name][status]
d[name] = {'name':name, 'status':status, 'ip':ip}... | 0 | 2016-06-03T11:42:04Z | [
"python",
"json",
"dictionary"
] |
Understanding of @gen.coroutine annotation | 37,612,712 | <p>I know that my question looks to broad, but I hope the answer on this question will give me correct direction what to read on. I am new to Tornado framework, basically I am new to Python.
I am looking into this <a href="https://github.com/legnaleurc/telezombie" rel="nofollow">project</a>:
Could you please explain me... | 1 | 2016-06-03T11:04:26Z | 37,613,672 | <ul>
<li><code>@gen</code> is a decorator, it will modify the function below it at definition (<a href="https://wiki.python.org/moin/PythonDecorators" rel="nofollow">https://wiki.python.org/moin/PythonDecorators</a>)</li>
<li>He uses <code>raise</code> to return values and will catch it with <code>except gen.Return</co... | 1 | 2016-06-03T11:50:48Z | [
"python",
"tornado"
] |
Will the Session() close after terminate the python script? | 37,612,735 | <p>I've written a simple python code to login to a forum, in order to keep alive and gain the online time. The code is as following:</p>
<pre><code>logPara = {'username':user,'password':pwd}
s = requests.Session()
s.post(forumUrl,data=logPara)
homePage = requests.get(pageUrl)
</code></pre>
<p>I can get the correct ho... | 0 | 2016-06-03T11:05:16Z | 37,613,720 | <p>When you run the script, unless the script is being told to run endlessly or after a certain condition, it'll terminate almost immediately. So for your script it'll end after you run it. To continue running it you can put in a condition like for example.</p>
<pre><code>while 1:
#Run your code
</code></pre>
| 0 | 2016-06-03T11:53:17Z | [
"python",
"session",
"python-requests",
"urllib2"
] |
Will the Session() close after terminate the python script? | 37,612,735 | <p>I've written a simple python code to login to a forum, in order to keep alive and gain the online time. The code is as following:</p>
<pre><code>logPara = {'username':user,'password':pwd}
s = requests.Session()
s.post(forumUrl,data=logPara)
homePage = requests.get(pageUrl)
</code></pre>
<p>I can get the correct ho... | 0 | 2016-06-03T11:05:16Z | 37,615,122 | <p>Yes, definitely the session will be lost.
So, you two options for making the session last longer, One is as the answer posted by @Seekheart. Second is to save the session state in a file using python's pickle and load it again when needed. But this also will depend on the cookie expiration etc.</p>
<p>This is how ... | 1 | 2016-06-03T13:01:05Z | [
"python",
"session",
"python-requests",
"urllib2"
] |
Pseuodo code to Python error | 37,612,810 | <p>Pseudo code >></p>
<p><a href="http://i.stack.imgur.com/vAvG1.png" rel="nofollow"><img src="http://i.stack.imgur.com/vAvG1.png" alt="Screenshot_pseudocode"></a></p>
<p>This is the question >> </p>
<p><a href="http://i.stack.imgur.com/IYfeF.png" rel="nofollow"><img src="http://i.stack.imgur.com/IYfeF.png" alt="scr... | -1 | 2016-06-03T11:09:19Z | 37,613,087 | <p>On your last iteration, count takes the value 12 when entering the loop and then half way inside the loop becomes 13. However the ISBN list, doesn't contain an entry with index value 13. It goes up to 12.</p>
<p>This is not a good way to create lists\tupples:</p>
<pre><code>ISBN = ([1,2,3,4,5,6,7,8,9,10,11,12,13])... | 0 | 2016-06-03T11:23:00Z | [
"python",
"pseudocode"
] |
How to iterate a column to get the sub list in sqlalchemy? | 37,612,870 | <p>I would like to acquire the sub list from a table like this using sqlalchemy: </p>
<pre><code>Column1 Column2
a 1
a 2
b 1
b 2
</code></pre>
<p>and firstly get </p>
<pre><code>Column1 Column2
a 1
a 2
</code></pre>
<p>and secondly get</... | 0 | 2016-06-03T11:11:56Z | 37,625,624 | <p>You can do it with a single query, but you need to perform the grouping in Python. To do that you could use <a href="https://docs.python.org/3/library/itertools.html#itertools.groupby" rel="nofollow"><code>itertools.groupby</code></a> to process the query results which you would order by (<code>column1</code>, <code... | 0 | 2016-06-04T01:58:04Z | [
"python",
"sqlalchemy"
] |
Import from libmproxy to Python | 37,613,118 | <p>I'm running a python 2.7 script (on Kali machine) which using the following import:</p>
<pre><code>from libmproxy.protocol.http import decoded
</code></pre>
<p>When running, I'm getting the following error:</p>
<pre><code>ImportError: Cannot import name decoded
</code></pre>
<p>How to fix this problem please?</p... | 0 | 2016-06-03T11:24:44Z | 37,613,979 | <p>Apparently, the <code>libmproxy.protocol.http</code> module doesn't define the name <code>decoded</code> which you're trying to <code>import</code>. Use the <a href="http://docs.mitmproxy.org/en/latest/" rel="nofollow">documentation</a> for the version of the library you have installed.</p>
| 1 | 2016-06-03T12:07:13Z | [
"python",
"python-2.7",
"python-import"
] |
"in" statement for lists/tuples of floats | 37,613,288 | <p>Should the use of <strong>in</strong> or <strong>not in</strong> be avoided when dealing with lists/tuples of floats? Is its implementation something like the code below or is it something more sophisticated?</p>
<pre><code>check = False
for item in list_to_search_the_value_in:
if value_to_search_for == item:
... | 3 | 2016-06-03T11:32:34Z | 37,613,545 | <p><a href="https://docs.python.org/3/library/stdtypes.html#common-sequence-operations" rel="nofollow">Here's</a> the part of the documentation saying that <code>in</code> checks for equality on sequence types. So no, this should not be used for sequences of floats.</p>
| 2 | 2016-06-03T11:45:22Z | [
"python"
] |
"in" statement for lists/tuples of floats | 37,613,288 | <p>Should the use of <strong>in</strong> or <strong>not in</strong> be avoided when dealing with lists/tuples of floats? Is its implementation something like the code below or is it something more sophisticated?</p>
<pre><code>check = False
for item in list_to_search_the_value_in:
if value_to_search_for == item:
... | 3 | 2016-06-03T11:32:34Z | 37,613,625 | <p>The <code>in</code> operator uses regular equality checks behind the scenes, so it has the same limitations as <code>__eq__()</code> when it comes to floats. Use with caution if at all.</p>
<pre><code>>>> 0.3 == 0.4 - 0.1
False
>>> 0.3 in [0.4 - 0.1]
False
</code></pre>
| 1 | 2016-06-03T11:48:21Z | [
"python"
] |
"in" statement for lists/tuples of floats | 37,613,288 | <p>Should the use of <strong>in</strong> or <strong>not in</strong> be avoided when dealing with lists/tuples of floats? Is its implementation something like the code below or is it something more sophisticated?</p>
<pre><code>check = False
for item in list_to_search_the_value_in:
if value_to_search_for == item:
... | 3 | 2016-06-03T11:32:34Z | 37,613,636 | <p><code>in</code> and <code>not in</code> should be your preferred way of membership testing. Both operators can make use (via <a href="https://docs.python.org/3/reference/datamodel.html#object.__contains__" rel="nofollow"><code>__contains__()</code></a>) of any optimized membership test that the container offers.</p>... | 3 | 2016-06-03T11:48:57Z | [
"python"
] |
"in" statement for lists/tuples of floats | 37,613,288 | <p>Should the use of <strong>in</strong> or <strong>not in</strong> be avoided when dealing with lists/tuples of floats? Is its implementation something like the code below or is it something more sophisticated?</p>
<pre><code>check = False
for item in list_to_search_the_value_in:
if value_to_search_for == item:
... | 3 | 2016-06-03T11:32:34Z | 37,613,775 | <p>Since <code>in</code> operator uses equality check, it'll frequently fail, since <a href="http://stackoverflow.com/questions/588004/is-floating-point-math-broken">floating point math is "broken"</a> (well, it's not, but you get a point).</p>
<p>You may easily achieve similar functionality by using <code>any</code>:... | 1 | 2016-06-03T11:56:24Z | [
"python"
] |
"in" statement for lists/tuples of floats | 37,613,288 | <p>Should the use of <strong>in</strong> or <strong>not in</strong> be avoided when dealing with lists/tuples of floats? Is its implementation something like the code below or is it something more sophisticated?</p>
<pre><code>check = False
for item in list_to_search_the_value_in:
if value_to_search_for == item:
... | 3 | 2016-06-03T11:32:34Z | 37,613,873 | <p>Python's <code>list</code> type has its <code>__contains__</code> method <a href="https://hg.python.org/cpython/file/default/Objects/listobject.c#l399" rel="nofollow">implemented in C</a>:</p>
<pre><code>static int
list_contains(PyListObject *a, PyObject *el)
{
Py_ssize_t i;
int cmp;
for (i = 0, cmp = ... | 1 | 2016-06-03T12:01:40Z | [
"python"
] |
Django Rest Framwork get user in serializer | 37,613,293 | <p>I can get the user in my serializer? </p>
<p>For example I have this serializer:</p>
<p><em>serializers.py</em></p>
<pre><code>class ClientSearchSerializer(serializers.ModelSerializer):
client = serializers.SlugRelatedField(
many=False,
queryset=Client.objects.filter(user=????),
slug_... | 0 | 2016-06-03T11:32:48Z | 37,613,429 | <p><code>CurrentUserDefault</code> should work for you. </p>
<p>Documentation: <a href="http://www.django-rest-framework.org/api-guide/validators/#currentuserdefault" rel="nofollow">http://www.django-rest-framework.org/api-guide/validators/#currentuserdefault</a></p>
<p>Please note: </p>
<blockquote>
<p>In order... | 2 | 2016-06-03T11:39:51Z | [
"python",
"django",
"api",
"serialization",
"django-rest-framework"
] |
Django Rest Framwork get user in serializer | 37,613,293 | <p>I can get the user in my serializer? </p>
<p>For example I have this serializer:</p>
<p><em>serializers.py</em></p>
<pre><code>class ClientSearchSerializer(serializers.ModelSerializer):
client = serializers.SlugRelatedField(
many=False,
queryset=Client.objects.filter(user=????),
slug_... | 0 | 2016-06-03T11:32:48Z | 37,617,192 | <p><code>CurrentUserDefault()</code> is a great way to get the user, as has been answered. Another option would be to return a function which returns a serializer class in your view's <code>get_serializer_class</code> method. That way you could supply <code>self.request.user</code> as an argument to the function.</p>
... | 0 | 2016-06-03T14:36:34Z | [
"python",
"django",
"api",
"serialization",
"django-rest-framework"
] |
Finding local minima from set of points in octave/python | 37,613,316 | <p>I have a file with set of points like <code>652 653 655...</code> and when plotted looks like this.
<a href="http://i.stack.imgur.com/r32th.png" rel="nofollow"><img src="http://i.stack.imgur.com/r32th.png" alt="enter image description here"></a></p>
<p>I want to detect the local minima (in this case, approximately ... | 0 | 2016-06-03T11:33:48Z | 37,613,514 | <p>If you want to find all elements from array <code>Y</code> that are smaller than their neighbors, you can use this call:</p>
<p><code>numpy.r_[True, Y[1:] < Y[:-1]] & numpy.r_[Y[:-1] < Y[1:], True]</code></p>
| 0 | 2016-06-03T11:43:31Z | [
"python",
"octave"
] |
Finding local minima from set of points in octave/python | 37,613,316 | <p>I have a file with set of points like <code>652 653 655...</code> and when plotted looks like this.
<a href="http://i.stack.imgur.com/r32th.png" rel="nofollow"><img src="http://i.stack.imgur.com/r32th.png" alt="enter image description here"></a></p>
<p>I want to detect the local minima (in this case, approximately ... | 0 | 2016-06-03T11:33:48Z | 37,675,556 | <p>I show here one solution with <a href="https://github.com/octave-de/macgyver_utils/blob/master/peakdet.cc" rel="nofollow">peakdet</a> which is based on <a href="http://billauer.co.il/peakdet.html" rel="nofollow">http://billauer.co.il/peakdet.html</a> <- (you shoud read this page)</p>
<pre><code>set (0, "defaultl... | 1 | 2016-06-07T09:31:22Z | [
"python",
"octave"
] |
how to find that how many times a while loop has get executed? | 37,613,349 | <p>Sample program in which <code>while</code> loop is illustrated:</p>
<pre><code>answer="0"
while answer!="4":
answer=input("What is 2 + 2?")
if answer!="4":
print("Wrong...Try again.")
else:
print("Yes! 2 + 2 = 4")
</code></pre>
<p>Here the loop will execute till the user gives the corre... | 1 | 2016-06-03T11:35:30Z | 37,613,528 | <p>Create a variable which stores the amount of attempts the user has taken:</p>
<pre><code>attempts = 0
while True:
answer = int(raw_input("What is 2 + 2?"))
attempts += 1
if answer == 4:
print("Yes! 2 + 2 = 4")
break
print "Wrong.. try again"
print "It took {0} amount of attempts"... | 2 | 2016-06-03T11:44:46Z | [
"python",
"loops",
"while-loop"
] |
how to find that how many times a while loop has get executed? | 37,613,349 | <p>Sample program in which <code>while</code> loop is illustrated:</p>
<pre><code>answer="0"
while answer!="4":
answer=input("What is 2 + 2?")
if answer!="4":
print("Wrong...Try again.")
else:
print("Yes! 2 + 2 = 4")
</code></pre>
<p>Here the loop will execute till the user gives the corre... | 1 | 2016-06-03T11:35:30Z | 37,613,529 | <p>Convert the <code>while</code>-loop into a <code>for</code>-loop:</p>
<pre><code>from itertools import count
for attempts in count(1):
answer = input("What is 2 + 2?")
if answer == "4":
break
print("Wrong...Try again.")
print("Correct in {} attempts!".format(attempts))
</code></pre>
| 2 | 2016-06-03T11:44:47Z | [
"python",
"loops",
"while-loop"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.