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 |
|---|---|---|---|---|---|---|---|---|---|
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,645 | <p>Currently working through some tutorials on Python, so if it doesn't work, do excuse my n00b level...</p>
<pre><code>answer=0
attempts = 0
while answer!=4:
answer=input("What is 2 + 2?")
if answer!=4:
print("Wrong...Try again.")
attempts = attempts + 1
else:
print("Yes! 2 + 2 = 4... | 0 | 2016-06-03T11:49:13Z | [
"python",
"loops",
"while-loop"
] |
How give a new view access to a BigQuery dataset via API (patch) | 37,613,403 | <p>I have a dataset in BigQuery with some views permissioned to it.</p>
<p>Via the API, I want to permission a new view for that dataset. Using the <a href="https://cloud.google.com/bigquery/docs/reference/v2/datasets#resource-representations" rel="nofollow">patch</a> method:</p>
<pre><code>...
#permission the view
d... | 1 | 2016-06-03T11:38:21Z | 37,614,261 | <p>The update method replaces the entire dataset resource, whereas the patch method only replaces fields that are provided in the submitted dataset resource. </p>
<p>The key above is - the patch method only replaces fields that are provided<br>
This means that access property will be REPLACED - the whole access prope... | 2 | 2016-06-03T12:20:11Z | [
"python",
"google-bigquery"
] |
can't acquire python output | 37,613,547 | <p>My python code gives a print in java in a while true loop but doesn't print if i put in a sleep, even after the duration of the sleep there is no output in java</p>
<pre><code>print 33
import time
while True:
i = 0
time.sleep(0.01)
j = 0
print 1
</code></pre>
<p>this is the python code. I run thi... | 0 | 2016-06-03T11:45:26Z | 37,616,049 | <p>This is a common problem. Python (and C, for the matter) streams are <a href="https://docs.python.org/2/library/io.html#io.DEFAULT_BUFFER_SIZE" rel="nofollow">buffered</a>.</p>
<p>In your case, this means that a <code>print</code> does not necessary cause immediate output, but rather fills the output buffer of the ... | 0 | 2016-06-03T13:43:46Z | [
"java",
"python",
"sleep"
] |
pympler raises TypeError | 37,613,792 | <p>In python2.7, following the pympler <a href="https://pythonhosted.org/Pympler/muppy.html">example</a>:</p>
<pre><code>from anotherfile import somefunction, somecustomclass
from os import path, listdir
import pandas as pd
import gc
from pympler import tracker, muppy, summary
all_objects = muppy.get_objects()
print ... | 6 | 2016-06-03T11:57:30Z | 37,613,909 | <p>Probably the code is supposed to work with Python3, only. In <a href="http://stackoverflow.com/questions/10482953/python-extending-with-using-super-python-3-vs-python-2">this question</a>, there's the same error for python2 and if you look at the accepted response it says:</p>
<blockquote>
<p>super() (without arg... | 0 | 2016-06-03T12:03:42Z | [
"python",
"python-2.7",
"memory-management",
"memory-leaks"
] |
pympler raises TypeError | 37,613,792 | <p>In python2.7, following the pympler <a href="https://pythonhosted.org/Pympler/muppy.html">example</a>:</p>
<pre><code>from anotherfile import somefunction, somecustomclass
from os import path, listdir
import pandas as pd
import gc
from pympler import tracker, muppy, summary
all_objects = muppy.get_objects()
print ... | 6 | 2016-06-03T11:57:30Z | 37,681,457 | <p>it seems to be a problem in pandas library. I solved it by editing the library code. The track of the error indicates you which line is wrong:</p>
<pre><code>File "/usr/local/lib/python2.7/dist-packages/pandas/core/base.py", line 130, in __sizeof__
return super(self, PandasObject).__sizeof__()
</code></pre>
<p>Yo... | 0 | 2016-06-07T13:56:35Z | [
"python",
"python-2.7",
"memory-management",
"memory-leaks"
] |
pympler raises TypeError | 37,613,792 | <p>In python2.7, following the pympler <a href="https://pythonhosted.org/Pympler/muppy.html">example</a>:</p>
<pre><code>from anotherfile import somefunction, somecustomclass
from os import path, listdir
import pandas as pd
import gc
from pympler import tracker, muppy, summary
all_objects = muppy.get_objects()
print ... | 6 | 2016-06-03T11:57:30Z | 38,313,067 | <p>This is <a href="https://github.com/pydata/pandas/pull/12924" rel="nofollow">Pandas issue #12924</a>. <code>PandasObject.__sizeof__</code> had the arguments in the wrong order for the <code>super</code> call. The fix has been pulled, and it should be available in the next release. In the meantime, you could edit <co... | 0 | 2016-07-11T17:44:04Z | [
"python",
"python-2.7",
"memory-management",
"memory-leaks"
] |
Is it possible to call the create function of another method from a the write method of a model in odoo | 37,613,845 | <p>I have two models, i need to create record in demo2 model from demo model. Is it possible to access the create method of demo2 from write method of demo model?</p>
<pre><code>class demo(models.Model):
_name= 'demo'
@api.multi
def write(self,vals):
self.env['demo2'].create({})
... | 0 | 2016-06-03T12:00:29Z | 37,615,500 | <p>yes it's possible, there is no as such constrain , just remember one thing : </p>
<blockquote>
<p><strong>write</strong> always return <strong>True/False</strong> and <strong>create</strong> <strong>object</strong> in 8/9 and <strong>id</strong> in
odoo7</p>
</blockquote>
| 1 | 2016-06-03T13:18:53Z | [
"python",
"odoo-8"
] |
/usr/bin/ld: cannot find -lpython3.5m | 37,613,860 | <p>I want to install tifffile package from terminal:</p>
<pre><code>pip install tifffile
</code></pre>
<p>I am getting the following error </p>
<pre><code> gcc -pthread -shared -L/home/l-01-314/anaconda3/lib -Wl,-rpath=/home/l-01-314/anaconda3/lib,--no-as-needed build/temp.linux-x86_64-3.5/tifffile/_tifffile.o -L/... | 1 | 2016-06-03T12:01:06Z | 37,615,685 | <p>solved, there was a wrong link from system gcc so I installed gcc for python anaconda via conda. </p>
<pre><code>conda install -c anaconda gcc=4.8.5
</code></pre>
| 0 | 2016-06-03T13:27:42Z | [
"python",
"linux",
"ubuntu",
"pip",
"tiff"
] |
py.test passing results of one test to another | 37,613,883 | <p>Currently I have test looking like this:</p>
<pre><code>@pytest.mark.parametrize("param", [1,2,3])
def test_two_services(param):
id = check_service_one(param)
check_service_two(id)
</code></pre>
<p>Is there any way to split this test in two, where a second test depends on a first?</p>
| 0 | 2016-06-03T12:02:11Z | 37,623,268 | <p>Remember to test at the boundary. So if the the values of <code>id</code> depend solely on <code>param</code> and if <code>id</code> isn't some implementation detail, but a part of the defined behaviour of the system under test, split up your tests like so:</p>
<pre><code>def test_service_one(param, id):
assert... | 1 | 2016-06-03T20:55:46Z | [
"python",
"python-2.7",
"unit-testing",
"automated-tests",
"py.test"
] |
Use python 3 regex to match a string in double quotes | 37,613,908 | <p>I want to match a string contained in a pair of either single or double quotes. I wrote a regex pattern as so:</p>
<pre><code>pattern = r"([\"\'])[^\1]*\1"
mytext = '"bbb"ccc"ddd'
re.match(pattern, mytext).group()
</code></pre>
<p>The expected output would be:</p>
<pre><code>"bbb"
</code></pre>
<p>However, this ... | 0 | 2016-06-03T12:03:39Z | 37,614,110 | <p>You should use a negative lookahead assertion. And I assume there won't be any escaped quotes in your input string.</p>
<pre><code>>>> pattern = r"([\"'])(?:(?!\1).)*\1"
>>> mytext = '"bbb"ccc"ddd'
>>> re.search(pattern, mytext).group()
'"bbb"'
</code></pre>
| 0 | 2016-06-03T12:12:38Z | [
"python",
"regex"
] |
Use python 3 regex to match a string in double quotes | 37,613,908 | <p>I want to match a string contained in a pair of either single or double quotes. I wrote a regex pattern as so:</p>
<pre><code>pattern = r"([\"\'])[^\1]*\1"
mytext = '"bbb"ccc"ddd'
re.match(pattern, mytext).group()
</code></pre>
<p>The expected output would be:</p>
<pre><code>"bbb"
</code></pre>
<p>However, this ... | 0 | 2016-06-03T12:03:39Z | 37,614,143 | <p>I guess you can use:</p>
<pre><code>pattern = r"[\"'][^\"']*[\"']"
</code></pre>
<p><a href="https://regex101.com/r/dO0cA8/1" rel="nofollow">https://regex101.com/r/dO0cA8/1</a></p>
<hr>
<p><code>[^\"']*</code> will match everything that isn't <code>"</code> or <code>'</code></p>
| 0 | 2016-06-03T12:14:19Z | [
"python",
"regex"
] |
Use python 3 regex to match a string in double quotes | 37,613,908 | <p>I want to match a string contained in a pair of either single or double quotes. I wrote a regex pattern as so:</p>
<pre><code>pattern = r"([\"\'])[^\1]*\1"
mytext = '"bbb"ccc"ddd'
re.match(pattern, mytext).group()
</code></pre>
<p>The expected output would be:</p>
<pre><code>"bbb"
</code></pre>
<p>However, this ... | 0 | 2016-06-03T12:03:39Z | 37,614,194 | <p>In your regex</p>
<pre><code>([\"'])[^\1]*\1
</code></pre>
<p><strong><em>Character class</em></strong> is meant for matching only one character. So your use of <code>[^\1]</code> is incorrect. Think, what would have have happened if there were more than one characters in the first capturing group.</p>
<p>You can... | 2 | 2016-06-03T12:17:17Z | [
"python",
"regex"
] |
Linked list search to stop loops before they happen | 37,613,928 | <p>I have a series of frames, and each frame can either be <code>None</code> or point to another frame. I don't want anything looping back to itself, so I'd like a quick way to check which frames are available for a certain frame to point to.</p>
<p>For example, if frame 1 points to 2, and frame 2 points to 3, then I'... | 0 | 2016-06-03T12:04:26Z | 37,617,640 | <p>Given that each frame can only point to one other frame, a simple way to go about this would be, for every frame, to build the sequence of frames that follow. Then, we can check to see if a given frame is in that sequence. If so, then having that given frame point to the initial frame of the sequence would create a ... | 2 | 2016-06-03T14:58:47Z | [
"python"
] |
Linked list search to stop loops before they happen | 37,613,928 | <p>I have a series of frames, and each frame can either be <code>None</code> or point to another frame. I don't want anything looping back to itself, so I'd like a quick way to check which frames are available for a certain frame to point to.</p>
<p>For example, if frame 1 points to 2, and frame 2 points to 3, then I'... | 0 | 2016-06-03T12:04:26Z | 37,618,204 | <p>As the other answerer said, you're dealing with a directed acyclic graph. For each node, you want to find the set of all the parents of that node (all of the nodes from which that node is reachable), which is equivalent to finding the set of all of the children of that node (all of the nodes reachable from it) in th... | 1 | 2016-06-03T15:27:06Z | [
"python"
] |
Did I reinvent the wheel with this deduplicating function? | 37,614,091 | <p>I was looking for a <code>set()</code>-like method to deduplicate a list, except that the items figuring in the original list are not hashable (they are <code>dict</code>s).</p>
<p>I spent a while looking for something adequate, and I ended up writing this little function:</p>
<pre><code>def deduplicate_list(lst, ... | 8 | 2016-06-03T12:11:57Z | 37,614,467 | <p>This <a href="http://stackoverflow.com/a/8714242/5741205">answer</a> will help to solve a more generic problem - find unique elements not by a single attribute (<code>id</code> in your case), but if <strong>any</strong> nested attribute differs </p>
<p>The following code will return a list of indices of the unique ... | 0 | 2016-06-03T12:31:10Z | [
"python",
"python-3.x",
"duplicates"
] |
Did I reinvent the wheel with this deduplicating function? | 37,614,091 | <p>I was looking for a <code>set()</code>-like method to deduplicate a list, except that the items figuring in the original list are not hashable (they are <code>dict</code>s).</p>
<p>I spent a while looking for something adequate, and I ended up writing this little function:</p>
<pre><code>def deduplicate_list(lst, ... | 8 | 2016-06-03T12:11:57Z | 37,614,580 | <p>You could try a short version which is based on the link to the answer, which you provided in the question:</p>
<pre><code>key = "id"
deduplicated = [val for ind, val in enumerate(l)
if val[key] not in [tmp[key] for tmp in l[ind + 1:]]]
print(deduplicated)
</code></pre>
<p>Note, this will take the ... | 0 | 2016-06-03T12:36:33Z | [
"python",
"python-3.x",
"duplicates"
] |
Did I reinvent the wheel with this deduplicating function? | 37,614,091 | <p>I was looking for a <code>set()</code>-like method to deduplicate a list, except that the items figuring in the original list are not hashable (they are <code>dict</code>s).</p>
<p>I spent a while looking for something adequate, and I ended up writing this little function:</p>
<pre><code>def deduplicate_list(lst, ... | 8 | 2016-06-03T12:11:57Z | 37,614,796 | <p>You are picking only the first <code>dict</code> in your list for every distinct value for <code>key</code>. <a href="https://docs.python.org/2/library/itertools.html#itertools.groupby" rel="nofollow"><code>itertools.groupby</code></a> is the built-in tool that can do that for you - sort and group by <code>key</code... | 3 | 2016-06-03T12:47:01Z | [
"python",
"python-3.x",
"duplicates"
] |
Did I reinvent the wheel with this deduplicating function? | 37,614,091 | <p>I was looking for a <code>set()</code>-like method to deduplicate a list, except that the items figuring in the original list are not hashable (they are <code>dict</code>s).</p>
<p>I spent a while looking for something adequate, and I ended up writing this little function:</p>
<pre><code>def deduplicate_list(lst, ... | 8 | 2016-06-03T12:11:57Z | 37,911,489 | <p>In your example, the value returned by the key is hashable. If this is always the case, then use this:</p>
<pre><code>def deduplicate(lst, key):
return list({item[key]: item for item in lst}.values())
</code></pre>
<p>If there are duplicates, only the last matching duplicate is retained.</p>
| 0 | 2016-06-19T20:23:55Z | [
"python",
"python-3.x",
"duplicates"
] |
Add list of values to a blob field in firebird using Python | 37,614,218 | <p>I have a list of items which I like to store in my firebird database.
Thus far I made the following code</p>
<pre><code> Sens=278.3
DSens=1.2
Fc10=3.8
Bw10=60.0
Fc20=4.2
Bw20=90.0
ResultArray = (Sens,DSens,Fc10,Bw10,Fc20,Bw20,t6,t20,Nel,Nsub)
con = fdb.connect(dsn="192.168.0.2:/datab... | 0 | 2016-06-03T12:18:16Z | 37,629,791 | <p>I've tested this with Python 3.5.1 and FDB 1.6. The following variants of writing all work (into a <code>blob sub_type text</code>):</p>
<pre><code>import fdb
import io
con = fdb.connect(dsn='localhost:testdatabase', user='sysdba', password='masterkey')
cur = con.cursor()
statement = "insert into blob_test2 (text... | 1 | 2016-06-04T11:41:54Z | [
"python",
"blob",
"firebird"
] |
in Pandas how to get a UTC TimeStamp (at a given hour) from a DateTime? | 37,614,303 | <p>I have a variable in my dataframe that looks like</p>
<pre><code>Day
2015-01-01
2015-02-01
</code></pre>
<p>I would like to generate a time variable that gives me the <strong>UTC timestamp</strong> of the corresponding <strong>EST timestamp</strong> of the day in <strong>Day</strong> at 9:00 am in the morning (alw... | 1 | 2016-06-03T12:22:28Z | 37,614,778 | <pre><code>df.Day = pd.date_range('1/1/2015 09:00', periods=10, freq='D')
df.Day = df.Day.tz_localize('UTC')
df.Day_converted = df.Day.tz_convert('US/Eastern')
</code></pre>
<p>After creating the timeseries you can localize it to a zone with .tz_localize and then convert it.</p>
| 3 | 2016-06-03T12:46:16Z | [
"python",
"datetime",
"pandas",
"timestamp"
] |
in Pandas how to get a UTC TimeStamp (at a given hour) from a DateTime? | 37,614,303 | <p>I have a variable in my dataframe that looks like</p>
<pre><code>Day
2015-01-01
2015-02-01
</code></pre>
<p>I would like to generate a time variable that gives me the <strong>UTC timestamp</strong> of the corresponding <strong>EST timestamp</strong> of the day in <strong>Day</strong> at 9:00 am in the morning (alw... | 1 | 2016-06-03T12:22:28Z | 37,662,253 | <p>thats probably the better solution</p>
<pre><code>df['time']=df['Day'].apply(lambda x: x + ' 9:00')
df['time_utc']=df['time'].apply(lambda x: `pd.Timestamp(x).tz_localize('US/Eastern').tz_convert('UTC'))`
</code></pre>
| 1 | 2016-06-06T16:16:51Z | [
"python",
"datetime",
"pandas",
"timestamp"
] |
Numpy: Error in broadcasting without using np.reshape? | 37,614,332 | <p>I just found out that despite having an array that python shows as (5000,1) and (5000,3072), which should be technically possible to perform broadcasting to give a (5000,3072), it sometimes just doesn't work if we don't reshape them explicitly to these shapes?</p>
<p>I have a set of data which I simply extract them... | 0 | 2016-06-03T12:23:50Z | 37,614,454 | <p>The arrays being broadcasted have shapes <code>(5000, 3072)</code> and <code>(5000,)</code>.
The first array is 2-dimensional, but the second is 1-dimensional. NumPy broadcasting always adds new axes (dimensions) <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html#general-broadcasting-rules" rel=... | 2 | 2016-06-03T12:30:28Z | [
"python",
"numpy"
] |
Python loop with default value otherwise infinite | 37,614,420 | <p>I want to create a loop which runs n-times where:</p>
<ol>
<li>'n' can be changed freely</li>
<li>'n' should have a default value when no value is passed</li>
<li>'n' should run forever when wanted</li>
</ol>
<p>My current code looks like this:</p>
<pre><code>n = raw_input('number of runs: ') # Get user inp... | 0 | 2016-06-03T12:28:36Z | 37,614,466 | <p>Use a <code>for</code>-loop, and different iterables:</p>
<pre><code>from itertools import count
n = raw_input('number of runs: ')
if n == '': #empty input-> run the loop 1000 times
counter = xrange(1, 1001)
elif n == 'oo': #run the loop forever
counter = count(1)
else:
counter = xrange(1, int(n... | 2 | 2016-06-03T12:31:09Z | [
"python",
"python-2.7"
] |
Python loop with default value otherwise infinite | 37,614,420 | <p>I want to create a loop which runs n-times where:</p>
<ol>
<li>'n' can be changed freely</li>
<li>'n' should have a default value when no value is passed</li>
<li>'n' should run forever when wanted</li>
</ol>
<p>My current code looks like this:</p>
<pre><code>n = raw_input('number of runs: ') # Get user inp... | 0 | 2016-06-03T12:28:36Z | 37,614,927 | <pre><code>a = raw_input('Enter value for a: ')
try:
a = int(a)
except:
if a != 'oo':
a = 10000
if a == 'oo':
while True:
print "infinite"
pass
else:
while a != 0:
# do something
print a
a = a - 1
</code></pre>
| 0 | 2016-06-03T12:52:47Z | [
"python",
"python-2.7"
] |
Comparing pandas DataFrame to Series | 37,614,489 | <p>I've looked at <a href="http://stackoverflow.com/questions/26285661/working-with-comparing-dataframes-and-series-and-generating-new-dataframes-on-th">this</a> and <a href="http://stackoverflow.com/questions/34220521/how-to-extract-pandas-series-element-and-compare-it-with-rows-in-dataframes-col">this</a> question so... | 1 | 2016-06-03T12:32:12Z | 37,614,549 | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.gt.html" rel="nofollow"><code>.gt</code></a> and pass <code>axis=0</code> to compare row-wise against a Series:</p>
<pre><code>In [126]:
df.gt(s, axis=0)
Out[126]:
Stock1 Stock2
index
Date1 True True
Date2 ... | 1 | 2016-06-03T12:35:02Z | [
"python",
"pandas"
] |
Spark reduce by some keys in reduceByKey | 37,614,511 | <p>After loading a large file into an <code>RDD0</code>, I create (very time consuming) <code>RDD1</code> of pairs</p>
<pre><code>((k1,k2), value)
</code></pre>
<p>and apply <code>reduceByKey</code>. For <code>RRD0</code> I need to create a <code>RDD2</code> of pairs </p>
<pre><code>((k1,k3), value)
</code></pre>
<... | 0 | 2016-06-03T12:33:15Z | 37,615,229 | <p>Your first operation should be a <a href="https://spark.apache.org/docs/1.2.0/api/python/pyspark.html#pyspark.RDD.flatMap" rel="nofollow">flatMap</a> and return</p>
<pre><code>[((k1,k2), value1), ((k1,k3)), value2)]
</code></pre>
<p>And then run the reduceByKey afterwards and you'll have your results</p>
| 0 | 2016-06-03T13:06:39Z | [
"python",
"scala",
"apache-spark",
"mapreduce"
] |
Why a "stack smashing detected" once ZeroMQ C++ client runs against a python Server? | 37,614,550 | <p>I'm trying to learn how to use <strong><code>ZeroMQ</code></strong> lib to exchange data ( a simple 'hello' ) between a client and a server.</p>
<hr>
<h2>python <kbd><code>client</code></kbd> - python <kbd><code>server</code></kbd> implementation works</h2>
<p>With success I have created a client and a server in ... | 1 | 2016-06-03T12:35:04Z | 37,618,762 | <h2><code>Step 0:</code> isolate the sweet-spot</h2>
<p>As proposed in comments above, kindly update, <strong>run</strong> & <strong>post</strong> output from a trivial self-diagnosing code modification:</p>
<pre><code> int main ()
{
zmq::context_t context (1);
// std::cout << "[1] .... + errn... | 1 | 2016-06-03T15:55:24Z | [
"python",
"c++",
"cmake",
"stack",
"zeromq"
] |
Extracting String within strings using Regex Python | 37,614,622 | <p>Say i have this string</p>
<p>"Input:Can we book an hotel in Lagos ? Parse: book VB ROOT +-- Can MD aux +-- we PRP nsubj +-- hotel NN dobj | +-- an DT det | +-- in IN prep | +-- Lagos NNP pobj +-- ? . punct "</p>
<p>and i want to get a list like this </p>
<pre><code>['book VB ROOT', 'Can MD aux',... | 1 | 2016-06-03T12:38:51Z | 37,614,695 | <p>I would use <code>re.split</code>..</p>
<pre><code>>>> s = 'Can we book an hotel in Lagos ? Parse: book VB ROOT +-- Can MD aux +-- we PRP nsubj +-- hotel NN dobj | +-- an DT det | +-- in IN prep | +-- Lagos NNP pobj +-- ? . punct'
>>> re.split(r'\s*\|?\s*\+\s*--\s*', s.split('Pars... | 0 | 2016-06-03T12:42:28Z | [
"python",
"regex"
] |
Extracting String within strings using Regex Python | 37,614,622 | <p>Say i have this string</p>
<p>"Input:Can we book an hotel in Lagos ? Parse: book VB ROOT +-- Can MD aux +-- we PRP nsubj +-- hotel NN dobj | +-- an DT det | +-- in IN prep | +-- Lagos NNP pobj +-- ? . punct "</p>
<p>and i want to get a list like this </p>
<pre><code>['book VB ROOT', 'Can MD aux',... | 1 | 2016-06-03T12:38:51Z | 37,614,808 | <p>Without regex by playing with built-in functions and methods:</p>
<pre><code>>>> filter(bool, map(str.strip, s.replace('+--', '|').split('Parse:')[1].split('|')))
['book VB ROOT', 'Can MD aux', 'we PRP nsubj', 'hotel NN dobj', 'an DT det', 'in IN prep', 'Lagos NNP pobj', '? . punct']
</code></pre>
| 1 | 2016-06-03T12:47:37Z | [
"python",
"regex"
] |
Extracting String within strings using Regex Python | 37,614,622 | <p>Say i have this string</p>
<p>"Input:Can we book an hotel in Lagos ? Parse: book VB ROOT +-- Can MD aux +-- we PRP nsubj +-- hotel NN dobj | +-- an DT det | +-- in IN prep | +-- Lagos NNP pobj +-- ? . punct "</p>
<p>and i want to get a list like this </p>
<pre><code>['book VB ROOT', 'Can MD aux',... | 1 | 2016-06-03T12:38:51Z | 37,620,985 | <p>Here's a version that does use a regex, but doesn't require looping over all the parts twice:</p>
<pre><code>def extract(line):
_, _, parts = line.strip().partition(' Parse: ')
return re.split('(?: \|)? \+-- ', parts)
line = "Input:Can we book an hotel in Lagos ? Parse: book VB ROOT +-- Can MD aux +-- we PR... | 0 | 2016-06-03T18:12:02Z | [
"python",
"regex"
] |
Python pivot table | 37,614,664 | <p>I am working through the book "Python for Data Analysis", but it seems half of the code runs into small errors. I have switched from Anaconda to Enthought for installation purposes. Currently only into page 31 I can't get this error fixed, yet the dataframe data is visible.</p>
<pre><code>mean_ratings =data.pivot_t... | -1 | 2016-06-03T12:40:48Z | 37,614,711 | <p>Try this:</p>
<pre><code>mean_ratings = data.pivot_table(values='rating', index='title',
columns='gender', aggfunc='mean')
</code></pre>
<p>As @unutbu has mentioned in the comment, very old versions of <a href="https://en.wikipedia.org/wiki/Pandas_%28software%29" rel="nofollow">Pand... | 1 | 2016-06-03T12:43:00Z | [
"python",
"pandas",
"ipython"
] |
Simplifying nested-lists as a Cartesian product | 37,614,676 | <p>I have a nested list in Python as:</p>
<pre><code>lst = ['alpha', ['beta', 'gamma'], ['delta', 'peta', 'lambda']]
</code></pre>
<p>I need a function that will return a list having the Cartesian product of them. Well, I think Cartesian product is not a right word, but still in a logical way the result will look lik... | 2 | 2016-06-03T12:41:22Z | 37,614,770 | <p>Use<a href="https://docs.python.org/3/library/itertools.html#itertools.product" rel="nofollow"><code>itertools.product</code></a>, which will require you to slightly modify your input (<code>'alpha'</code> to <code>['alpha']</code>):</p>
<pre><code>from itertools import product
lst = [['alpha'],['beta','gamma'],['... | 1 | 2016-06-03T12:45:48Z | [
"python",
"recursion",
"nested-lists"
] |
Simplifying nested-lists as a Cartesian product | 37,614,676 | <p>I have a nested list in Python as:</p>
<pre><code>lst = ['alpha', ['beta', 'gamma'], ['delta', 'peta', 'lambda']]
</code></pre>
<p>I need a function that will return a list having the Cartesian product of them. Well, I think Cartesian product is not a right word, but still in a logical way the result will look lik... | 2 | 2016-06-03T12:41:22Z | 37,614,777 | <p>You can use <a href="https://docs.python.org/2/library/itertools.html#itertools.product" rel="nofollow"><code>itertools.product</code></a> once you've converted all the items to lists:</p>
<pre><code>>>> from itertools import product
>>> lst = ['alpha',['beta','gamma'],['delta','peta','lambda']]
&... | 1 | 2016-06-03T12:46:12Z | [
"python",
"recursion",
"nested-lists"
] |
Simplifying nested-lists as a Cartesian product | 37,614,676 | <p>I have a nested list in Python as:</p>
<pre><code>lst = ['alpha', ['beta', 'gamma'], ['delta', 'peta', 'lambda']]
</code></pre>
<p>I need a function that will return a list having the Cartesian product of them. Well, I think Cartesian product is not a right word, but still in a logical way the result will look lik... | 2 | 2016-06-03T12:41:22Z | 37,616,031 | <p>It is great to use libraries in Python! However, if you are looking for a pure Python implementation:</p>
<pre><code>def CartesianProduct(list_entry):
# Save Sizes of Everything
size_dictionary = {}
# Get Size of Entire Entry List
size_dictionary["full_size"] = len(list_entry)
# Get Sizes of All Sub Entries
for i... | 1 | 2016-06-03T13:42:56Z | [
"python",
"recursion",
"nested-lists"
] |
Python logging exceptions with traceback, but without displaying messages twice | 37,614,710 | <p>If I run the following code:</p>
<pre><code>import logging
logger = logging.getLogger('creator')
try:
# some stuff
except Exception as exception:
logger.exception(exception)
</code></pre>
<p>I get the following output on the screen:</p>
<pre><code>creator : ERROR division by zero
Traceback (most re... | 0 | 2016-06-03T12:42:57Z | 37,615,094 | <p>If you called <code>exception</code> like this:</p>
<pre><code>logger.exception('%s: %s', exception.__class__.__name__, exception)
</code></pre>
<p>then you could get the exception class name in the initial line.</p>
<p>If you need more precise changes, you can use a custom <code>Formatter</code> subclass which f... | 0 | 2016-06-03T12:59:56Z | [
"python",
"exception",
"logging",
"exception-handling",
"output"
] |
Python:Storing path in variable; Argument Error | 37,614,716 | <pre><code>path = input("Enter the path")
book = xlrd.open_workbook(path)
</code></pre>
<p>After giving path and running program, I am getting the following error:</p>
<p>OSError: [Errno 22] Invalid argument: '"D:\\\shreyatest1.xlsx"'</p>
<p>Path is: "D:\\shreyatest1.xlsx"</p>
| 1 | 2016-06-03T12:43:09Z | 37,614,784 | <p>The <code>\\</code> character is how python represents an escaped <code>\</code> in a string literal. When inputting a string from the console, there's no need (read: it's wrong) to use this notation. Just input the path as you see it - <code>D:\shreyatest1.xlsx</code>.</p>
| 1 | 2016-06-03T12:46:23Z | [
"python",
"path",
"invalid-argument"
] |
flake8 not reporting on lines that are too long | 37,614,726 | <p>If I create a file <code>test.py</code> with the following poorly-formatted contents:</p>
<pre><code>import re
long_string = "foooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo"
class Foo():
pass
</code></pre>
<p>and run <code>flake8</code> on the file from the command-line like ... | 0 | 2016-06-03T12:43:31Z | 37,630,433 | <p><code>E501</code> is being ignored somewhere. It's either in <code>~/.config/flake8</code> or in the local directory in <code>tox.ini</code>, <code>setup.cfg</code>, or <code>.flake8</code>. Somewhere in one of those files you will probably find something akin to:</p>
<pre><code>[flake8]
ignore = E501
</code></pre>... | 3 | 2016-06-04T12:50:48Z | [
"python",
"pyflakes",
"flake8"
] |
How to limit the queryset of related fields of serializer based on some request parameters in Django Rest Framework | 37,614,840 | <p>I have three models <code>Transaction</code>, <code>Business</code>, and <code>Location</code>. They are defined as follows:</p>
<pre><code>class Business(models.Model):
# Can have zero or more locations. A user can have many businesses.
name = models.CharField(max_length=200, validators=[MinLengthValidat... | 0 | 2016-06-03T12:48:39Z | 37,617,091 | <p>You can <strong>override the <code>get_fields()</code> method of the serializer and modify the <code>queryset</code> for <code>business</code> and <code>location</code> fields</strong> to the desired values.</p>
<p><code>get_fields()</code> method is used by the serializer to generate the <code>field names -> fi... | 0 | 2016-06-03T14:32:27Z | [
"python",
"django",
"django-rest-framework"
] |
Python3 regex issue | 37,615,003 | <p>I'm writing a solution to a problem in which I need to parse the command line arguments. Before parsing, I first did the validation.</p>
<p>Permissible arguments are:</p>
<pre><code>someKey=(apps IN (app1))
someKey=(apps IN (app1,app2))
someKey=(apps IN (app1,app2, app3))
</code></pre>
<p>But if comma is at the e... | 0 | 2016-06-03T12:56:18Z | 37,615,090 | <p>You can use <code>\(apps\sIN\s\((app\d+)(,\s*app\d+)*\)\)</code></p>
<p>This will ensure that at least one occurrence of <code>app\d+</code> exists, and every subsequent occurrence has to be preceded by a comma (and optional whitespace).</p>
<p><a href="https://regex101.com/r/yG9aF3/3" rel="nofollow">Demo</a></p>
... | 0 | 2016-06-03T12:59:50Z | [
"python",
"regex"
] |
Python - mapping over a sparse matrix | 37,615,119 | <p>I am working with a csr_matrix (from scipy.sparse) and I need to apply a logarithm-like function on all its items. </p>
<blockquote>
<p>f:x->log(x+1), so f(0)=0).</p>
</blockquote>
<p>What would be the efficient way of doing that ?</p>
<p>I could not found any map function for csr_matrix, do I have forgotten on... | 2 | 2016-06-03T13:00:59Z | 37,615,172 | <p>What about (specifically for this function) <code>log1p</code>?</p>
<p>See the scipy documentation: <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csr_matrix.log1p.html" rel="nofollow">http://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csr_matrix.log1p.html</a></p>
| 4 | 2016-06-03T13:04:14Z | [
"python",
"scipy",
"sparse-matrix"
] |
How do I use instance attributes with pandas dataframe? | 37,615,128 | <p>I use pandas dataframes to access mass data from an oracle database, which is working fine. One function that I implemented in a class derived from dataframe replaces foreign keys with the data the foreign key points to. Works very nice.</p>
<p>Because the number of rows is quite high in the dataframe (i.e. 100.000... | 1 | 2016-06-03T13:01:13Z | 37,617,492 | <p>Track the new object in a variable. Update your object's <code>__dict__</code> attribute with the new objects <code>__dict__</code> attrubute.</p>
<p>The <code>__dict__</code> attribute is a dictionary of all attributes and methods. This is how I've done something similar in the past.</p>
<pre><code> def reso... | 0 | 2016-06-03T14:50:10Z | [
"python",
"pandas",
"dataframe",
"instance"
] |
Element-wise equality in 3-D array with arbitrarily sized axes | 37,615,196 | <p>I am looking for an efficient way to find element-wise equality in a 3D or N-D array, for example, equal value on RGB pixels of an image. Some test data:</p>
<pre><code>a = numpy.arange(100).reshape((10,10))
b = a.copy()
c = a.copy()
b[5,5] = 1
c[6,6] = 100
d = numpy.array([a,b,c])
</code></pre>
<p>I can think of ... | 1 | 2016-06-03T13:05:13Z | 37,615,429 | <p>Maybe this one:</p>
<pre><code>np.logical_and(*(d[0,:]==d[1:,:]))
</code></pre>
| 1 | 2016-06-03T13:16:00Z | [
"python",
"numpy",
"equality"
] |
Element-wise equality in 3-D array with arbitrarily sized axes | 37,615,196 | <p>I am looking for an efficient way to find element-wise equality in a 3D or N-D array, for example, equal value on RGB pixels of an image. Some test data:</p>
<pre><code>a = numpy.arange(100).reshape((10,10))
b = a.copy()
c = a.copy()
b[5,5] = 1
c[6,6] = 100
d = numpy.array([a,b,c])
</code></pre>
<p>I can think of ... | 1 | 2016-06-03T13:05:13Z | 37,616,427 | <p>Here's an approach for <code>nD</code> array cases that looks for all <code>0'</code>s diferentiations along the first axis -</p>
<pre><code>(np.diff(d,axis=0)==0).all(0)
</code></pre>
<p>Sample run to verify results -</p>
<pre><code>In [46]: d = np.random.randint(0,9,(3,3,5,2,3,4,2))
In [47]: out = (np.diff(d,a... | 1 | 2016-06-03T14:01:23Z | [
"python",
"numpy",
"equality"
] |
Element-wise equality in 3-D array with arbitrarily sized axes | 37,615,196 | <p>I am looking for an efficient way to find element-wise equality in a 3D or N-D array, for example, equal value on RGB pixels of an image. Some test data:</p>
<pre><code>a = numpy.arange(100).reshape((10,10))
b = a.copy()
c = a.copy()
b[5,5] = 1
c[6,6] = 100
d = numpy.array([a,b,c])
</code></pre>
<p>I can think of ... | 1 | 2016-06-03T13:05:13Z | 37,620,938 | <p>Divakar and Colonel Beauvel's solutions both hint that I can make my solution a bit faster by skipping the check <code>d[0] == d[0]</code>:</p>
<pre><code>numpy.logical_and.reduce(d[1:] == d[0])
</code></pre>
<p>In terms of efficiency and ability to to work on arbitrarily size axes, this still appears to be the be... | 1 | 2016-06-03T18:09:27Z | [
"python",
"numpy",
"equality"
] |
Evaluation of an Regression Model with r² | 37,615,222 | <p>Using a Bag of Words Model I count the occurences of words per Document (which are Posts from Boards) and create the vector for every Post. Example:</p>
<pre><code>X = [[0,0,0,1,0,3,0,0]
[0,0,1,0,0,0,1,0]
[1,0,1,0,2,0,0,0]]
y = [22,35,87]
</code></pre>
<p>In y are the labels/targets to every vector in X... | 0 | 2016-06-03T13:06:18Z | 37,616,112 | <p>The coefficient of determination R² describes the proportion of variance of the dependent variable explained by the regression model. MAE just gives the mean error over all test data. So they are two different ways to measure the performance of a model because each one has it own pitfalls. </p>
<p>R-squared does n... | 0 | 2016-06-03T13:47:12Z | [
"python",
"machine-learning",
"nlp",
"scikit-learn",
"regression"
] |
Python bool compare vs string compare | 37,615,264 | <p>This question is out of itch of being perfect. </p>
<p>I come across the case where I have to get parameter from post and check if it is <code>True</code> or <code>False</code> (in python), and accordingly call the LOC. </p>
<p>Obviously parameter read is of type <code><str></code> and <code>if param:</cod... | 0 | 2016-06-03T13:08:31Z | 37,615,546 | <p>I would certainly not go down the route of converting the string to a boolean, that's too much overhead for a simple logic statement.
You should first ensure the parameter is either of the values 'True' or 'False'.</p>
<p>Then:</p>
<pre><code>if (param == 'True'):
# True code here
else:
# False code here
<... | 2 | 2016-06-03T13:20:53Z | [
"python"
] |
Python bool compare vs string compare | 37,615,264 | <p>This question is out of itch of being perfect. </p>
<p>I come across the case where I have to get parameter from post and check if it is <code>True</code> or <code>False</code> (in python), and accordingly call the LOC. </p>
<p>Obviously parameter read is of type <code><str></code> and <code>if param:</cod... | 0 | 2016-06-03T13:08:31Z | 37,615,599 | <p>Memory Considerations: </p>
<pre><code>For String
sys.getsizeof("True")
>> 41
sys.getsizeof("False")
>> 42
For Boolean
sys.getsizeof(True)
>> 24
sys.getsizeof(False)
>> 24
</code></pre>
| 0 | 2016-06-03T13:23:03Z | [
"python"
] |
Python SQL update query: string or integer address expected instead of instance instance | 37,615,316 | <p>I use Python 2.7 and pypyodbc in order to run SQL queries but whenever I run the update query using python,</p>
<pre><code>cursor.execute("UPDATE tbl_User SET gender = ? WHERE id = 1", ['male'])
</code></pre>
<p>I get the error:</p>
<pre><code>TypeError: string or integer address expected instead of instance inst... | 3 | 2016-06-03T13:10:43Z | 37,615,540 | <p>How about that: </p>
<pre><code>gender = 'male'
cursor.execute("UPDATE tbl_User SET gender = {:s} WHERE id = 1".format(gender))
</code></pre>
<p>Also make sure that the python version of sqlite and the one used by the SQL Server are the same. For the python one type:</p>
<pre><code>import sqlite3
print(sqlite3... | 0 | 2016-06-03T13:20:40Z | [
"python",
"sql-server",
"sql-update",
"pyodbc",
"pypyodbc"
] |
Python SQL update query: string or integer address expected instead of instance instance | 37,615,316 | <p>I use Python 2.7 and pypyodbc in order to run SQL queries but whenever I run the update query using python,</p>
<pre><code>cursor.execute("UPDATE tbl_User SET gender = ? WHERE id = 1", ['male'])
</code></pre>
<p>I get the error:</p>
<pre><code>TypeError: string or integer address expected instead of instance inst... | 3 | 2016-06-03T13:10:43Z | 37,616,142 | <p>The problem was I didn't put a semicolon at the end of the query. The solution is:</p>
<pre><code>cursor.execute("UPDATE tbl_User SET gender = ? WHERE id = 1;", ['male'])
</code></pre>
| 3 | 2016-06-03T13:48:22Z | [
"python",
"sql-server",
"sql-update",
"pyodbc",
"pypyodbc"
] |
Python Webdriver Multithread | 37,615,350 | <p>I'm trying to spawn multiple webdriver instances with the code from: <a href="http://www.ibm.com/developerworks/aix/library/au-threadingpython/" rel="nofollow">http://www.ibm.com/developerworks/aix/library/au-threadingpython/</a></p>
<pre><code>import time
import Queue
import urllib2
import threading
from selenium ... | 0 | 2016-06-03T13:12:10Z | 37,615,493 | <p>You are not instantiating the Queue correctly. Instead of,</p>
<pre><code>queue = Queue.Queue
out_queue = Queue.Queue
</code></pre>
<p>it should be</p>
<pre><code>queue = Queue.Queue()
out_queue = Queue.Queue()
</code></pre>
| 1 | 2016-06-03T13:18:36Z | [
"python",
"selenium-webdriver",
"python-multithreading"
] |
Python Webdriver Multithread | 37,615,350 | <p>I'm trying to spawn multiple webdriver instances with the code from: <a href="http://www.ibm.com/developerworks/aix/library/au-threadingpython/" rel="nofollow">http://www.ibm.com/developerworks/aix/library/au-threadingpython/</a></p>
<pre><code>import time
import Queue
import urllib2
import threading
from selenium ... | 0 | 2016-06-03T13:12:10Z | 37,615,501 | <p>You need to use <code>Queue.Queue()</code> instead of <code>Queue.Queue</code></p>
| 1 | 2016-06-03T13:18:57Z | [
"python",
"selenium-webdriver",
"python-multithreading"
] |
Mocks not getting hit in Python unit tests | 37,615,354 | <p>I'm new to Python, but I've done quite a bit of unit testing in C# and JavaScript. I'm having trouble figuring out the mocking framework in Python. Here's what I have (trimmed down):</p>
<p><strong>invoice_business.py</strong></p>
<pre><code>import ims.repository.invoice_repository as invoiceRepository
import logg... | 0 | 2016-06-03T13:12:27Z | 37,615,943 | <p>The mock arguments to your test function are swapped. The inner decorator (for the logger) is applied first, so the mock logger should be the first argument to your method.</p>
<pre><code>@mock.patch("ims.business.invoice_business.invoiceRepository")
@mock.patch("ims.business.invoice_business.logger")
def test_invo... | 3 | 2016-06-03T13:39:10Z | [
"python",
"unit-testing",
"mocking"
] |
Fit data to different array size | 37,615,357 | <p>I have two sets of data created by two measuring instruments, each instrument gives a time column and voltage column, while the two sets of data represent the same amount of time (or very close), they are stored in different size arrays as the sampling times are different.
I want to get the scipy.stats.pearsonr coef... | 0 | 2016-06-03T13:12:35Z | 37,615,656 | <p>What you could do though, to get to array of the same length, is to take the shorter and to expand it by interpolation of the information.
You can interpolate the signal (bilinear or even trilinear to have better values) and resample it.</p>
<p><a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/num... | 0 | 2016-06-03T13:26:03Z | [
"python",
"numpy",
"signal-processing",
"data-manipulation"
] |
Fit data to different array size | 37,615,357 | <p>I have two sets of data created by two measuring instruments, each instrument gives a time column and voltage column, while the two sets of data represent the same amount of time (or very close), they are stored in different size arrays as the sampling times are different.
I want to get the scipy.stats.pearsonr coef... | 0 | 2016-06-03T13:12:35Z | 37,616,400 | <p>This is hard to answer without some minimum example of what you're doing exactly, but one approach that might work is to do it via <code>pandas</code>. If you have the timing of your measurements, you could create two DataFrames with datetime indexes:</p>
<pre><code>df1 = pd.DataFrame({"data":np.random.rand(6)}, in... | 0 | 2016-06-03T14:00:06Z | [
"python",
"numpy",
"signal-processing",
"data-manipulation"
] |
Pypyodbc pulling SQL Column as value | 37,615,416 | <p>I am using pypyodbc to pull data but I will simplify the data for this example. My issue is that I have a column named 475Election and when I pull data from this column I am getting 475 as a value in python. For example:</p>
<pre><code>TradeID ...Other Values... 475Election
1 ...Other Values... ... | 0 | 2016-06-03T13:15:29Z | 37,620,093 | <p>I figured it out, the column had to be renamed from [475Election] to TaxElection in order to stop pypyodbc from reading the value as an integer instead of a boolean</p>
| 0 | 2016-06-03T17:14:03Z | [
"python",
"sql",
"pypyodbc"
] |
How to convert Series into DataFrame preserving the columns? | 37,615,426 | <p>I have a large <code>DataFrame</code> with the following contents:</p>
<pre><code>obj0 type obj1 counts
car P wheel 2
tree P branch 5
box I ball 23
wheel P bus 3
grass A cow 10
...
</code></pre>
<p>I want to see how many <code>obj0</code> and <code>type</code> pair... | 0 | 2016-06-03T13:15:45Z | 37,615,496 | <p>try this:</p>
<pre><code>In [262]: df.groupby(['obj0', 'type'], as_index=False)['counts'].sum()
Out[262]:
obj0 type counts
0 box I 23
1 car P 2
2 grass A 10
3 tree P 5
4 wheel P 3
</code></pre>
<p>from <a href="http://pandas.pydata.org/pandas-docs/stable/ge... | 3 | 2016-06-03T13:18:41Z | [
"python",
"pandas",
"dataframe"
] |
How to convert Series into DataFrame preserving the columns? | 37,615,426 | <p>I have a large <code>DataFrame</code> with the following contents:</p>
<pre><code>obj0 type obj1 counts
car P wheel 2
tree P branch 5
box I ball 23
wheel P bus 3
grass A cow 10
...
</code></pre>
<p>I want to see how many <code>obj0</code> and <code>type</code> pair... | 0 | 2016-06-03T13:15:45Z | 37,615,502 | <p>I think you might be looking for </p>
<pre><code>pdf.groupby(['obj0', 'type'], as_index=False)['counts'].sum()
</code></pre>
| 1 | 2016-06-03T13:18:58Z | [
"python",
"pandas",
"dataframe"
] |
F1-score per class for multi-class classification | 37,615,544 | <p>I'm working on a multiclass classification problem using python and scikit-learn. Currently, I'm using the <code>classification_report</code> function to evaluate the performance of my classifier, obtaining reports like the following:</p>
<pre><code>>>> print(classification_report(y_true, y_pred, target_na... | 0 | 2016-06-03T13:20:42Z | 37,617,532 | <p>Taken from the <code>f1_score</code> <a href="http://scikit-learn.org/stable/modules/generated/sklearn.metrics.f1_score.html" rel="nofollow">docs</a>.</p>
<pre><code>from sklearn.metrics import f1_score
y_true = [0, 1, 2, 0, 1, 2]
y_pred = [0, 2, 1, 0, 0, 1]
f1_score(y_true, y_pred, average=None)
</code></pre>
<p... | 2 | 2016-06-03T14:51:46Z | [
"python",
"machine-learning",
"scikit-learn"
] |
Time data errors in input while trying to get the sum from txt.file (PYTHON) | 37,615,605 | <p>the program i am trying to make is supposed to get a user to input a start date and end date and the program is to iterate through the list which is in a txt file containing such info as </p>
<pre><code>1-2-2014,store1,42305.67,23
12-4-2014,store2,21922.22,17
10-2-2015,store3,63277.9,32
10-5-2015,store4,83290.09,16... | -1 | 2016-06-03T13:23:34Z | 37,616,018 | <p>Problem in date formats:</p>
<pre><code>%m Month as a zero-padded decimal number.
%d Day of the month as a zero-padded decimal number.
</code></pre>
<p>You are using this formats but they have to contain 2 digits. </p>
<p>Like 01,03,10 and so on. </p>
<p><a href="https://docs.python.org/2/library/datetime.html... | 0 | 2016-06-03T13:42:31Z | [
"python",
"csv",
"datetime",
"error-handling",
"text-files"
] |
Remove carriage return in python macro for libre or open office | 37,615,753 | <p>I try to write a macro for libre/Open office in python.</p>
<p>i use this for replace some string and it's work :</p>
<pre><code>document = XSCRIPTCONTEXT.getDocument()
search = document.createSearchDescriptor()
search.SearchString = "\:\Z"
search.SearchAll = True
search.SearchCaseSensitive = False
search.SearchRe... | 0 | 2016-06-03T13:30:39Z | 37,625,275 | <p>My (LO 4.1.6.2/Linux) Online Help tells me to use a <code>\n</code> to search for a <code>newline character</code> entered with <kbd>Ctrl</kbd>+<kbd>Enter</kbd>.</p>
<p>If a replace instruction is not given, I get what you want.
I'm pretty sure this will work for you with Python (I actually tested it with StarBasic... | 0 | 2016-06-04T00:46:20Z | [
"python",
"regex",
"macros",
"libreoffice",
"carriage-return"
] |
Unable to click on element on webpage via xpath and no errors thrown | 37,615,834 | <p>I am trying to test a website's form submit page. The submit button has the following HTML:</p>
<pre><code><input id="ctl00_PlaceHolderMain_SubmitButton" class="SubmitButton" type="submit" onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$PlaceHolderMain$SubmitButton", "", true... | 0 | 2016-06-03T13:34:06Z | 37,616,550 | <p>Try using the class name instead, it shall work :</p>
<pre><code>driver.find_element(By.CLASS_NAME, 'SubmitButton')
</code></pre>
<p>for which you shall introduce this inside <code>wait_until_element_clickable</code> to your code :</p>
<pre><code>if locatorMode == LocatorMode.CLASS_NAME
element = WebDriverWait(se... | 1 | 2016-06-03T14:06:53Z | [
"python",
"selenium"
] |
Unable to click on element on webpage via xpath and no errors thrown | 37,615,834 | <p>I am trying to test a website's form submit page. The submit button has the following HTML:</p>
<pre><code><input id="ctl00_PlaceHolderMain_SubmitButton" class="SubmitButton" type="submit" onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$PlaceHolderMain$SubmitButton", "", true... | 0 | 2016-06-03T13:34:06Z | 37,618,203 | <p>So the onclick() in the HTML was not firing because one of the radio buttons on the website was not chosen. I was able to click on the submit button after selecting the required radio button. </p>
<p>A regular click() method worked via CSS selector.</p>
| 0 | 2016-06-03T15:27:05Z | [
"python",
"selenium"
] |
How do you get data out of brackets and curly braces in Python? | 37,615,869 | <p>I'm trying to pull info out of google searches using the py-web-search module. The result of pulling a search is this(as stated in the <a href="https://github.com/rohithpr/py-web-search#usage" rel="nofollow">Github</a>):</p>
<pre><code>{
'url': '...',
'expected_num': 5,
'received_num' : 5, # There will ... | 2 | 2016-06-03T13:36:08Z | 37,616,079 | <p>What you are doing is correct, but that library is out-of-date and does not return any results for Google searches. See <a href="https://github.com/rohithpr/py-web-search/issues/20" rel="nofollow">this issue</a> for details:</p>
<blockquote>
<p>Also, Google has changed the HTML structure. So the scraper has to be... | 6 | 2016-06-03T13:45:10Z | [
"python"
] |
python using multiple conditions with numpy where | 37,615,932 | <p>I have a giant array called AllDays storing datetime.</p>
<p>I generated an array which stores day of week information for each day. </p>
<p>I am trying to extract the weekends only from the original datetime array AllDays.</p>
<p>So, from the day of week I am trying the following:</p>
<pre><code>DayOfWeek = np.... | 0 | 2016-06-03T13:38:44Z | 37,616,055 | <p>The problem here is the "or" which is not defined for numpy boolean arrays. You can just use a sum instead:</p>
<pre><code>np.where((DayOfWeek == 0) + (DayOfWeek == 6))
</code></pre>
<p>edit: You can also use the bitwise or operator:</p>
<pre><code>np.where((DayOfWeek == 0) | (DayOfWeek == 6))
</code></pre>
<p>w... | 3 | 2016-06-03T13:44:00Z | [
"python",
"datetime",
"numpy"
] |
Need a string with double quote immediately followed by single quote in python 2.6 | 37,616,101 | <p>I am trying to store a string in variable <code>A</code> which contains:</p>
<pre><code>"'D:\\Work\\B1.tif';'D:\\Work\\B2.tif'"
</code></pre>
<p>I have two variables that store the locations of <code>B1.tif</code> and <code>B2.tif</code>:</p>
<pre><code>X = "D:\\Work\\B1.tif"
Y = "D:\\Work\\B2.tif"
</code></pre>
... | 0 | 2016-06-03T13:46:18Z | 37,616,396 | <p>String formatting (and raw strings) is much easier:</p>
<pre><code>A = "\"'D:\\Work\\B1.tif';'D:\\Work\\B1.tif'\""
print A
X = r"D:\Work\B1.tif"
Y = r"D:\Work\B2.tif"
A = '"' + "'" + X + "'" + ";" + "'" + Y + "'" + '"'
print A
A = "\"'%s';'%s'\"" % (X, Y)
print A
</code></pre>
<p>Gives:</p>
<pre><code>"'D:\Wo... | 2 | 2016-06-03T13:59:38Z | [
"python",
"string",
"python-2.6"
] |
Need a string with double quote immediately followed by single quote in python 2.6 | 37,616,101 | <p>I am trying to store a string in variable <code>A</code> which contains:</p>
<pre><code>"'D:\\Work\\B1.tif';'D:\\Work\\B2.tif'"
</code></pre>
<p>I have two variables that store the locations of <code>B1.tif</code> and <code>B2.tif</code>:</p>
<pre><code>X = "D:\\Work\\B1.tif"
Y = "D:\\Work\\B2.tif"
</code></pre>
... | 0 | 2016-06-03T13:46:18Z | 37,616,404 | <p>print '"\'%s\';\'%s\'"' %(X,Y)</p>
| 2 | 2016-06-03T14:00:16Z | [
"python",
"string",
"python-2.6"
] |
Need a string with double quote immediately followed by single quote in python 2.6 | 37,616,101 | <p>I am trying to store a string in variable <code>A</code> which contains:</p>
<pre><code>"'D:\\Work\\B1.tif';'D:\\Work\\B2.tif'"
</code></pre>
<p>I have two variables that store the locations of <code>B1.tif</code> and <code>B2.tif</code>:</p>
<pre><code>X = "D:\\Work\\B1.tif"
Y = "D:\\Work\\B2.tif"
</code></pre>
... | 0 | 2016-06-03T13:46:18Z | 37,616,439 | <p>When you display a variable in Python by just typing it's name, Python tries to print it in a way that if you were to copy and paste it as a variable, it would produce the same object. This works for strings, lists, dictionaries, sets, etc. The consequence is that strings need to be escaped when printed out this way... | 1 | 2016-06-03T14:01:53Z | [
"python",
"string",
"python-2.6"
] |
Need a string with double quote immediately followed by single quote in python 2.6 | 37,616,101 | <p>I am trying to store a string in variable <code>A</code> which contains:</p>
<pre><code>"'D:\\Work\\B1.tif';'D:\\Work\\B2.tif'"
</code></pre>
<p>I have two variables that store the locations of <code>B1.tif</code> and <code>B2.tif</code>:</p>
<pre><code>X = "D:\\Work\\B1.tif"
Y = "D:\\Work\\B2.tif"
</code></pre>
... | 0 | 2016-06-03T13:46:18Z | 37,616,455 | <p>Try using <code>str.format()</code> for these complicated formatting situations, you can even use triple quoted strings to make it easier.</p>
<pre><code>A = ''' "'{}';'{}'" '''.format(X,Y)
</code></pre>
| 0 | 2016-06-03T14:02:29Z | [
"python",
"string",
"python-2.6"
] |
Searching in google using GET method | 37,616,151 | <p>I want to query google using GET method and retrieve the HTML result. I've tried the following:</p>
<pre><code>import httplib
import urllib
params = urllib.urlencode({'gws_rd': 'ssl', 'q': 'hello'}) # search for hello
headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
c = http... | 0 | 2016-06-03T13:49:01Z | 37,616,824 | <p>Hi what you trying to do is already Deprecated. You can check below link for the reference.</p>
<p><a href="https://developers.google.com/web-search/" rel="nofollow">https://developers.google.com/web-search/</a></p>
<p>In place of that google have given new API.</p>
<p><a href="https://developers.google.com/custo... | 0 | 2016-06-03T14:19:45Z | [
"python",
"python-2.7",
"google-search"
] |
No such message id pylint | 37,616,221 | <p>When I try to pylint a file by doing <code>pylint fname.py</code>, I get the following error:
<code>pylint.utils.UnknownMessage: No such message id E1608</code>. However, 'E1608' is certainly a valid message id; it says so on their <a href="https://docs.pylint.org/features.html" rel="nofollow">website</a>. What ar... | 0 | 2016-06-03T13:52:24Z | 37,616,557 | <p>It looks like you need</p>
<pre><code>disable=old-octal-literal
</code></pre>
<p>The <code>disable</code> flag takes a message, not a message ID, according to the docs. See <a href="https://docs.pylint.org/faq.html#what-is-the-format-of-the-configuration-file" rel="nofollow">here</a> for the relevant documentation... | 1 | 2016-06-03T14:07:06Z | [
"python",
"pylint"
] |
No such message id pylint | 37,616,221 | <p>When I try to pylint a file by doing <code>pylint fname.py</code>, I get the following error:
<code>pylint.utils.UnknownMessage: No such message id E1608</code>. However, 'E1608' is certainly a valid message id; it says so on their <a href="https://docs.pylint.org/features.html" rel="nofollow">website</a>. What ar... | 0 | 2016-06-03T13:52:24Z | 37,616,812 | <p>If you want to disable a message ID instead of a messages, you can do</p>
<p><code>disable-msg=E1608</code></p>
| 0 | 2016-06-03T14:19:14Z | [
"python",
"pylint"
] |
How to find out the state of a checkbox using AndroidViewClient | 37,616,289 | <p>I'm using androidviewclient for automated black-box level testing of an android GUI, I have two checkboxes (YES and NO) with YES checked by default, I use vc.touch() to select NO and I need to know whether NO has been selected.The way I do it now is by taking screenshot before and after a touch and compare them. Is... | 1 | 2016-06-03T13:55:19Z | 37,621,434 | <p>As an example, I'm using <strong>Clock</strong> and the <strong>Vibrate</strong> checkbox in Alarms</p>
<p><a href="http://i.stack.imgur.com/pBrTS.png" rel="nofollow"><img src="http://i.stack.imgur.com/pBrTS.png" alt="enter image description here"></a></p>
<p>Then, I generated the script using <a href="https://git... | 0 | 2016-06-03T18:44:24Z | [
"android",
"python",
"automated-tests",
"androidviewclient"
] |
Raspberry Pi - Open CV & C++ | 37,616,303 | <p>We're doing a project in school where we need to do basic image processing. What we want to do in our project is take a picture every 50ms (or faster) with our Raspberry Pi and do real time image processing.</p>
<p>We've tried to include raspistill in our python-program but so far nothing has worked. The goal of ou... | 0 | 2016-06-03T13:56:11Z | 37,617,075 | <p>I'm just going to gloss over how to do this without writing up a full program. The short answer is this is VERY possible and relatively simple.</p>
<p><strong>Step 1</strong>: Get an image from the camera<br>
For this I would recommend just using <code>VideoCapture</code> and processing each image that comes in. Th... | 0 | 2016-06-03T14:31:33Z | [
"python",
"opencv",
"raspberry-pi3"
] |
Pygame UnboundLocalError | 37,616,444 | <p>The following code from a game engine I'm tinkering in gives me this error: </p>
<pre><code>***"UnboundLocalError: local variable 'event' referenced before assignment":***
player.update(current_level.object_list, event) found in the main_loop() in line 342
main_loop() in line 364.
</code></pre>
<p>The only thing... | 0 | 2016-06-03T14:01:56Z | 37,617,166 | <p>As mentioned by molbdnilo, the indentation was wrong in the main loop. However, once you pass in the event, it's fine, but if there is no event, the player doesn't update.</p>
<p>The better way around this would be to make a global variable for events, then run the update function once per frame, and inside that ch... | 1 | 2016-06-03T14:35:36Z | [
"python",
"python-2.7",
"pygame"
] |
How to print out http-response header in Python | 37,616,460 | <p>Today I actually needed to retrieve data from the http-header response. But since I've never done it before and also there is not much you can find on Google about this. I decided to ask my question here.</p>
<p>So actual question: How does one print the http-header response data in python? I'm working in Python3.5... | 0 | 2016-06-03T14:02:56Z | 37,616,615 | <p><strong>Update</strong>: Based on comment of OP, that only the response headers are needed. Even more easy as written in below documentation of Requests module:</p>
<blockquote>
<p>We can view the server's response headers using a Python dictionary:</p>
</blockquote>
<pre><code>>>> r.headers
{
'cont... | 0 | 2016-06-03T14:09:46Z | [
"python",
"http",
"header",
"response"
] |
How to print out http-response header in Python | 37,616,460 | <p>Today I actually needed to retrieve data from the http-header response. But since I've never done it before and also there is not much you can find on Google about this. I decided to ask my question here.</p>
<p>So actual question: How does one print the http-header response data in python? I'm working in Python3.5... | 0 | 2016-06-03T14:02:56Z | 37,616,638 | <p>How about something like this:</p>
<pre><code>import urllib2
req = urllib2.Request('http://www.google.com/')
res = urllib2.urlopen(req)
print res.info()
res.close();
</code></pre>
<p>If you are looking for something specific in the header:</p>
<pre><code>For Date: print res.info().get('Date')
</code></pre>
| 0 | 2016-06-03T14:11:05Z | [
"python",
"http",
"header",
"response"
] |
Given a list of n points, how can I generate a matrix that contains the distance from every point to every other point using numpy? | 37,616,593 | <p>Hey guys so i'm trying to rewrite the following matlab code in python:</p>
<pre><code>repmat(points, 1, length(points)) - repmat(points', length(points),1);
</code></pre>
<p><code>points</code> is an array that contain the radian value of several points.</p>
<p>The above code gives me a matrix output like this:</... | 4 | 2016-06-03T14:08:47Z | 37,616,731 | <p>In MATLAB, you had to use <code>repmat</code> because you needed the arrays on the left and right side of the <code>-</code> to be the same size. With numpy, this does not have to be the case thanks to numpy's <a href="https://docs.scipy.org/doc/numpy-dev/user/quickstart.html#broadcasting-rules" rel="nofollow">autom... | 7 | 2016-06-03T14:14:59Z | [
"python",
"matlab",
"numpy",
"matrix"
] |
Given a list of n points, how can I generate a matrix that contains the distance from every point to every other point using numpy? | 37,616,593 | <p>Hey guys so i'm trying to rewrite the following matlab code in python:</p>
<pre><code>repmat(points, 1, length(points)) - repmat(points', length(points),1);
</code></pre>
<p><code>points</code> is an array that contain the radian value of several points.</p>
<p>The above code gives me a matrix output like this:</... | 4 | 2016-06-03T14:08:47Z | 37,616,883 | <p>You probably want to take a look at <a href="http://docs.scipy.org/doc/scipy-0.17.1/reference/generated/scipy.spatial.distance.pdist.html#scipy.spatial.distance.pdist" rel="nofollow"><code>scipy.spatial.pdist</code></a></p>
<p>But for constructing the original matrix you're looking for, if <code>points</code> is ju... | 4 | 2016-06-03T14:22:31Z | [
"python",
"matlab",
"numpy",
"matrix"
] |
Given a list of n points, how can I generate a matrix that contains the distance from every point to every other point using numpy? | 37,616,593 | <p>Hey guys so i'm trying to rewrite the following matlab code in python:</p>
<pre><code>repmat(points, 1, length(points)) - repmat(points', length(points),1);
</code></pre>
<p><code>points</code> is an array that contain the radian value of several points.</p>
<p>The above code gives me a matrix output like this:</... | 4 | 2016-06-03T14:08:47Z | 37,617,990 | <p>I'm not familiar with the matlab code. However, just trying to calculate euclidean distance from every column vector to every other column vector:</p>
<pre><code>np.sqrt((np.square(A[:, None].T - A.T)).sum(axis=2))
array([[ 0., 3., 6., 0., 3., 6., 0., 3., 6.],
[ 3., 0., 3., 3., 0., 3., 3., 0... | 0 | 2016-06-03T15:16:17Z | [
"python",
"matlab",
"numpy",
"matrix"
] |
Writing custom log handler in python | 37,616,599 | <p>I am trying to extend RotatingFile Handler to say FooBar.</p>
<pre>
class FooBar(RotatingFileHandler) :
def __init__(self, filename, mode='a', maxBytes=0,backupCount=0, encoding=None, delay=0) :
RotatingHandler.__init__(self, filename, mode, maxBytes, backupCount, encoding, delay)
</pre>
<p>I confi... | 0 | 2016-06-03T14:08:57Z | 37,616,788 | <p><code>RotatingHandler</code> is not in scope, so you would need something like this to bring it into scope:</p>
<pre><code>from logging.handlers import RotatingFileHandler
</code></pre>
<p>However, have a look at this example:</p>
<p><a href="http://stackoverflow.com/questions/20154490/how-to-log-everything-into-... | 1 | 2016-06-03T14:17:50Z | [
"python"
] |
Any way to add **kwargs to __str__()'s signature of an object? | 37,616,746 | <p>I would like to be able to change the output of <code>__str__()</code>, and would like to add <code>**kwargs</code> for that.</p>
<p>Problem: it doesn't seem possible to change the function's signature.</p>
<p>For instance:</p>
<pre><code>#!/usr/bin/env python3
class my_printable_obj(object):
def __init__(s... | 2 | 2016-06-03T14:15:37Z | 37,617,001 | <p>The function that you are calling with the kwarg is <a href="https://docs.python.org/3.5/library/functions.html#func-str" rel="nofollow"><code>str</code> (the inbuilt function)</a>.</p>
<p><code>str()</code> does call the <code>__str__</code> method on your object.</p>
<hr>
<p>Maybe what you are looking for is <c... | 4 | 2016-06-03T14:27:59Z | [
"python",
"string",
"python-3.x",
"signature",
"kwargs"
] |
Any way to add **kwargs to __str__()'s signature of an object? | 37,616,746 | <p>I would like to be able to change the output of <code>__str__()</code>, and would like to add <code>**kwargs</code> for that.</p>
<p>Problem: it doesn't seem possible to change the function's signature.</p>
<p>For instance:</p>
<pre><code>#!/usr/bin/env python3
class my_printable_obj(object):
def __init__(s... | 2 | 2016-06-03T14:15:37Z | 37,617,172 | <p>The built-in <code>str</code> is a <code>type</code>. When you execute something like <code>str(custom_object)</code>, the constructor of <code>str</code> call the object's <code>__str__()</code> method. You can't change the signature of the type without overwriting it (which isn't really a great idea).</p>
<pre><c... | 2 | 2016-06-03T14:35:51Z | [
"python",
"string",
"python-3.x",
"signature",
"kwargs"
] |
some Exceptional Error | 37,616,775 | <p>hey i have written this python code.</p>
<pre><code>str="abc def abc def abc def abc"
str=str.split(" ")
dict={0:'word'}
count=0
temp_list=[]
temp_list1=[]
for i in str:
dict[str.count(i)]=i
for key,values in dict.items():
print(key,values)
</code></pre>
<p>o/p:0 word
3 def
4 abc</p>
<p>that is okay but wh... | 0 | 2016-06-03T14:17:10Z | 37,616,867 | <p>Dictionaries can't have duplicate keys. <code>{2: "def", 2: "abc"}</code> is impossible output. If you're trying to make a histogram, you should be aiming for <code>{"def": 2, "abc": 2}</code>. It seems like you've got keys and values mixed up.</p>
<p>Try using <code>collections.Counter</code>.</p>
<pre><code>>... | 2 | 2016-06-03T14:21:30Z | [
"python",
"string",
"dictionary"
] |
Correct way to implement multi-folder menus | 37,616,797 | <p>I'm a bit stuck trying to implement a multi-level folder grouping. The top level folder lists a few line items, each of which plays a track. What I'm trying to accomplish is have one of these items be a folder which leads to another playlist (since this is a music add-on, they're all 'playlists').</p>
<p>Here's a s... | 0 | 2016-06-03T14:18:09Z | 38,438,656 | <p>Look at my example Kodi video plugin: <a href="https://github.com/romanvm/plugin.video.example" rel="nofollow">https://github.com/romanvm/plugin.video.example</a></p>
<pre><code># -*- coding: utf-8 -*-
# Module: default
# Author: Roman V. M.
# Created on: 28.11.2014
# License: GPL v.3 https://www.gnu.org/copyleft/g... | 1 | 2016-07-18T13:58:26Z | [
"python",
"xbmc",
"kodi"
] |
Define Ctypes array that overlaps in memory for numpy array and multiprocessing | 37,616,863 | <p>How to define a ctype array buffer that can hold several numpy array of floats (say A, B, C) at one time point and then hold several numpy arrays of integers (say D, E) at another time point? Can this be done with some combination of ctypes, numpy, or multiprocessing in python?</p>
<p>Thank you. I am trying to use ... | 0 | 2016-06-03T14:21:25Z | 37,618,063 | <p>First, is your program using too much memory? If the answer is "no" or "I'm not sure", then ignore this can carry on until you know you really do have a problem.</p>
<h1>Using the same buffer for different arrays</h1>
<p>You can do all of what you want using "views" that are available within numpy. Views are just ... | 1 | 2016-06-03T15:19:25Z | [
"python",
"numpy",
"multiprocessing",
"ctypes"
] |
Redirect AFTER response is ended | 37,616,880 | <p>Hope this is not already answer somewhere else but I cannot find it...</p>
<p>I've created a nodejs script to display in live the output of a python script, see demo :</p>
<pre><code>app.get('/', function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/html' });
PythonShell.run('script_web_e2L.p... | 0 | 2016-06-03T14:22:17Z | 37,617,146 | <p>You writing http response headers twice.</p>
<pre><code>res.writeHead(200, { 'Content-Type': 'text/html' });
res.writeHead(301,{Location: results[results.length - 1]});
</code></pre>
<p>You cannot do that. You must write headers once only, http spec.</p>
<p>To redirect the user after command completion you hav... | 1 | 2016-06-03T14:35:02Z | [
"python",
"node.js",
"express"
] |
Is it possible to append a whole list of XML nodes without a loop? | 37,616,912 | <p>If I want to append an XML node to another, I would do <code>nodeA.append(nodeB)</code>. And if I want to append a list of nodes to another node, I would do a for loop like:</p>
<pre><code>for node in nodes:
nodeA.append(node)
</code></pre>
<p>I was wondering if there is a way to do this in one step.</p>
<p>P... | 0 | 2016-06-03T14:23:40Z | 37,617,201 | <pre><code>nodeA.extend(nodes)
</code></pre>
<p>See <a href="https://docs.python.org/2/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element/%22here%22" rel="nofollow">here</a> for more documentation on the ElementTreeAPI </p>
| 2 | 2016-06-03T14:36:52Z | [
"python",
"xml",
"python-2.7",
"parsing",
"lxml"
] |
Is it possible to append a whole list of XML nodes without a loop? | 37,616,912 | <p>If I want to append an XML node to another, I would do <code>nodeA.append(nodeB)</code>. And if I want to append a list of nodes to another node, I would do a for loop like:</p>
<pre><code>for node in nodes:
nodeA.append(node)
</code></pre>
<p>I was wondering if there is a way to do this in one step.</p>
<p>P... | 0 | 2016-06-03T14:23:40Z | 37,617,216 | <p>as far as i know you can do it by just using nodeA = [nodes] that would only work if nodes is already in listform, like this: ["1","2","3"] for example but that is with python3.4 though, i think it might work</p>
| 0 | 2016-06-03T14:37:37Z | [
"python",
"xml",
"python-2.7",
"parsing",
"lxml"
] |
Python Changes Both Variables When Set Equal? | 37,616,939 | <p>I noticed a very strange behavior when working with python that binds 2 variables, that are set equal, to the same changes and I want to know if anyone has an explanation for this behavior and if there is a better solution than mine for it.</p>
<p>For example, I have an array called schema1. I later need to expand ... | -1 | 2016-06-03T14:24:52Z | 37,617,049 | <p>It's important to remember that in Python, variables are not little boxes that hold stuff, they're just handy names that are attached to stuff.</p>
<p>So when you do</p>
<pre><code>schema1 = SomeClass.SomeSchema
schema2 = schema1
</code></pre>
<p>You're just attaching two names to the same piece of data, which is... | 1 | 2016-06-03T14:30:21Z | [
"python",
"variables"
] |
Python Changes Both Variables When Set Equal? | 37,616,939 | <p>I noticed a very strange behavior when working with python that binds 2 variables, that are set equal, to the same changes and I want to know if anyone has an explanation for this behavior and if there is a better solution than mine for it.</p>
<p>For example, I have an array called schema1. I later need to expand ... | -1 | 2016-06-03T14:24:52Z | 37,617,059 | <p>On this line:</p>
<pre><code>schema2 = schema1
</code></pre>
<p>you are not creating a <strong>new</strong> array, but instead you are just setting the reference <code>schema2</code> to point at the <strong>same</strong> array that <code>schema1</code> is pointing at. </p>
<p>Writing</p>
<pre><code>schema2 = sch... | 0 | 2016-06-03T14:30:47Z | [
"python",
"variables"
] |
Python Changes Both Variables When Set Equal? | 37,616,939 | <p>I noticed a very strange behavior when working with python that binds 2 variables, that are set equal, to the same changes and I want to know if anyone has an explanation for this behavior and if there is a better solution than mine for it.</p>
<p>For example, I have an array called schema1. I later need to expand ... | -1 | 2016-06-03T14:24:52Z | 37,617,116 | <p>both answer above are right but instead of doing schema1[:]
you can do</p>
<pre><code>from copy import copy
schema2 = copy(scheme1)
</code></pre>
<p>which makes it more readable and can work with other object such as dict</p>
| 0 | 2016-06-03T14:33:29Z | [
"python",
"variables"
] |
Python Changes Both Variables When Set Equal? | 37,616,939 | <p>I noticed a very strange behavior when working with python that binds 2 variables, that are set equal, to the same changes and I want to know if anyone has an explanation for this behavior and if there is a better solution than mine for it.</p>
<p>For example, I have an array called schema1. I later need to expand ... | -1 | 2016-06-03T14:24:52Z | 37,617,577 | <p>When you assign an object to a variable, you are binding that name to that object. If you then set that variable to another variable, the second variable name is binding to the original object. </p>
<pre><code>schema1 = SomeClass.someSchema
schema2 = schema1
</code></pre>
<p>In this example, schema1 and schema2 ar... | 0 | 2016-06-03T14:54:57Z | [
"python",
"variables"
] |
Django ORM : how can i see last executed query on fly | 37,616,990 | <p>so lets say we have a simple query using django orm </p>
<pre><code>filterd = User.objects.exclude(id = request.user.id ).filter(username=data['username'] )
</code></pre>
<p>this is suppose to return some objects but it returns none !
obviously i'm doing something wrong as i' not comfortable with django ORM yet ,... | 1 | 2016-06-03T14:27:31Z | 37,617,266 | <p>Try:<br>
</p>
<pre><code>from django.db import connection as conn
filterd = User.objects.exclude(id = request.user.id).filter(username=data['username'] )
# to execute query
print filterd
print conn.queries
</code></pre>
| 1 | 2016-06-03T14:39:41Z | [
"python",
"django",
"orm"
] |
Importing ctypes.windll.shell32.IsUserAnAdmin gives ImportError | 37,617,033 | <p>Really stupid question here, sorry - it's my first day in Python.</p>
<p>I want to import the 'IsUserAnAdmin' function like so:</p>
<pre><code>from ctypes.windll.shell32 import IsUserAnAdmin
</code></pre>
<p>I'm obviously doing something wrong because I'm getting:</p>
<blockquote>
<p>ImportError: No module nam... | 0 | 2016-06-03T14:29:43Z | 37,617,589 | <p><code>windll</code> is a <code>LibraryLoader</code> object not a <code>module</code>. If you read the <a href="https://docs.python.org/2.7/library/ctypes.html" rel="nofollow">docs</a>, you will notice the import been done as:</p>
<pre><code>>>> from ctypes import *
>>> print windll.Shell32.IsUserA... | 2 | 2016-06-03T14:55:26Z | [
"python",
"python-3.x",
"import",
"ctypes",
"python-import"
] |
How to get word frequency using collections.Counter, even when the count is zero? | 37,617,135 | <p>I am trying to get the counts for frequencies of words occurring in multiple files in a directory and thanks to this answer <a href="http://stackoverflow.com/a/14921951/6419547">here</a> I was able to get results for when the word did occur. However, I can't figure out how to also get the results to display when the... | 2 | 2016-06-03T14:34:23Z | 37,617,268 | <p>It looks like it's returning NULL if the word doesn't appear. Put in a conditioned return statement, where if the value it's returning isn't an int > 0, return 0.</p>
| -1 | 2016-06-03T14:40:00Z | [
"python",
"counter"
] |
How to get word frequency using collections.Counter, even when the count is zero? | 37,617,135 | <p>I am trying to get the counts for frequencies of words occurring in multiple files in a directory and thanks to this answer <a href="http://stackoverflow.com/a/14921951/6419547">here</a> I was able to get results for when the word did occur. However, I can't figure out how to also get the results to display when the... | 2 | 2016-06-03T14:34:23Z | 37,617,725 | <p>You are never using the <code>ct</code> Counter you constructed in <code>word_frequency</code> but constructing a new Counter that only has the existing words, you need to use your constructed <code>ct</code>, e.g.:</p>
<pre><code>...
for word in file_words:
if word in words:
ct[word] += 1
return ct
</c... | 1 | 2016-06-03T15:03:04Z | [
"python",
"counter"
] |
Creating a lag variable in a Python Sframe by group | 37,617,233 | <p>Hi I am trying to identify the lag variable for a set of groups in a python Sframe.</p>
<p>The code I am using is:</p>
<pre><code>sf['lag'] = sf.groupby(['Group'])['Num'].shift(1)
</code></pre>
<p>However I am getting the error:</p>
<blockquote>
<p>TypeError: groupby() takes at least 3 arguments (2 given)</p>
... | 0 | 2016-06-03T14:38:20Z | 37,619,521 | <p>You need to indicate which aggregation functions you would like the<code>groupby</code> operator to do. For example</p>
<pre><code>import sframe
import sframe.aggregate as agg
grp = sf.groupby(key_columns='Group',
operations={'count': agg.COUNT('Group')})
</code></pre>
<p>Check out the documenta... | 0 | 2016-06-03T16:39:35Z | [
"python",
"lag",
"sframe"
] |
python3 add_command doesn't work | 37,617,255 | <p>I'm programming with Python,
but I wanted to make a text editor of mine with tkinter</p>
<p>so I watched a tutorial but it didn't work.
This is the code</p>
<pre><code>from tkinter import *
from tkinter import filedialog
filename = None
def newFile():
global filename
filename = "Untitled"
text.delet... | -1 | 2016-06-03T14:39:23Z | 37,617,346 | <p>You're creating <code>filemenu</code>:</p>
<pre><code>filemenu = Menu(menubar)
</code></pre>
<p>But then using <code>filename</code> which is set to <code>None</code> at the top of the code you've posted, which is why it's being reported as type <code>NoneType</code>:</p>
<pre><code>filename.add_command(label="Ne... | 1 | 2016-06-03T14:43:18Z | [
"python",
"tkinter"
] |
python3 add_command doesn't work | 37,617,255 | <p>I'm programming with Python,
but I wanted to make a text editor of mine with tkinter</p>
<p>so I watched a tutorial but it didn't work.
This is the code</p>
<pre><code>from tkinter import *
from tkinter import filedialog
filename = None
def newFile():
global filename
filename = "Untitled"
text.delet... | -1 | 2016-06-03T14:39:23Z | 37,618,176 | <p>Too many typos & mistakes. I managed to fix them somehow...</p>
<pre><code>1c1
< from tkinter import *
---
> from tkinter import *
2a3
> from tkinter.filedialog import asksaveasfile, askopenfile
5a7
>
10a13
>
17a21
>
24c28,29
< showerror(title="Oops!", message="Error had been fi... | -1 | 2016-06-03T15:25:06Z | [
"python",
"tkinter"
] |
How to delete a Parquet file on Spark? | 37,617,263 | <p>I have saved a parquet file on Spark using DataFrame.saveAsParquet() command.</p>
<p>How can I delete/remove this file via python code?</p>
| 0 | 2016-06-03T14:39:32Z | 37,617,472 | <p>This parquet "file" will actually be a directory. <a href="http://stackoverflow.com/questions/303200/how-do-i-remove-delete-a-folder-that-is-not-empty-with-python">This answer</a> shows how to delete a directory with files in it </p>
<pre><code>import shutil
shutil.rmtree('/folder_name')
</code></pre>
| 1 | 2016-06-03T14:48:40Z | [
"python",
"apache-spark",
"parquet"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.