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 |
|---|---|---|---|---|---|---|---|---|---|
Programatically check if google protocol buffer field is required | 38,086,686 | <p>Is it possible to programmatically check if a given proto field is marked as <code>required</code> vs <code>optional</code>? I'm using python and have a <code>FieldDescriptor</code> object, but can't find a way to determine whether the field is required.</p>
| 0 | 2016-06-28T21:34:07Z | 38,086,753 | <p>A quick look at the <a href="https://developers.google.com/protocol-buffers/docs/reference/python/google.protobuf.descriptor.FieldDescriptor-class" rel="nofollow">documentation</a> indicates that your <code>FieldDescriptor</code> should have a <code>label</code> attribute indicating whether it's optional, required, ... | 2 | 2016-06-28T21:39:48Z | [
"python",
"protocol-buffers"
] |
fit regression of the form y = x ** a with numpy | 38,086,701 | <pre><code>import numpy as np
import matplotlib.pyplot as plt
x_ = np.array([1.0, 2.0, 4.0, 8.0, 16.0, 33.0])
y_ = np.array([0.4, 0.55, 0.62, 0.72, 0.76, 0.8])
</code></pre>
<p>I want to fit a regression model of the form <code>y = x ** a</code> where <code>a</code> is estimated.
The purpose is to extrapolate to (much... | 3 | 2016-06-28T21:35:08Z | 38,086,801 | <p>use:</p>
<pre><code>log(y+1) = a * log(x+1)
</code></pre>
<p>This gets you your exponential and forces through <code>(0, 0)</code></p>
<pre><code>f = lambda x, a: (x + 1) ** a - 1
x = np.random.rand(200, 1) * 100
y = f(x, 1.5) + np.random.rand(*x.shape) * 200
plt.plot(x, y, '.')
</code></pre>
<p><a href="http:/... | 2 | 2016-06-28T21:43:37Z | [
"python",
"numpy"
] |
fit regression of the form y = x ** a with numpy | 38,086,701 | <pre><code>import numpy as np
import matplotlib.pyplot as plt
x_ = np.array([1.0, 2.0, 4.0, 8.0, 16.0, 33.0])
y_ = np.array([0.4, 0.55, 0.62, 0.72, 0.76, 0.8])
</code></pre>
<p>I want to fit a regression model of the form <code>y = x ** a</code> where <code>a</code> is estimated.
The purpose is to extrapolate to (much... | 3 | 2016-06-28T21:35:08Z | 38,087,423 | <p>This fits a pure <code>y = x ** a</code> by least squares on <code>logy_ = a * logx_</code>:</p>
<pre><code>a = np.linalg.lstsq(logx_[:, np.newaxis], logy_)[0][0]
</code></pre>
| 2 | 2016-06-28T22:40:59Z | [
"python",
"numpy"
] |
How to draw a histogram in dask? | 38,086,741 | <p><code>t</code> is a dask array. I'd like to plot a histogram of <code>t</code>. Dask documentation has method </p>
<pre><code>dask.array.histogram(a, bins=None, range=None, normed=False, weights=None, density=None)
</code></pre>
<p>but no example. I've tried setting <code>bins</code> with a numpy array. Didn't wor... | 0 | 2016-06-28T21:38:38Z | 38,086,839 | <p>Dask.array.histogram requires both <code>bins</code> and <code>range</code> to be set with the number of desired bins and the min/max range of the data respectively. Here is a quick example:</p>
<pre><code>In [1]: import dask.array as da
In [2]: x = da.random.normal(10, 0.1, size=(100000,), chunks=(1000,)) # ran... | 1 | 2016-06-28T21:46:48Z | [
"python",
"dask"
] |
Does the for/in loop construct preserve order? | 38,086,774 | <p>Does an ordinary for/in statement guarantee the list is iterated in order?</p>
<pre><code>my_list = [5,4,3,2]
for i in my_list
print(i)
</code></pre>
<p>That is, is the loop above guaranteed to print <code>5 4 3 2</code> every time?</p>
| 0 | 2016-06-28T21:41:26Z | 38,086,825 | <p>A <code>for</code> loop's iteration order is controlled by whatever object it's iterating over. Iterating over an ordered collection like a <code>list</code> is guaranteed to iterate over elements in the list's order, but iterating over an unordered collection like a <code>set</code> makes almost no order guarantees... | 3 | 2016-06-28T21:46:01Z | [
"python"
] |
Does the for/in loop construct preserve order? | 38,086,774 | <p>Does an ordinary for/in statement guarantee the list is iterated in order?</p>
<pre><code>my_list = [5,4,3,2]
for i in my_list
print(i)
</code></pre>
<p>That is, is the loop above guaranteed to print <code>5 4 3 2</code> every time?</p>
| 0 | 2016-06-28T21:41:26Z | 38,086,834 | <p>When you iterate over a sequence (list, tuple, etc.), the order is guaranteed.
Hashed structures (dict, set, etc.) have their own order -- but for a given structure, the order will be the same each time. If you add or delete an element, the order may then be different.</p>
<hr>
<p>Consider the folloing code: I ma... | 1 | 2016-06-28T21:46:28Z | [
"python"
] |
Does the for/in loop construct preserve order? | 38,086,774 | <p>Does an ordinary for/in statement guarantee the list is iterated in order?</p>
<pre><code>my_list = [5,4,3,2]
for i in my_list
print(i)
</code></pre>
<p>That is, is the loop above guaranteed to print <code>5 4 3 2</code> every time?</p>
| 0 | 2016-06-28T21:41:26Z | 38,086,837 | <p>If you want to test it yourself:</p>
<pre><code>my_list = [5,4,3,2]
for _ in range(20):
new_list = []
for i in my_list:
new_list.append(i)
print(my_list == new_list)
</code></pre>
<p>And just for a control case:</p>
<pre><code>print([2,4,5,3] == my_list)
</code></pre>
| 1 | 2016-06-28T21:46:34Z | [
"python"
] |
Does the for/in loop construct preserve order? | 38,086,774 | <p>Does an ordinary for/in statement guarantee the list is iterated in order?</p>
<pre><code>my_list = [5,4,3,2]
for i in my_list
print(i)
</code></pre>
<p>That is, is the loop above guaranteed to print <code>5 4 3 2</code> every time?</p>
| 0 | 2016-06-28T21:41:26Z | 38,086,838 | <p>For lists, yes, since they are ordered data structures in Python. </p>
| 1 | 2016-06-28T21:46:42Z | [
"python"
] |
PySide & Python: How to send a dictionary via Signal/Slot? | 38,086,813 | <p>Platform: Centos 6 & Python 2.6.6</p>
<p>After looking at every example and question about doing this, for the life of me I can't get it to work on my system. Most answers seem to revolve around using PyQt instead of PySide, which isn't an option for me: I gotta use what the company gives me. </p>
<p>Here is t... | 0 | 2016-06-28T21:44:27Z | 38,104,422 | <p>The following is the location of that method, according to the docs. As mentioned in comments, you should upgrade PySide to the latest version as the issue you're having was not reproducible in the current version.</p>
<p><code>PySide.QtCore.QSettings.qRegisterMetaType</code></p>
| 1 | 2016-06-29T15:46:36Z | [
"python",
"qt",
"pyside"
] |
Stacked 3d bar chart with matplotlib | 38,086,972 | <p>i worked on a simple 3d bar chart using the following code:</p>
<pre><code>from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(111, projection = "3d")
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_zlabel("z")
ax.set_xlim3d(0,10)
ax.set... | 2 | 2016-06-28T21:57:23Z | 38,088,169 | <p>To make a stacked 3d bar plot, you can accumulate your <code>dz</code> values and use them as the base for each next bar. Here's an example:</p>
<p><a href="http://i.stack.imgur.com/226cy.png" rel="nofollow"><img src="http://i.stack.imgur.com/226cy.png" alt="enter image description here"></a></p>
<pre><code>from ... | 2 | 2016-06-29T00:01:17Z | [
"python",
"matplotlib",
"charts",
"3d"
] |
pandas function to fill missing values from other dataframe based on matching column? | 38,087,004 | <p>So I have two dataframes: one where certain columns are filled in and one where others are filled in but some from the previous df are missing. Both share some common non-empty columns.</p>
<pre><code>DF1:
FirstName Uid JoinDate BirthDate
Bob 1 20160628 NaN
Charlie 3 20160627 NaN
DF2:
Fir... | 2 | 2016-06-28T22:00:54Z | 38,087,019 | <p><strong>UPDATE:</strong> you can do it setting the proper indices and finally resetting the index of joined DF:</p>
<pre><code>In [14]: df1.set_index('FirstName').combine_first(df2.set_index('FirstName')).reset_index()
Out[14]:
FirstName Uid JoinDate BirthDate
0 Alice 2.0 NaN 19950403.0
1 ... | 3 | 2016-06-28T22:02:14Z | [
"python",
"python-3.x",
"pandas",
"dataframe"
] |
Random Sampling of Pandas data frame (both rows and columns) | 38,087,032 | <p>I know how to randomly sample few rows from a pandas data frame. Lets say I had a data frame df, then to get a fraction of rows, I can do :</p>
<pre><code>df_sample = df.sample(frac=0.007)
</code></pre>
<p>However what I need is random rows as above AND also random columns from the above data frame. </p>
<p>Df is... | 3 | 2016-06-28T22:03:30Z | 38,087,059 | <p>Just call <code>sample</code> twice, with corresponding axis parameters:</p>
<pre><code>df.sample(n=500).sample(n=1000, axis=1)
</code></pre>
<p>For the first one, axis=0 by default.</p>
| 5 | 2016-06-28T22:06:14Z | [
"python",
"numpy",
"pandas"
] |
using import inside class | 38,087,060 | <p>I am completely new to the python class concept. After searching for a solution for some days, I hope I will get help here:</p>
<p>I want a python class where I import a function and use it there. The main code should be able to call the function from the class. for that I have two files in the same folder.</p>
<h... | 2 | 2016-06-28T22:06:14Z | 38,087,102 | <p><code>sleep</code> is not a python builtin, and the name as is, does not reference any object. So Python has rightly raised a <code>NameEror</code>.</p>
<p>You intend to:</p>
<pre><code>import time as zeit
zeit.sleep(2)
</code></pre>
<p>And move <code>import time as zeit</code> to the top of the module. </p>
<p... | 3 | 2016-06-28T22:09:11Z | [
"python",
"class",
"import"
] |
using import inside class | 38,087,060 | <p>I am completely new to the python class concept. After searching for a solution for some days, I hope I will get help here:</p>
<p>I want a python class where I import a function and use it there. The main code should be able to call the function from the class. for that I have two files in the same folder.</p>
<h... | 2 | 2016-06-28T22:06:14Z | 38,087,114 | <p>You're almost there! <code>sleep</code> is a function within the <code>time</code> module. This means that the name <code>sleep</code> doesn't exist unless its understood within the context of <code>time</code>, unless you define it on your own. Since you didn't define it on your own, you can access it by running <c... | 2 | 2016-06-28T22:10:28Z | [
"python",
"class",
"import"
] |
using import inside class | 38,087,060 | <p>I am completely new to the python class concept. After searching for a solution for some days, I hope I will get help here:</p>
<p>I want a python class where I import a function and use it there. The main code should be able to call the function from the class. for that I have two files in the same folder.</p>
<h... | 2 | 2016-06-28T22:06:14Z | 38,087,143 | <p>You want <a href="https://docs.python.org/2/library/time.html?highlight=sleep#time.sleep%20" rel="nofollow">time.sleep</a>. You can also use;</p>
<pre><code>from time import sleep
</code></pre>
<p>Edit: Importing within class scope issues explained <a href="http://stackoverflow.com/a/6883558/5757280">here</a>.</p>... | 3 | 2016-06-28T22:12:34Z | [
"python",
"class",
"import"
] |
using import inside class | 38,087,060 | <p>I am completely new to the python class concept. After searching for a solution for some days, I hope I will get help here:</p>
<p>I want a python class where I import a function and use it there. The main code should be able to call the function from the class. for that I have two files in the same folder.</p>
<h... | 2 | 2016-06-28T22:06:14Z | 38,087,292 | <p>Everything defined inside the <em>namespace</em> of a class has to be accessed from that class. That holds for methods, variables, nested classes and everything else including modules.</p>
<p>If you really want to import a module inside a class you must access it from that class:</p>
<pre><code>class Test:
imp... | 3 | 2016-06-28T22:26:06Z | [
"python",
"class",
"import"
] |
Unittest __unittest_skip__ access in beforeTest method | 38,087,092 | <p>I am using the skip decorator for a test:</p>
<pre><code>@skip('I want this to skip')
def test_abc(self):
</code></pre>
<p>I also have a nose plugin to report test results with a defined </p>
<pre><code>def beforeTest(self, *args, **kwargs):
</code></pre>
<p>the test case <code>test_abc</code> is getting capture... | 1 | 2016-06-28T22:08:22Z | 38,087,223 | <p>Looking at the source code, there doesn't seem to be a <em>clean</em> way to do this. <code>TestCase</code> seems to know what method it is testing based on the <a href="https://hg.python.org/cpython/file/tip/Lib/unittest/case.py#l388" rel="nofollow"><code>_testMethodName</code></a> implementation detail. If you h... | 1 | 2016-06-28T22:19:28Z | [
"python",
"unit-testing",
"nose"
] |
Python Pandas SettingWithCopyWarning copies vs new objects | 38,087,204 | <p>I'm working with a dataframe 'copy' created by sub-setting a previous one - see below:</p>
<pre><code>import random
import pandas as pd
df = pd.DataFrame({'data':list(random.sample(range(10,100),25))})
df_filtered = df.query('data > 20 and data < 80')
df_filtered.rename(columns={'data':'observations'},inplace... | 1 | 2016-06-28T22:18:14Z | 38,087,271 | <p>You can always explicitly make a copy by calling <code>.copy()</code> on your filtered dataframe. Concretely, replace</p>
<pre><code>df_filtered = df.query('data > 20 and data < 80')
</code></pre>
<p>with</p>
<pre><code>df_filtered = df.query('data > 20 and data < 80').copy()
</code></pre>
<p>Does th... | 2 | 2016-06-28T22:24:34Z | [
"python",
"pandas"
] |
Python Pandas SettingWithCopyWarning copies vs new objects | 38,087,204 | <p>I'm working with a dataframe 'copy' created by sub-setting a previous one - see below:</p>
<pre><code>import random
import pandas as pd
df = pd.DataFrame({'data':list(random.sample(range(10,100),25))})
df_filtered = df.query('data > 20 and data < 80')
df_filtered.rename(columns={'data':'observations'},inplace... | 1 | 2016-06-28T22:18:14Z | 38,087,273 | <p>try this instead of using <code>inplace=True</code>:</p>
<pre><code>In [12]: df_filtered = df.query('data > 20 and data < 80')
In [13]: df_filtered = df_filtered.rename(columns={'data':'observations'})
</code></pre>
<p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.rename.ht... | 1 | 2016-06-28T22:24:52Z | [
"python",
"pandas"
] |
li a:nth-child with variable from Django doesn't work as expected | 38,087,260 | <p>I am currently working on a personal blog in Django to get better at web programming, but I have encountered a slight problem. My idea was to make the webpage able to know which menu element is the active one, passing an argument from the views.py and to the template. Thus, I am here to ask why that might be so.</p>... | 0 | 2016-06-28T22:23:30Z | 38,089,622 | <p>There are a couple of issues here: <code>nth-child</code> looks for the n-th child element in a group. Your code as it is currently would style the <code>n</code>th <code>a</code> element inside a <code>li</code> tag - but there's only ever one <code>a</code> in each <code>li</code>. You need to target the <code>li<... | 1 | 2016-06-29T02:58:16Z | [
"python",
"html",
"css",
"django"
] |
python flask can't find '__main__' module in '' | 38,087,283 | <p>Hi All I am just learning about flask. I have used pip to install it. Then when I run this basic code I get an error. Basically I see its working then abruptly exits with the following error. This maybe looks to be some environment issue but I'm not sure. The strange thing this was working the other day now it's not... | 1 | 2016-06-28T22:25:39Z | 38,087,811 | <p>You said, that the problem only occurs when you run the code from an interactive shell. It is caused by a feature in <code>werkzeug</code> (the wsgi server <code>flask</code> is based on).</p>
<p>In debug mode <code>werkzeug</code> will automatically restart your server if a project file is changed. Everytime a cha... | 2 | 2016-06-28T23:20:10Z | [
"python",
"python-3.x",
"flask"
] |
TypeError: sequence item 1:expected str instance, bytes found | 38,087,294 | <p>I want to download tweets from twitter as data sets for sentiment analysis using Python Twitter API ..</p>
<p>I am using SemEval 2016 task 6 dataset ..So I downloaded "<a href="http://alt.qcri.org/semeval2016/task6/data/uploads/semeval2016-task6-domaincorpus.zip" rel="nofollow">Domain corpus for task B</a>" and I f... | 0 | 2016-06-28T22:26:51Z | 38,100,912 | <p>The issue is with the last line of the <code>download_tweets_api.py</code> script. The script was written in Python 2 and would probably run seamlessly in Python 2. The main reason it is not running in Python 3 is that the last line is trying to <code>join</code> strings with bytes. However, in Python 3, <code>bytes... | 0 | 2016-06-29T13:23:30Z | [
"python",
"twitter"
] |
Prepopulating instances in code for classes (Python) | 38,087,304 | <p>I am trying to make it so that when I can run a function which would populate a class with a couple of instances which are contained within the code.</p>
<pre><code>class Pets(object):
def __init__(self, name, scientific_name, feet_number, type)
super(Pets,self).__init__()
self.name = name
self.scien... | 0 | 2016-06-28T22:27:45Z | 38,131,421 | <p>Is this what you are trying to do?</p>
<pre><code>class Pet(object):
def __init__(self, details):
self.name = details[0]
self.scientific_name = details[1]
self.feet_number = details[2]
self.type = details[3]
if __name__ == '__main__':
pet_list = [('Cat', 'Kitty Cat', 4, 'Cuddly'), ('Dog', 'Pu... | 0 | 2016-06-30T19:08:22Z | [
"python",
"class"
] |
Use large dataset in Tensorflow | 38,087,342 | <p>I would like to train a CNN with a large dataset. Currently I load all data into tf.constant and then loop through it with a small Batch size in tf.Session(). That works fine for a small fraction of the dataset, but when I increase the input size I get the error:</p>
<pre><code>ValueError: Cannot create a tensor pr... | 1 | 2016-06-28T22:31:12Z | 38,087,439 | <p>Do not load data to constant, it will be part of your computational graph.</p>
<p>You should rather:</p>
<ul>
<li>Create an op which is loading your data in stream fashion</li>
<li>Load data in python part, and use feed_dict to pass the batch into the graph</li>
</ul>
| 4 | 2016-06-28T22:42:27Z | [
"python",
"machine-learning",
"computer-vision",
"tensorflow"
] |
Use large dataset in Tensorflow | 38,087,342 | <p>I would like to train a CNN with a large dataset. Currently I load all data into tf.constant and then loop through it with a small Batch size in tf.Session(). That works fine for a small fraction of the dataset, but when I increase the input size I get the error:</p>
<pre><code>ValueError: Cannot create a tensor pr... | 1 | 2016-06-28T22:31:12Z | 38,483,880 | <p>This seems like a duplicate of this question:
<a href="http://stackoverflow.com/questions/35394103/initializing-tensorflow-variable-with-an-array-larger-than-2gb">Initializing tensorflow Variable with an array larger than 2GB</a></p>
<p>Copied the answer below:</p>
<p>The easiest solution is to feed_dict'ing it in... | 0 | 2016-07-20T14:21:07Z | [
"python",
"machine-learning",
"computer-vision",
"tensorflow"
] |
Logging from a child module ignores the added root logger stream handler | 38,087,371 | <p>My goal is to redirect logging messages from a certain function into a file. This function is defined in another module. I added <em>StreamHandler</em> to a main logger, but a message from a <em>child_call</em> function is not saved to <em>tmp.log</em> as expected.</p>
<pre><code># main.py
import logging
import os... | 0 | 2016-06-28T22:33:58Z | 38,087,696 | <p>The problem is that your loggers are not correctly chained. They need to have the same root name. For example:</p>
<pre><code># main.py
logger = logging.getLogger("parent")
# child_logger.py
logger = logging.getLogger("parent.child")
</code></pre>
<p>Both of your log retrievals just ask for a logger with <code>__... | 1 | 2016-06-28T23:08:47Z | [
"python",
"logging"
] |
What are the uses of iter(callable, sentinel)? | 38,087,427 | <p>So, I was watching Raymond Hettinger's talk <a href="https://www.youtube.com/watch?v=OSGv2VnC0go" rel="nofollow">Transforming Code into Beautiful, Idiomatic Python</a> and he brings up this form of <code>iter</code> which I was never aware of. His example is the following:</p>
<p>Instead of:</p>
<pre><code>blocks ... | 5 | 2016-06-28T22:41:23Z | 38,087,569 | <p>Here's a silly example I came up with:</p>
<pre><code>from functools import partial
from random import randint
pull_trigger = partial(randint, 1, 6)
print('Starting a game of Russian Roulette...')
print('--------------------------------------')
for i in iter(pull_trigger, 6):
print('I am still alive, selecte... | 5 | 2016-06-28T22:55:56Z | [
"python"
] |
What are the uses of iter(callable, sentinel)? | 38,087,427 | <p>So, I was watching Raymond Hettinger's talk <a href="https://www.youtube.com/watch?v=OSGv2VnC0go" rel="nofollow">Transforming Code into Beautiful, Idiomatic Python</a> and he brings up this form of <code>iter</code> which I was never aware of. His example is the following:</p>
<p>Instead of:</p>
<pre><code>blocks ... | 5 | 2016-06-28T22:41:23Z | 38,087,899 | <p>As a rule, the main uses I've seen for two arg iter involve converting functions that are similar to C APIs (implicit state, no concept of iteration) to iterators. File-like objects are a common example, but it shows up in other libraries that poorly wrap C APIs. The pattern you'd expect would be one seen in APIs li... | 2 | 2016-06-28T23:30:05Z | [
"python"
] |
TypeError: decoding str is not supported (Python 3.4) | 38,087,507 | <p>I'm receiving a strange error when trying to turn a bytes object into a string:</p>
<pre><code> Traceback (most recent call last):
File "/home/Scraper_v1.0.py", line 149, in <module>
rawjsonstr = str(rawjsonstr, 'utf-16')
TypeError: decoding str is not supported
</code></pre>
<p>My code is as follow... | -1 | 2016-06-28T22:50:49Z | 38,134,272 | <p>The error was being caused as a result of the program trying to parse an invalid JSON string: <a href="http://i.stack.imgur.com/uTA9n.png" rel="nofollow">JSON formatter</a></p>
<p><strong>Solution:</strong> Catch the error and append a '{' to the end of the string when it occurs.</p>
| 0 | 2016-06-30T22:29:48Z | [
"python",
"string",
"utf-8",
"decode",
"utf-16"
] |
Find the path of the file loading base class defining variable | 38,087,538 | <p>I have the following sample code:</p>
<pre><code>$ cat f1.py
class classA(object):
var1 = "something"
$ cat f2.py
from f1 import classA
class classB(classA):
pass
$ cat loader.py
#!/usr/bin/python -tt
from f2 import classB
if __name__ == "__main__":
for cl in classB.__mro__:
print cl.__module... | 1 | 2016-06-28T22:53:30Z | 38,087,891 | <p>You want the <a href="https://docs.python.org/2/library/inspect.html?highlight=getfile#inspect.getfile" rel="nofollow">inspect</a> module.</p>
<pre><code>import inspect
inspect.getfile(ClassA.__class__)
inspect.getfile(ClassB.__class__)
</code></pre>
| 2 | 2016-06-28T23:29:09Z | [
"python",
"python-2.7"
] |
Find the path of the file loading base class defining variable | 38,087,538 | <p>I have the following sample code:</p>
<pre><code>$ cat f1.py
class classA(object):
var1 = "something"
$ cat f2.py
from f1 import classA
class classB(classA):
pass
$ cat loader.py
#!/usr/bin/python -tt
from f2 import classB
if __name__ == "__main__":
for cl in classB.__mro__:
print cl.__module... | 1 | 2016-06-28T22:53:30Z | 38,088,006 | <p>The easiest thing to do is:</p>
<pre><code>sys.modules[__module__].__file__
</code></pre>
<p>We modify loader.py above to say:</p>
<pre><code>if __name__ == "__main__":
for cl in classB.__mro__:
print sys.modules[cl.__module__].__file__
$ ./loader.py
/Users/virgilg/Code/testing/python/f2.pyc
/Users/v... | 1 | 2016-06-28T23:42:12Z | [
"python",
"python-2.7"
] |
Need help creating curves based on set keyframe positions (maya/python) | 38,087,551 | <p>I'm trying to create a tool in maya using python that creates curves based on an objects keyframe positions. The end goal is to create different animation curves that the object can blend between so as to create adjustments to the main animation. Here's what I have so far. It creates a curve that follows the path of... | 0 | 2016-06-28T22:54:25Z | 38,087,739 | <p>If I understand you correctly, you'll want to iterate through key frames (using <a href="http://download.autodesk.com/us/maya/2011help/CommandsPython/keyframe.html#flagtimeChange" rel="nofollow">keyframe</a> timeChange query) rather than a start/end range stepping numCvs.</p>
<pre><code>keyframes = sorted(list(set(... | 2 | 2016-06-28T23:12:36Z | [
"python",
"animation",
"maya",
"curve",
"keyframe"
] |
How would I get the largest portion of valid HTML code given invalid input in Python? | 38,087,647 | <p>I would like to make some sort of HTML parser which takes in some code that is invalid: i.e. has a start tag without an end tag or vice versa, and return the largest portion of valid HTML. </p>
<p>Example Input:</p>
<pre><code> <h1>asdf</h1>
<p>p1</p>
<p... | 0 | 2016-06-28T23:02:44Z | 38,087,702 | <p>Something with a tag stack and a content stack:</p>
<ul>
<li>opening tag: push tag on tag stack</li>
<li>content : push on content stack</li>
<li>closing tag: pop and output opening tag, pop and output content, output closing tag</li>
</ul>
| 0 | 2016-06-28T23:09:06Z | [
"python",
"html"
] |
Convert string into ISO date python | 38,087,666 | <p>I'm using <code>postgresql</code>.On it I have data that I have to use on python.
One table field contains a date. It looks like this:</p>
<p><a href="http://i.stack.imgur.com/7Ur5a.png" rel="nofollow"><img src="http://i.stack.imgur.com/7Ur5a.png" alt="enter image description here"></a></p>
<p>On my python script... | 1 | 2016-06-28T23:05:26Z | 38,087,912 | <p>Replace this</p>
<pre><code>query = "SELECT name, created FROM user;"
</code></pre>
<p>by this</p>
<pre><code>query = "SELECT name, 'ISODate(\"' || created || '\")' FROM user;"
</code></pre>
<p>The query will return the well formed string you want to store as <code>created</code>.</p>
| 0 | 2016-06-28T23:31:31Z | [
"python",
"mongodb",
"postgresql",
"date",
"psycopg2"
] |
Convert string into ISO date python | 38,087,666 | <p>I'm using <code>postgresql</code>.On it I have data that I have to use on python.
One table field contains a date. It looks like this:</p>
<p><a href="http://i.stack.imgur.com/7Ur5a.png" rel="nofollow"><img src="http://i.stack.imgur.com/7Ur5a.png" alt="enter image description here"></a></p>
<p>On my python script... | 1 | 2016-06-28T23:05:26Z | 38,096,998 | <p>IMO you does not need to specify <code>ISODate</code> when you store the data into the MongoDB.</p>
<p>Python code (fragment):</p>
<pre><code>cur.execute("select name, created from tt_user;")
data = cur.fetchall()
for row in data:
print(row[0], row[1])
mdr = {
'user': row[0],
'created': row... | 1 | 2016-06-29T10:30:52Z | [
"python",
"mongodb",
"postgresql",
"date",
"psycopg2"
] |
Detecting ordered iterables (sequences) in python | 38,087,720 | <p>I am attempting to build a function that takes an iterable and returns a tuple, provided that the iterable will always be iterated over in a canonical way. For example, if the input iterable is <code>list</code> or <code>tuple</code>-like, I want to accept the input, but not if it is <code>dict</code>-like (where t... | 2 | 2016-06-28T23:10:42Z | 38,087,770 | <p>There's no such function. Even with generators, you'd want to be able to catch</p>
<pre><code>(x for x in {1, 2, 3})
</code></pre>
<p>but permit</p>
<pre><code>(x for x in [1, 2, 3])
</code></pre>
<p>I'd recommend just raising a warning if <code>type(x) is dict</code>. Not even <code>isinstance(x, dict)</code>, ... | 2 | 2016-06-28T23:15:29Z | [
"python"
] |
Detecting ordered iterables (sequences) in python | 38,087,720 | <p>I am attempting to build a function that takes an iterable and returns a tuple, provided that the iterable will always be iterated over in a canonical way. For example, if the input iterable is <code>list</code> or <code>tuple</code>-like, I want to accept the input, but not if it is <code>dict</code>-like (where t... | 2 | 2016-06-28T23:10:42Z | 38,087,835 | <p>You may want to check if slicing operation is defined:</p>
<pre><code>def to_tuple(x):
return tuple(x[:])
</code></pre>
<p>That rules out dictionaries, generators, but welcomes strings, tuples, lists...</p>
| 0 | 2016-06-28T23:22:45Z | [
"python"
] |
pylint, coroutines, decorators and type inferencing | 38,087,760 | <p>I'm working on a Google AppEngine project and I recently upgraded my pylint version to:</p>
<pre><code>No config file found, using default configuration
pylint 1.5.6,
astroid 1.4.6
Python 2.7.10 (default, Oct 23 2015, 19:19:21)
</code></pre>
<p>This seems to have broken some type inferencing. Specifically, GAE's... | 0 | 2016-06-28T23:14:28Z | 38,094,620 | <p>That blog post is definitely very old, things have changed for a while now.</p>
<p>You might take a look at the way how astroid's brain modules are implemented (<a href="https://github.com/PyCQA/astroid/tree/master/astroid/brain" rel="nofollow">https://github.com/PyCQA/astroid/tree/master/astroid/brain</a>). They u... | 1 | 2016-06-29T08:49:04Z | [
"python",
"pylint"
] |
pylint, coroutines, decorators and type inferencing | 38,087,760 | <p>I'm working on a Google AppEngine project and I recently upgraded my pylint version to:</p>
<pre><code>No config file found, using default configuration
pylint 1.5.6,
astroid 1.4.6
Python 2.7.10 (default, Oct 23 2015, 19:19:21)
</code></pre>
<p>This seems to have broken some type inferencing. Specifically, GAE's... | 0 | 2016-06-28T23:14:28Z | 38,521,386 | <p>With the advice from PCManticore above, I've been able to hack this together:</p>
<pre><code>"""Brains for helping silence pylint errors/warnings from ndb."""
import astroid
def _is_tasklet(node):
"""Check whether a FunctionDef node is decorated with ndb.tasklet."""
if not node.decorators:
return ... | 0 | 2016-07-22T08:10:31Z | [
"python",
"pylint"
] |
Reading no-header CSV to pandas dataframe and parsing date | 38,087,790 | <p>I am trying to read similar to below CSV file to pandas.DataFrame:</p>
<pre><code>2011 1 10 AAPL Buy 1500
2011 1 13 AAPL Sell 1500
2011 1 13 IBM Buy 4000
2011 1 26 GOOG Buy 1000
</code></pre>
<p>Data doesn't have column headers. When I read that file I also want ... | 0 | 2016-06-28T23:17:46Z | 38,087,822 | <p>try to add:</p>
<pre><code>sep='\s+'
</code></pre>
<p>or</p>
<pre><code>delim_whitespace=True
</code></pre>
<p>parameter</p>
<p>Demo:</p>
<pre><code>In [7]: %paste
(pd.read_csv(fileName, sep='\s+', header = None,
names = ('Year', 'Month', 'Day', 'Symbol', 'Side', 'Quantity'),
parse_da... | 1 | 2016-06-28T23:21:28Z | [
"python",
"csv",
"pandas",
"dataframe"
] |
Using Python, trying to save an xml file with hex-coded html escape characters | 38,087,831 | <p>I am using ElementTree. I have a parsed xml document that looks like this:</p>
<pre><code><data>
<name>
<slash>/</slash>
</name>
</data>
</code></pre>
<p>I would like to be able to save it using a hex code for the html escape character.</p>
<p>Since the <a href... | 0 | 2016-06-28T23:22:26Z | 38,087,865 | <p>You can use the codecs module (included in python)</p>
<pre><code>import codecs
def returnHex(input):
hexitup = codecs.getencoder('hex')
return ("&#" + hexitup(input)[0]+";")
print(returnHex('/'))
</code></pre>
<p>This should return &#2f;</p>
| 1 | 2016-06-28T23:25:38Z | [
"python",
"xml",
"python-2.7",
"hex",
"ascii"
] |
Using Python, trying to save an xml file with hex-coded html escape characters | 38,087,831 | <p>I am using ElementTree. I have a parsed xml document that looks like this:</p>
<pre><code><data>
<name>
<slash>/</slash>
</name>
</data>
</code></pre>
<p>I would like to be able to save it using a hex code for the html escape character.</p>
<p>Since the <a href... | 0 | 2016-06-28T23:22:26Z | 38,088,234 | <p>Using lxml:</p>
<pre><code>x = """<data>
<name>
<slash>/</slash>
</name>
</data>"""
import lxml.etree as et
xml_doc = et.fromstring(x)
for node in xml_doc.xpath("//*[contains(text(), '/')]"):
node.text = node.text.replace("/","&#x2f;")
print(et.tostrin... | 1 | 2016-06-29T00:08:51Z | [
"python",
"xml",
"python-2.7",
"hex",
"ascii"
] |
how to use genderize package for python with big datasets? | 38,087,873 | <p>I am using genderize package for python to infer the gender of names. I have a csv file of more than 7 thousands of names. In my code, the csv file is passed into the genderize function. I want the function to return the gender for all of the names in the file, however, it only returns the gender of the first 10 nam... | 0 | 2016-06-28T23:27:00Z | 38,087,909 | <p>The API is limited to a maximum of 10 names per request. Split your list and do multiple calls. And read the manual: <a href="https://genderize.io/" rel="nofollow">https://genderize.io/</a></p>
| 0 | 2016-06-28T23:31:17Z | [
"python",
"api",
"packages"
] |
How do I fix: TypeError: object() takes no parameters? | 38,088,087 | <p>Here's my program:</p>
<pre><code>class member:
name = ""
phone = ""
number = 0
def init(self, name, phone, number):
self.name = name
self.phone = phone
self.number = number
def setName(self, name):
self.name = name
def setPhone(self, phone):
sel... | 0 | 2016-06-28T23:50:56Z | 38,088,109 | <p>You named your initializer method <code>init</code>; the correct name is <a href="https://docs.python.org/3/reference/datamodel.html?highlight=__init__#object.__init__" rel="nofollow"><code>__init__</code></a>. The double underscores are how Python indicates names reserved for Python "special" use. By not using the ... | 3 | 2016-06-28T23:53:37Z | [
"python"
] |
How do I fix: TypeError: object() takes no parameters? | 38,088,087 | <p>Here's my program:</p>
<pre><code>class member:
name = ""
phone = ""
number = 0
def init(self, name, phone, number):
self.name = name
self.phone = phone
self.number = number
def setName(self, name):
self.name = name
def setPhone(self, phone):
sel... | 0 | 2016-06-28T23:50:56Z | 38,088,119 | <p>You're missing __. Your</p>
<pre><code> def init(self, name, phone, number):
self.name = name
self.phone = phone
self.number = number
</code></pre>
<p>has to be</p>
<pre><code>def __init__(self, name, phone, number):
self.name = name
self.phone = phone
self.number = number
</c... | 0 | 2016-06-28T23:54:37Z | [
"python"
] |
How to read custom data format in Tensorflow using FixedLengthRecordReader? | 38,088,098 | <p>I am doing some experiments while reading data using <strong>Tensorflow</strong> queue, and I would like to ask a simple case below. </p>
<p>Assume my binary data files have a list of a <code>float</code> value (4byte) and <code>boolean</code> label (1byte). For example </p>
<pre><code>3.4 true 2.1 false 0.3 true ... | 1 | 2016-06-28T23:52:25Z | 38,104,537 | <p>Try something like this:</p>
<pre><code>data_part = tf.bitcast(tf.slice(value, [0], [data_bytes]), tf.float32)
</code></pre>
<p>i.e., use <code>tf.bitcast</code> to convert 4 uint8s into a float32, instead of using <code>tf.cast</code>.</p>
| 2 | 2016-06-29T15:52:17Z | [
"python",
"tensorflow"
] |
Python: Simple Web Crawler using BeautifulSoup4 | 38,088,180 | <p>I have been following TheNewBoston's Python 3.4 tutorials that use Pycharm, and am currently on the tutorial on how to create a web crawler. I Simply want to download all of XKCD's Comics. Using the archive that seemed very easy. Here is <a href="http://pastebin.com/eNTPqGQn" rel="nofollow">my code</a>, followed by ... | 1 | 2016-06-29T00:02:13Z | 38,088,437 | <p>The <em>comic</em> is in the div with the id <em>comic</em>, you just need to pull the <em>src</em> from <em>img</em> inside that div then join it to the <em>base</em> url and finally request the content and write, I use the <em>basename</em> as the name to save the file under.</p>
<p>I also replaced your while wit... | 1 | 2016-06-29T00:34:54Z | [
"python",
"web",
"beautifulsoup"
] |
Pandas dataframe: how to cluster together groups by values without machine learning? | 38,088,200 | <p>I have the following pandas DataFrame.</p>
<pre><code>import pandas as pd
df = pd.read_csv('filename.csv')
print(df)
A B C D
0 2 0 11 0.053095
1 2 0 11 0.059815
2 0 35 11 0.055268
3 0 35 ... | -1 | 2016-06-29T00:04:58Z | 38,088,702 | <p>A pure pandas solution would involve binning, assuming that your values are close to each other and your bin size is large enough for cluster variation but smaller than distance between cluster values. That answer depends on your data.</p>
<p>The binning approach uses the <code>cut</code> function in pandas. You pr... | 1 | 2016-06-29T01:09:50Z | [
"python",
"pandas",
"dataframe",
"group-by"
] |
Replace all 1's at a given index - numpy | 38,088,323 | <p>I have a binary matrix of size <code>10-by-10</code>. I wanted to change all the <code>1's</code> in the matrix at a given index to <code>-1</code></p>
<p>I was able to get something like this</p>
<pre><code>import numpy as np
mat = np.random.randint(2, size=(10, 10))
index = [6,7,8,9]
mat[(mat[index,:] == 1).non... | 2 | 2016-06-29T00:19:05Z | 38,088,350 | <p>Use <code>numpy.where</code> to select conditionally elements based on <code>mat</code>:</p>
<pre><code>import numpy as np
mat = np.random.randint(2, size=(10, 10))
index = [6,7,8,9]
mat[index,:] = np.where(mat[index,:],-1,mat[index,:])
print(mat)
</code></pre>
<p>This will overwrite the given rows of <code>mat</... | 2 | 2016-06-29T00:23:04Z | [
"python",
"numpy"
] |
How to use same port twice in Python | 38,088,342 | <p>Even with the REUSEADDR option, I still cannot reuse the same set of ports. It gives me a 98, "address already in use" error.</p>
<p>Is there a way to kill the first group of sockets before the second group, or fix this?</p>
<p>In the code below, I'm doing the exact same thing twice.</p>
<pre><code>servers = []
p... | 0 | 2016-06-29T00:20:56Z | 38,088,349 | <p>You need to close your server sockets after you're done with them. <code>SO_REUSEADDR</code> doesn't let you use the address of an <em>open</em> socket, only one that has been recently closed but is still lingering in the <code>TIME_WAIT</code> state.</p>
| 3 | 2016-06-29T00:22:52Z | [
"python",
"sockets",
"networking"
] |
How to use same port twice in Python | 38,088,342 | <p>Even with the REUSEADDR option, I still cannot reuse the same set of ports. It gives me a 98, "address already in use" error.</p>
<p>Is there a way to kill the first group of sockets before the second group, or fix this?</p>
<p>In the code below, I'm doing the exact same thing twice.</p>
<pre><code>servers = []
p... | 0 | 2016-06-29T00:20:56Z | 38,090,209 | <p>Try something like this -- SO_REUSEPORT vs SO_REUSEADDR and you were appending into the same server list. Does it work for you ?</p>
<pre><code>#!/usr/bin/env python
import os
import sys
import socket
import select
while True:
servers = []
port_list = [i for i in range(40007, 40107)]
for port in port_... | 1 | 2016-06-29T04:08:48Z | [
"python",
"sockets",
"networking"
] |
Memory error while caching heavy data with Django | 38,088,372 | <p>I'm using Django in order to archive a web with dynamically generated images from a big image stack (around 150mb each). It's suppose to be interactive so I need to keep cached the selected stack. For this, I'm using the memcached cache backend and the "django.contrib.sessions.backends.cache" session engine.</p>
<p... | 0 | 2016-06-29T00:25:21Z | 38,237,561 | <p>Ideally the memcached server should not be on the same host as your web server. A standard memcached installation will have multiple memcached instances be running standalone on its own individual servers located close to the web servers and the web servers talking to them over the network. More elaborate installati... | 0 | 2016-07-07T04:30:52Z | [
"python",
"django",
"caching",
"memcached",
"django-sessions"
] |
Access a list within an element of a Pandas DataFrame | 38,088,419 | <p>I have a Pandas <code>DataFrame</code> which has a list of integers inside one of the columns. I'd like to access the individual elements within this list. I've found a way to do it by using <code>tolist()</code> and turning it back into a <code>DataFrame</code>, but I am wondering if there is a simpler/better way. ... | 1 | 2016-06-29T00:32:26Z | 38,088,490 | <p>One option is to use the <code>apply</code>, which should be faster than creating a data frame out of it:</p>
<pre><code>df['C'] = df['A'] + df.apply(lambda row: row['B'][1], axis = 1)
</code></pre>
<p>Some speed test:</p>
<pre><code>%timeit df['C'] = df['A'] + pd.DataFrame(df['B'].tolist())[1]
# 1000 loops, bes... | 1 | 2016-06-29T00:42:15Z | [
"python",
"list",
"pandas",
"indexing",
"dataframe"
] |
Access a list within an element of a Pandas DataFrame | 38,088,419 | <p>I have a Pandas <code>DataFrame</code> which has a list of integers inside one of the columns. I'd like to access the individual elements within this list. I've found a way to do it by using <code>tolist()</code> and turning it back into a <code>DataFrame</code>, but I am wondering if there is a simpler/better way. ... | 1 | 2016-06-29T00:32:26Z | 38,088,525 | <p>A bit more straightforward is:</p>
<pre><code>df['C'] = df['A'] + df['B'].apply(lambda x:x[1])
</code></pre>
| 2 | 2016-06-29T00:46:45Z | [
"python",
"list",
"pandas",
"indexing",
"dataframe"
] |
Python Search for File Unknown Extension | 38,088,633 | <p>New to python, apologies if this is a simple question. I've searched around a bit and found plenty on searching for files with an unknown name and known file extension, but not a known name and unknown extension, and if nobody minds I could use a little help getting my code to run correctly.</p>
<p>What I'm attempt... | 0 | 2016-06-29T01:00:01Z | 38,088,715 | <p>Why are you reglobbing to search? It means you end up rescanning directories repeatedly, when <code>os.walk</code> is giving you the names, so you can just check them directly using <a href="https://docs.python.org/3/library/os.path.html#os.path.splitext" rel="nofollow"><code>os.path.splitext</code></a> to do extens... | 2 | 2016-06-29T01:11:05Z | [
"python",
"python-2.7",
"os.walk"
] |
Pandas: convert categories to numbers | 38,088,652 | <p>Suppose I have a dataframe with countries that goes as:</p>
<pre><code>cc | temp
US | 37.0
CA | 12.0
US | 35.0
AU | 20.0
</code></pre>
<p>I know that there is a pd.get_dummies function to convert the countries to 'one-hot encodings'. However, I wish to convert them to indices instead such that I will get <code>cc_... | 1 | 2016-06-29T01:02:28Z | 38,089,089 | <p>First, change the type of the column:</p>
<pre><code>df.cc = pd.Categorical(df.cc)
</code></pre>
<p>Now the data look similar but are stored categorically. To capture the category codes:</p>
<pre><code>df['code'] = df.cc.cat.codes
</code></pre>
<p>Now you have:</p>
<pre><code> cc temp code
0 US 37.0 ... | 4 | 2016-06-29T01:58:48Z | [
"python",
"pandas"
] |
Python: How to instantiate an object, then access it in imported module? | 38,088,657 | <p>I'm fairly new to programming, trying to make a basic text-based game. I have a central 'hub' which imports modules for character creation and things like fighting and visiting markets. My question is this:</p>
<p>I instantiate an object 'player' from class 'Player' in the hub script. I then import the 'shops' scri... | -3 | 2016-06-29T01:03:05Z | 38,088,679 | <p>The most straight-forward way would be to pass it as an argument to whatever functions you are calling.</p>
| 1 | 2016-06-29T01:06:07Z | [
"python"
] |
Python: How to instantiate an object, then access it in imported module? | 38,088,657 | <p>I'm fairly new to programming, trying to make a basic text-based game. I have a central 'hub' which imports modules for character creation and things like fighting and visiting markets. My question is this:</p>
<p>I instantiate an object 'player' from class 'Player' in the hub script. I then import the 'shops' scri... | -3 | 2016-06-29T01:03:05Z | 38,088,723 | <p>Basicly check:
<a href="http://wiki.python-ogre.org/index.php?title=Game_State_Management" rel="nofollow">http://wiki.python-ogre.org/index.php?title=Game_State_Management</a></p>
<p>Read about Singletons.</p>
| 1 | 2016-06-29T01:12:17Z | [
"python"
] |
ValueError: chr() arg not in range(0x110000) | 38,088,859 | <p>Writing a decoding program and keep running into the ValueError: chr() arg not in range(0x110000) when I input the string I need to decode.</p>
<p>The input string is:</p>
<pre><code>[2ea^W_`^k2eiWSd2fZSf2[2S_2gb2fa2`a2YaaV@
</code></pre>
<p>The code is as follows curently:</p>
<pre><code># String manipulation
#... | 0 | 2016-06-29T01:30:43Z | 38,088,964 | <p>Just use:</p>
<pre><code> coded_message=raw_input("What is the line to be decoded?")
</code></pre>
<p>instead of</p>
<pre><code> coded_message=input("What is the line to be decoded?")
</code></pre>
<p>This should fix, so</p>
<pre><code>print("This progam can decode an encrypted by a known encryption key")
decod... | 1 | 2016-06-29T01:46:09Z | [
"python"
] |
ValueError: chr() arg not in range(0x110000) | 38,088,859 | <p>Writing a decoding program and keep running into the ValueError: chr() arg not in range(0x110000) when I input the string I need to decode.</p>
<p>The input string is:</p>
<pre><code>[2ea^W_`^k2eiWSd2fZSf2[2S_2gb2fa2`a2YaaV@
</code></pre>
<p>The code is as follows curently:</p>
<pre><code># String manipulation
#... | 0 | 2016-06-29T01:30:43Z | 38,089,031 | <p>Maybe when you subtract 18 from original ascii value, it goes out of range,i.e, less than 0.</p>
| 0 | 2016-06-29T01:53:13Z | [
"python"
] |
Recursion Code Failing | 38,088,968 | <p>New to python - appreciate help getting function dot working and understanding what I'm doing wrong.</p>
<pre><code> def dot(l,k): """multiply each elements in list l with each element from list k and return the total
"""
total = 0
if l == [] or '':
return
else:
last_l = l[-1]
... | 0 | 2016-06-29T01:46:33Z | 38,089,111 | <p>You can do it using map and reduce on a much simpler way:</p>
<pre><code>l1=[1,2]
l2=[2,3]
mult = lambda l1,l2: [x*y for x,y in zip(l1,l2)]
print reduce(lambda x,y: x+y,mult(l1,l2))
</code></pre>
| 0 | 2016-06-29T02:01:27Z | [
"python",
"recursion"
] |
Python | how to print multiple rows of alphabet? | 38,088,991 | <p>I am trying to get multiple lines of the alphabet but it isn't working. At the moment I have 1 row but it won't work.</p>
<p>What I'm after is once the alphabet gets from <code>a</code> to <code>z</code>, it will add another letter on until <code>aa</code> to <code>zz</code> and on and on.</p>
<p>As Requested, the... | -1 | 2016-06-29T01:49:34Z | 38,089,091 | <p>I would recommend using nested for loops. The outer for loop will iterate through the alphabet, while the outer defines the number of times you want to add a given letter. Note that some string s times some integer i duplicates that string i times. This gives us:</p>
<pre><code>for i in range(...) #However many ... | 0 | 2016-06-29T01:58:56Z | [
"python"
] |
Merge a list of pandas dataframes | 38,089,010 | <p>There has been many similar questions but none specifically to this.</p>
<p>I have a list of data frames and I need to merge them together using a unique column <code>(date)</code>. Field names are different so concat is out. </p>
<p>I can manually use <code>df[0].merge(df[1],on='Date').merge(df[3],on='Date)</code... | 1 | 2016-06-29T01:51:10Z | 38,089,112 | <p>You can use <code>reduce</code> function where <code>dfList</code> is your list of data frames:</p>
<pre><code>import pandas as pd
reduce(lambda x, y: pd.merge(x, y, on = 'Date'), dfList)
</code></pre>
<p>As a demo:</p>
<pre><code>df = pd.DataFrame({'Date': [1,2,3,4], 'Value': [2,3,3,4]})
dfList = [df, df, df]
df... | 5 | 2016-06-29T02:01:34Z | [
"python",
"pandas",
"dataframe"
] |
Is `with` statement __enter__ and __exit__ thread safe? | 38,089,037 | <p>Suppose:</p>
<pre><code>class A(object):
def __init__(self):
self.cnt = 0
def __enter__(self):
self.cnt += 1
def __exit__(self, exc_type, exc_value, traceback)
self.cnt -= 1
</code></pre>
<ol>
<li>Is it possible that <code>self.cnt += 1</code> might be executed twice when multi-threading?</li>
<l... | 0 | 2016-06-29T01:53:39Z | 38,089,570 | <p>No, thread safety can only be guaranteed through locks.</p>
<blockquote>
<p>Is it possible that <code>self.cnt += 1</code> might be executed twice when multi-threading?</p>
</blockquote>
<p>If you have two threads running that, it will be executed twice. Three threads, thrice, etc. I am not sure what you really ... | 0 | 2016-06-29T02:52:41Z | [
"python",
"thread-safety",
"with-statement"
] |
How to delete entire row of data set given a condition on a column in csv file? | 38,089,040 | <p>Here is a snippet of the following data-set in csv format:</p>
<pre><code>quantity revenue time_x transaction_id user_id
1 0 57:57.0 0 0 0
1 0 18:59.0 0 1
</code></pre>
<p>I want to delete the entire row when the user_id is empty. How do I do this ... | 0 | 2016-06-29T01:53:56Z | 38,089,099 | <p>With Pandas:</p>
<pre><code>import pandas as pd
df = pd.read_csv("path/to/csv/data.csv", delimiter=';', error_bad_lines=False)
df = df[pd.notnull(df.user_id)] # boolean indexing
# Shift user_id to first column
df = df.set_index("user_id")
df = df.reset_index()
df.to_csv("path/to/csv/data.csv", index=False)
</cod... | 2 | 2016-06-29T01:59:49Z | [
"python",
"csv",
"pandas",
"extract",
"isnullorempty"
] |
How to delete entire row of data set given a condition on a column in csv file? | 38,089,040 | <p>Here is a snippet of the following data-set in csv format:</p>
<pre><code>quantity revenue time_x transaction_id user_id
1 0 57:57.0 0 0 0
1 0 18:59.0 0 1
</code></pre>
<p>I want to delete the entire row when the user_id is empty. How do I do this ... | 0 | 2016-06-29T01:53:56Z | 38,089,840 | <p>Different style: get the data, join then delete. Keep the namespace clean. </p>
<pre><code>activity = pd.read_csv("activity(delimited).csv", delimiter=';', error_bad_lines=False)
impression = pd.read_csv("impression(delimited).csv", delimiter=';', error_bad_lines=False)
pre_merge = activity.merge(impression, on=... | 0 | 2016-06-29T03:22:53Z | [
"python",
"csv",
"pandas",
"extract",
"isnullorempty"
] |
Calculating geographic distances in python | 38,089,173 | <p>I am new in python so I don't really know how to manipulate arrays.
I have a large JSON file than contains geographic location an example of this is:</p>
<blockquote>
<p>{"items":[{"language":"en","created":"2013-12-17T09:31:31.000+01:00","geometry":{"type":"Point","<strong>coordinates":[9.2056232,45.4825264]</st... | 0 | 2016-06-29T02:07:09Z | 38,089,225 | <p>First you have to extract the latitude and longitude in your files. See json module for a json file for example. <a href="https://docs.python.org/2/library/json.html" rel="nofollow">https://docs.python.org/2/library/json.html</a></p>
<p>To calculate the distance between two points on a sphere given the angles (lati... | 0 | 2016-06-29T02:13:05Z | [
"python",
"arrays",
"coordinates"
] |
Calculating geographic distances in python | 38,089,173 | <p>I am new in python so I don't really know how to manipulate arrays.
I have a large JSON file than contains geographic location an example of this is:</p>
<blockquote>
<p>{"items":[{"language":"en","created":"2013-12-17T09:31:31.000+01:00","geometry":{"type":"Point","<strong>coordinates":[9.2056232,45.4825264]</st... | 0 | 2016-06-29T02:07:09Z | 38,089,387 | <pre><code>import pandas as pd
from vincenty import vincenty
df1 = pd.read_json(data.json)
df2 = pd.read_csv(data.csv)
results = []
for i1, d1 in df1.iterrows():
for i2, d2 in df2.iterrows():
distances.append({
"index1": i1,
"index2": i2,
"results": vincenty((d1.coo... | 2 | 2016-06-29T02:32:49Z | [
"python",
"arrays",
"coordinates"
] |
How do I use SWIG to return specific exceptions based on C function return type? | 38,089,206 | <p>Here are examples of functions in my C API:</p>
<pre><code>int do_something(struct object *with_this)
struct object *get_something(struct object *from_this)
</code></pre>
<p><code>do_something</code> will return <code>0</code> for success or <code>-1</code> and set <code>errno</code> for failure. <code>get_somethi... | 0 | 2016-06-29T02:10:51Z | 38,191,420 | <p>To help answer this question I took your functions and created the following test.h file that included enough real code to actually illustrate the problem:</p>
<pre class="lang-c prettyprint-override"><code>struct object { int bar; };
static int do_something(struct object *with_this) {
errno = EACCES;
return ... | 0 | 2016-07-04T19:50:47Z | [
"python",
"c",
"swig"
] |
python rename header row after w.writerow is finished | 38,089,295 | <p>In the below script, I cannot figure out how to either rename or "faux-rename" the headers.</p>
<pre><code>import csv,time,string,os
print "rendering report. This will take a few minutes..."
raw_report = "\\\\network\\x\\RAWREPORT.csv"
today = time.strftime("%Y-%m-%d")
fields = ["As of Date", "EB", "Cycle", "Co... | 0 | 2016-06-29T02:21:27Z | 38,103,444 | <p>I was thinking about this incorrectly. I can define <code>fields</code> as the columns in the original file to pull from, but I don't need to include those necessarily in the output file as they are two separate files.</p>
<p>This code works:</p>
<pre><code>fields = ["As of Date", "EB", "Cycle", "Col", "APP Name"... | 0 | 2016-06-29T15:04:57Z | [
"python"
] |
Pycharm cannot recognize print option args | 38,089,305 | <p>I am using PyCharm CE 2016.2 and python interpreter 3.5. When I tried to type the following in console, the file is generated with '123'.</p>
<pre><code>>>> with open('man_data.txt', 'w') as data:
print('123', file=data)
</code></pre>
<p>However, when I put the same statement into a test.py file a... | 0 | 2016-06-29T02:23:13Z | 38,105,860 | <p><code>Python 2</code> is started when you call <code>subprocess.call(['python', 'test.py'])</code>.</p>
<p>Try to change to <code>subprocess.call(['python3', 'test.py'])</code> or update the script as described <a href="http://stackoverflow.com/questions/9316023/python-2-7-print-to-file">here</a>.</p>
| 0 | 2016-06-29T16:58:36Z | [
"python",
"printing",
"pycharm"
] |
Python subprocess.call with multiline string EOF | 38,089,315 | <p>I've hit a issue that I don't really understand how to overcome. I'm trying to create a subprocess in python to run another python script. Not too difficult. The issue is I'm unable to get around is EOF error when a python file includes a super long string.</p>
<p>Here's an example of what my files look like.</p>
... | 0 | 2016-06-29T02:24:38Z | 38,089,860 | <p>Answering my own question here; my problem was that I didn't <code>file.close()</code> before trying to execute a <code>subprocess.call</code>. </p>
<p>If you encounter this problem, and are working with recently written files this could be your issue too. Thank you to everyone who read or responded to this thread.... | 0 | 2016-06-29T03:24:56Z | [
"python",
"python-2.7",
"shell",
"subprocess"
] |
Why is my condition expression giving a syntax error? | 38,089,322 | <pre class="lang-py prettyprint-override"><code>def singleNumber(nums):
for num in set(nums):
return num if nums.count(num) != 2 #error occurs here
print(singleNumber([1,1,4,5,5]))
</code></pre>
<p>This follows the usual python condition expression format. I don't understand why it's giving me a syntax e... | 0 | 2016-06-29T02:25:14Z | 38,089,341 | <p>Because you forgot to write what the result should be if the condition is false.</p>
<pre><code>return num if nums.count(num) != 2 else ...what?
</code></pre>
<p>And if you didn't want that then you should write a normal <code>if</code> statement instead.</p>
| 0 | 2016-06-29T02:27:55Z | [
"python"
] |
Why is my condition expression giving a syntax error? | 38,089,322 | <pre class="lang-py prettyprint-override"><code>def singleNumber(nums):
for num in set(nums):
return num if nums.count(num) != 2 #error occurs here
print(singleNumber([1,1,4,5,5]))
</code></pre>
<p>This follows the usual python condition expression format. I don't understand why it's giving me a syntax e... | 0 | 2016-06-29T02:25:14Z | 38,089,367 | <p>If you're going to actually execute a <code>return</code>, you must return <em>something</em> no matter what.</p>
<p>So you could <em>try</em>:</p>
<pre><code>return num if nums.count(num) != 2 else None
</code></pre>
<p>However, that's not going to work in this case since it will return on the <em>first</em> che... | 3 | 2016-06-29T02:30:17Z | [
"python"
] |
Why is my condition expression giving a syntax error? | 38,089,322 | <pre class="lang-py prettyprint-override"><code>def singleNumber(nums):
for num in set(nums):
return num if nums.count(num) != 2 #error occurs here
print(singleNumber([1,1,4,5,5]))
</code></pre>
<p>This follows the usual python condition expression format. I don't understand why it's giving me a syntax e... | 0 | 2016-06-29T02:25:14Z | 38,089,368 | <p>When you use a ternary conditional operator both if and else part are mandatory.</p>
<pre><code>return num if nums.count(num) != 2 else <missing???>
</code></pre>
| 0 | 2016-06-29T02:30:20Z | [
"python"
] |
In Python, How do I make my conditional if loop not execute if input is valid? | 38,089,340 | <pre><code>#Write a short program that will do the following
#Set a value your favorite number between 0 and 100
#Ask the user to guess your favorite number between 0 and 100
#Repeat until they guess that number and tell them how many tries it took
#If the value they guessed is not between 0 and 100
#tell the user inva... | 0 | 2016-06-29T02:27:48Z | 38,089,424 | <p>In Python 2.7.10 it appears that if you do not convert a string to an integer, it accepts it but all rules that apply to numbers return false.
Here is a working example:</p>
<pre><code>favoriteNumber = 7
attempts = 0
guess = raw_input("Guess a number between 0 and 100: ")
if (int(guess) < 0) or (int(guess) &g... | 0 | 2016-06-29T02:36:29Z | [
"python",
"validation",
"loops",
"input"
] |
In Python, How do I make my conditional if loop not execute if input is valid? | 38,089,340 | <pre><code>#Write a short program that will do the following
#Set a value your favorite number between 0 and 100
#Ask the user to guess your favorite number between 0 and 100
#Repeat until they guess that number and tell them how many tries it took
#If the value they guessed is not between 0 and 100
#tell the user inva... | 0 | 2016-06-29T02:27:48Z | 38,089,427 | <p>you raw_input returns a string, which is always <code>></code> 100. Cast it to a number with <code>int(raw_input())</code></p>
| 0 | 2016-06-29T02:36:32Z | [
"python",
"validation",
"loops",
"input"
] |
In Python, How do I make my conditional if loop not execute if input is valid? | 38,089,340 | <pre><code>#Write a short program that will do the following
#Set a value your favorite number between 0 and 100
#Ask the user to guess your favorite number between 0 and 100
#Repeat until they guess that number and tell them how many tries it took
#If the value they guessed is not between 0 and 100
#tell the user inva... | 0 | 2016-06-29T02:27:48Z | 38,089,444 | <p>Use input and not raw_input,so you get integer and not string </p>
<pre><code>favoriteNumber = 7
attempts = 0
while True:
guess = input("Guess a number between 0 and 100: ")
if (guess < 0) or (guess > 100):
attempts=attempts+1
print "Invalid guess. Try again"
else:
atte... | 0 | 2016-06-29T02:38:31Z | [
"python",
"validation",
"loops",
"input"
] |
Making new list of list with some condition of other list | 38,089,353 | <p>I am new to python and still struggle with it.
So can you guys help me with this?</p>
<p>I have this list of lists:</p>
<pre><code>sorted_Region: [[J, 0.80, 0.30], [H, 0.80, 0.21], [I, 0.87, 0.19], [G, 0.88, 0.15], [D, 0.96, 0.14], [B, 0.97, 0.14], [A, 1.01, 0.11], [C, 1.05, 0.15], [F, 1.06, 0.04], [E, 1.55, 0.22... | 0 | 2016-06-29T02:29:00Z | 38,089,423 | <pre><code>for index in range(len(sorted_Region)-1):
if sorted_Region[index+1][i] >= sorted_Region[index][1] and sorted_Region[index+1][2]<sorted_Region[index][2]:
Region_frontier.append(i)
print Region_frontier
</code></pre>
| -1 | 2016-06-29T02:36:24Z | [
"python",
"list",
"condition"
] |
Making new list of list with some condition of other list | 38,089,353 | <p>I am new to python and still struggle with it.
So can you guys help me with this?</p>
<p>I have this list of lists:</p>
<pre><code>sorted_Region: [[J, 0.80, 0.30], [H, 0.80, 0.21], [I, 0.87, 0.19], [G, 0.88, 0.15], [D, 0.96, 0.14], [B, 0.97, 0.14], [A, 1.01, 0.11], [C, 1.05, 0.15], [F, 1.06, 0.04], [E, 1.55, 0.22... | 0 | 2016-06-29T02:29:00Z | 38,089,469 | <p>For <code>i+1[1]</code>, getting the indexed item of 'int' object is ill-grammar. For the intended purpose, no index in the for loop for <code>sorted_Region</code>, so it is not possible to get the "<code>previous tuple</code>". </p>
<p>To iterate the <code>sorted_Region</code> and compare to the nearby item, try u... | 0 | 2016-06-29T02:41:11Z | [
"python",
"list",
"condition"
] |
Making new list of list with some condition of other list | 38,089,353 | <p>I am new to python and still struggle with it.
So can you guys help me with this?</p>
<p>I have this list of lists:</p>
<pre><code>sorted_Region: [[J, 0.80, 0.30], [H, 0.80, 0.21], [I, 0.87, 0.19], [G, 0.88, 0.15], [D, 0.96, 0.14], [B, 0.97, 0.14], [A, 1.01, 0.11], [C, 1.05, 0.15], [F, 1.06, 0.04], [E, 1.55, 0.22... | 0 | 2016-06-29T02:29:00Z | 38,089,474 | <p>You're trying to use index operator on integer which causes the error: <code>i+1[1]</code>. Instead of using indexing you could iterate over the pairs on the list with <a href="https://docs.python.org/3/library/functions.html#zip" rel="nofollow"><code>zip</code></a> and <a href="https://docs.python.org/3.5/library/i... | 1 | 2016-06-29T02:42:12Z | [
"python",
"list",
"condition"
] |
Making new list of list with some condition of other list | 38,089,353 | <p>I am new to python and still struggle with it.
So can you guys help me with this?</p>
<p>I have this list of lists:</p>
<pre><code>sorted_Region: [[J, 0.80, 0.30], [H, 0.80, 0.21], [I, 0.87, 0.19], [G, 0.88, 0.15], [D, 0.96, 0.14], [B, 0.97, 0.14], [A, 1.01, 0.11], [C, 1.05, 0.15], [F, 1.06, 0.04], [E, 1.55, 0.22... | 0 | 2016-06-29T02:29:00Z | 38,089,565 | <p>First of all I assume that by <strong>previous</strong> you mean the <strong>current</strong> element which you are iterating.
Also, I want to mention that you have a list of lists, not a set of tuple.
Since python has keywords like that so you should take care while using those words.
Now talking about your proble... | 1 | 2016-06-29T02:51:54Z | [
"python",
"list",
"condition"
] |
Finding the Kth Largest element in a Python List using recursion | 38,089,413 | <p>Given an input list that contains some random unsorted numbers, I am trying to write a program that outputs the kth largest distinct element in that list. For example:</p>
<pre><code>Input:
el = [10,10, 20,30,40, 40]
k = 2
Output: 30 #Since 30 is the second largest distinct element in the list
</code></pre>
<p>Th... | 1 | 2016-06-29T02:35:37Z | 38,089,839 | <p>Is there any reason you want to use recursion? To find the kth largest element of a list you have to look through the entire list, so the problem is essentially O(n) complexity anyway.</p>
<p>You could do this without recursion like this:</p>
<pre><code>el = [10, 10, 53, 20, 30, 40, 59, 40]
k = 2
def kth_largest(... | 0 | 2016-06-29T03:22:52Z | [
"python",
"recursion"
] |
Finding the Kth Largest element in a Python List using recursion | 38,089,413 | <p>Given an input list that contains some random unsorted numbers, I am trying to write a program that outputs the kth largest distinct element in that list. For example:</p>
<pre><code>Input:
el = [10,10, 20,30,40, 40]
k = 2
Output: 30 #Since 30 is the second largest distinct element in the list
</code></pre>
<p>Th... | 1 | 2016-06-29T02:35:37Z | 38,089,877 | <p>There's an easy way to do this problem using recursion. I'm just not sure why you need the pivot in the problem description... For example:</p>
<pre><code>def find_kth(k, arr):
if k == 1:
return max(arr)
m = max(arr)
new_arr = list(filter(lambda a: a != m, arr))
return(find_kth(k-1, new_arr... | 1 | 2016-06-29T03:27:42Z | [
"python",
"recursion"
] |
how to retrieve key with certain value that has value as a tuple(python) | 38,089,448 | <pre><code>{'Stephen Curry': [(22.6, 5.1, 3.4)], 'Draymond Green': [(16.5, 10.3, 6.3)], 'Lebron James': [(29.7, 11.3, 8.9)]})
</code></pre>
<p>Each value corresponds to a catergory in this case the format is (pts,reb,assists) I'm trying to retrieve the max value of pts,reb, and assists between each player and write t... | 1 | 2016-06-29T02:38:57Z | 38,089,699 | <p>I would just find the key corresponding to the max value like this:</p>
<pre><code>In [13]: max_pts_player = max(stats, key=lambda x:stats[x][0][0])
In [14]: max_pts_player
Out[14]: 'Lebron James'
In [15]: max_reb_player = max(stats, key=lambda x:stats[x][0][1])
In [16]: max_reb_player
Out[16]: 'Lebron James'
I... | 0 | 2016-06-29T03:07:21Z | [
"python",
"dictionary"
] |
how to retrieve key with certain value that has value as a tuple(python) | 38,089,448 | <pre><code>{'Stephen Curry': [(22.6, 5.1, 3.4)], 'Draymond Green': [(16.5, 10.3, 6.3)], 'Lebron James': [(29.7, 11.3, 8.9)]})
</code></pre>
<p>Each value corresponds to a catergory in this case the format is (pts,reb,assists) I'm trying to retrieve the max value of pts,reb, and assists between each player and write t... | 1 | 2016-06-29T02:38:57Z | 38,091,425 | <p>Okay so to the best of my understanding, this is what I came up with:</p>
<pre><code>d = {'Stephen Curry': [(23.6, 5.1, 3.4)], 'Draymond Green': [(16.5, 10.3, 6.3)], 'Lebron James': [(29.7, 11.3, 8.9)]}
lst_tuples = sorted(d.items())
max_pts = max(lst_tuples, key = lambda x: x[1][0][0])
max_rebs = max(lst_tuples,... | 0 | 2016-06-29T05:57:25Z | [
"python",
"dictionary"
] |
how to retrieve key with certain value that has value as a tuple(python) | 38,089,448 | <pre><code>{'Stephen Curry': [(22.6, 5.1, 3.4)], 'Draymond Green': [(16.5, 10.3, 6.3)], 'Lebron James': [(29.7, 11.3, 8.9)]})
</code></pre>
<p>Each value corresponds to a catergory in this case the format is (pts,reb,assists) I'm trying to retrieve the max value of pts,reb, and assists between each player and write t... | 1 | 2016-06-29T02:38:57Z | 38,092,363 | <pre><code>data = {'Stephen Curry': [(22.6, 5.1, 3.4)],
'Draymond Green': [(16.5, 10.3, 6.3)],
'Lebron James': [(29.7, 11.3, 8.9)]}
max_pts_player = list(reversed(sorted(data, key=lambda x: data[x][0][0])))[0]
max_reb_player = list(reversed(sorted(data, key=lambda x: data[x][0][1])))[0]
max_assits_player = list(rev... | 0 | 2016-06-29T06:54:28Z | [
"python",
"dictionary"
] |
I am having trouble with making a variable from an input on an Entry Box | 38,089,475 | <p>Basically, I'm trying to create Mad Lobs. My trouble is when I'm making a variable from the input in my function my syntax says that I have not defined MN1 (my first variable) which means the same for my others.</p>
<pre><code>from tkinter import *
root = Tk()
root.title("Mad Libs")
root.geometry("500x600")
x = ... | 0 | 2016-06-29T02:42:13Z | 38,090,938 | <p>Declare your variables like MN1 outside of your function <strong>mlib</strong> and also based on your code you are not taking any input entries from your eBox Entry widget but you are taking it from a unknown variable <strong><em>v</em></strong></p>
| 1 | 2016-06-29T05:20:27Z | [
"python",
"tkinter"
] |
How to select labels when both index and columns are named the same in a dataframe? | 38,089,513 | <p>I have a pandas dataframe and I need to find out the labels of the columns of nonzero elements of a particular row.</p>
<p>So for example:</p>
<pre><code>columns = ['a', 'b', 'c']
df = pd.DataFrame([[1, 0, 1], [0, 1, 0], [3, 5, 2]], index=columns, columns=columns)
</code></pre>
<p>For column <code>a</code>, I wou... | 0 | 2016-06-29T02:46:37Z | 38,089,681 | <p>Does this look like something you want?</p>
<pre><code>df.index[(df != 0)['a']]
# Index([u'a', u'c'], dtype='object')
df.index[(df != 0)['b']]
# Index([u'b', u'c'], dtype='object')
df.index[(df != 0)['c']]
# Index([u'a', u'c'], dtype='object')
</code></pre>
<p>To loop through the columns and build up a dictionar... | 0 | 2016-06-29T03:05:33Z | [
"python",
"pandas",
"dataframe"
] |
Unable to understand lecture 41 from Learn Python the hard way | 38,089,534 | <p>Unable to understand the code from PHRASES part. This is the code from learn Python the hard way. I am so lost after that part.Can someone please explain?</p>
<p>The book does not have any explanation about the code below.</p>
<pre><code>import random
from urllib import urlopen
import sys
WORD_URL = "http://learn... | 1 | 2016-06-29T02:48:47Z | 38,089,637 | <p>PHRASES is a dictionary containing problem descriptions (such as "Make a class named X that is a Y") and solutions (such as "class X(Y)").</p>
<p>The code picks one of the problem/solution pairs randomly from the dictionary, gets a list of words from <code>http://learncodethehardway.org/words.txt</code> and randoml... | 0 | 2016-06-29T02:59:48Z | [
"python"
] |
Change AngularJS opening and closing tags | 38,089,544 | <p>I'm trying to change angular opening and closing tags, (for python django jinja, if that matter)
So for example, instead of this</p>
<pre><code><div ng-app="">
<span>name - type: <input type="text" ng-model="name" /></span>
<span>name - output: {{name}}</span>
</div>... | 0 | 2016-06-29T02:49:35Z | 38,089,712 | <p>So it has to be something like this:</p>
<pre><code>angular.module('YourAppName', [], function ($interpolateProvider) {
$interpolateProvider.startSymbol('[[');
$interpolateProvider.endSymbol(']]');
});
</code></pre>
| 2 | 2016-06-29T03:09:09Z | [
"javascript",
"python",
"html",
"angularjs",
"django"
] |
Odoo change selected selection on python file | 38,089,546 | <p>I have a model which has a selection field like you can show below</p>
<pre><code>task_type = fields.Selection([
('product', 'Product'),
('document', 'Document'),
('issue', 'Issue'),
('child','Child'),
('other','Other')],
'Task Type', copy=False... | 0 | 2016-06-29T02:50:03Z | 38,105,613 | <p>If you want to update that record use write method like, </p>
<pre><code> Partner.write([partner.id], {'name': "MyCompany"})
</code></pre>
<p>Here Partner is an object of res.partner model.</p>
| 0 | 2016-06-29T16:45:39Z | [
"python",
"openerp",
"odoo-8",
"odoo-9"
] |
In python, how do I get list of objects contained in multiple lists | 38,089,574 | <p>Using python 2.6 I have essentially a list of lists. Some objects are the same within one or more of the lists. </p>
<p>I need to get a list of objects that are contained in ALL of the lists. </p>
<p>For example:</p>
<pre><code>list1 = ['apple','pear','cheese','grape']
list2 = ['grape','carrot','pear','cheese']
... | -1 | 2016-06-29T02:53:05Z | 38,089,599 | <p>You can use the <code>set</code> operator like this:</p>
<pre><code>set(list1) & set(list2) & set(list3)
</code></pre>
<p>If you want a <code>list</code> as output you can do:</p>
<pre><code>list(set(list1) & set(list2) & set(list3))
</code></pre>
| 1 | 2016-06-29T02:56:25Z | [
"python",
"list"
] |
In python, how do I get list of objects contained in multiple lists | 38,089,574 | <p>Using python 2.6 I have essentially a list of lists. Some objects are the same within one or more of the lists. </p>
<p>I need to get a list of objects that are contained in ALL of the lists. </p>
<p>For example:</p>
<pre><code>list1 = ['apple','pear','cheese','grape']
list2 = ['grape','carrot','pear','cheese']
... | -1 | 2016-06-29T02:53:05Z | 38,089,641 | <p>You can use <a href="https://docs.python.org/2/library/sets.html" rel="nofollow"><code>sets</code></a></p>
<pre><code>list1 = ['apple','pear','cheese','grape']
list2 = ['grape','carrot','pear','cheese']
list3 = ['apple','cheese','grape']
print(list(set(list1) & set(list2) & set(list3)))
</code></pre>
<p>... | 1 | 2016-06-29T03:00:16Z | [
"python",
"list"
] |
In python, how do I get list of objects contained in multiple lists | 38,089,574 | <p>Using python 2.6 I have essentially a list of lists. Some objects are the same within one or more of the lists. </p>
<p>I need to get a list of objects that are contained in ALL of the lists. </p>
<p>For example:</p>
<pre><code>list1 = ['apple','pear','cheese','grape']
list2 = ['grape','carrot','pear','cheese']
... | -1 | 2016-06-29T02:53:05Z | 38,089,693 | <pre><code>from collections import Counter
a = Counter(list1+list2+list3)
print([x for x in a if a[x]==3])
</code></pre>
| 2 | 2016-06-29T03:06:51Z | [
"python",
"list"
] |
In python, how do I get list of objects contained in multiple lists | 38,089,574 | <p>Using python 2.6 I have essentially a list of lists. Some objects are the same within one or more of the lists. </p>
<p>I need to get a list of objects that are contained in ALL of the lists. </p>
<p>For example:</p>
<pre><code>list1 = ['apple','pear','cheese','grape']
list2 = ['grape','carrot','pear','cheese']
... | -1 | 2016-06-29T02:53:05Z | 38,089,722 | <p>How about this one?</p>
<pre><code>a = [1,2,3,4,8]
b = [4,5,6,7,8]
c = [4,8,9]
print(list(set(a).intersection(b).intersection(c)))
</code></pre>
<p>I am using intersection() as it will add more readability in the code and other who is going to use this code will know what you are trying to do. </p>
| 0 | 2016-06-29T03:10:58Z | [
"python",
"list"
] |
In python, how do I get list of objects contained in multiple lists | 38,089,574 | <p>Using python 2.6 I have essentially a list of lists. Some objects are the same within one or more of the lists. </p>
<p>I need to get a list of objects that are contained in ALL of the lists. </p>
<p>For example:</p>
<pre><code>list1 = ['apple','pear','cheese','grape']
list2 = ['grape','carrot','pear','cheese']
... | -1 | 2016-06-29T02:53:05Z | 38,089,788 | <p>Use sets and set intersections:</p>
<pre><code>>>> list1 = ['apple','pear','cheese','grape']
>>> list2 = ['grape','carrot','pear','cheese']
>>> list3 = ['apple','cheese','grape']
>>> list_of_lists = [list1,list2,list3]
>>> reduce(set.intersection,map(set,list_of_lists))... | 1 | 2016-06-29T03:17:49Z | [
"python",
"list"
] |
In python, how do I get list of objects contained in multiple lists | 38,089,574 | <p>Using python 2.6 I have essentially a list of lists. Some objects are the same within one or more of the lists. </p>
<p>I need to get a list of objects that are contained in ALL of the lists. </p>
<p>For example:</p>
<pre><code>list1 = ['apple','pear','cheese','grape']
list2 = ['grape','carrot','pear','cheese']
... | -1 | 2016-06-29T02:53:05Z | 38,089,873 | <p>Do use the <code>set</code> class, it has useful methods like <code>intersection</code> that can be used to manipulate like iterables like Euler sets.
Here is the proof of concept and the answer to your question:</p>
<pre><code>list1 = ['apple', 'pear', 'cheese', 'grape']
list2 = ['grape', 'carrot', 'pear', 'chees... | 1 | 2016-06-29T03:27:14Z | [
"python",
"list"
] |
Python equivalent to R 's factor data type | 38,089,635 | <p>I'm new in using Python as scientific language. </p>
<p>I'm missing using an data type that informs me the data it self and the factors the data are in. (Specially for categorical data array. )</p>
<p>I'm wondering if there's a <strong>lib</strong> or <strong>an array</strong> type in <code>scipy package</code> fo... | 0 | 2016-06-29T02:59:22Z | 38,090,762 | <p>Try pandas</p>
<p><a href="http://pandas.pydata.org/" rel="nofollow">http://pandas.pydata.org/</a></p>
<p>and take a look at:</p>
<p><a href="http://pandas.pydata.org/pandas-docs/stable/categorical.html" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/categorical.html</a></p>
<p>It's an amazing librar... | 1 | 2016-06-29T05:02:15Z | [
"python",
"python-2.7",
"scipy",
"scikit-learn"
] |
OpenCV 2.4 - Playing Video from file on OSX | 38,089,717 | <p>I install Open CV and all the deps with <code>brew</code></p>
<p>Following this tutorial:</p>
<p><a href="http://docs.opencv.org/3.1.0/dd/d43/tutorial_py_video_display.html#gsc.tab=0" rel="nofollow">http://docs.opencv.org/3.1.0/dd/d43/tutorial_py_video_display.html#gsc.tab=0</a></p>
<p>I'm able to have it working... | 2 | 2016-06-29T03:10:16Z | 38,090,196 | <p>May be try reinstalling opencv with python and ffmpeg support</p>
<p><code>brew install opencv --with-ffmpeg -v</code></p>
<p>But before that install perian</p>
<p><a href="http://www.perian.org/" rel="nofollow">http://www.perian.org/</a></p>
| 1 | 2016-06-29T04:07:31Z | [
"python",
"c++",
"osx",
"opencv",
"computer-vision"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.