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
Python readinto: How to convert from an array.array to a custom ctype structure
39,162,028
<p>I have created an array of integers and I would like them to be interpreted by the structure definition which I have created</p> <pre><code>from ctypes import * from array import array class MyStruct(Structure): _fields_ = [("init", c_uint), ("state", c_char), ("constant", c_int), ("address", c_uint), ("size", c_uint), ("sizeMax", c_uint), ("start", c_uint), ("end", c_uint), ("timestamp", c_uint), ("location", c_uint), ("nStrings", c_uint), ("nStringsMax", c_uint), ("maxWords", c_uint), ("sizeFree", c_uint), ("stringSizeMax", c_uint), ("stringSizeFree", c_uint), ("recordCount", c_uint), ("categories", c_uint), ("events", c_uint), ("wraps", c_uint), ("consumed", c_uint), ("resolution", c_uint), ("previousStamp", c_uint), ("maxTimeStamp", c_uint), ("threshold", c_uint), ("notification", c_uint), ("version", c_ubyte)] # arr = array.array('I', [1]) # How can I do this? # mystr = MyStruct(arr) magic # (mystr.helloworld == 1) == True </code></pre> <p>I can do the following:</p> <pre><code>mystr = MyStruct() rest = array.array('I') with open('myfile.bin', 'rb') as binaryFile: binaryFile.readinto(mystr) rest.fromstring(binaryFile.read()) # Now create another struct with rest rest.readinto(mystr) # Does not work </code></pre> <p>How can I avoid using a file to convert an array of Ints to a struct if the data is contained in an array.array('I')? I am not sure what the Structure constructor accepts or how the readinto works.</p>
0
2016-08-26T08:41:59Z
39,252,109
<h2>Solution #1: Star unpacking for one-line initialization</h2> <p>Star-unpacking will work, but only if all the fields in your structure are integer types. In Python 2.x, <code>c_char</code> cannot be initialized from an <code>int</code> (it works fine in 3.5). If you change the type of <code>state</code> to <code>c_byte</code>, then you can just do:</p> <pre><code>mystr = MyStruct(*myarr) </code></pre> <p>This doesn't actually benefit from any <code>array</code> specific magic (the values are briefly converted to Python <code>int</code>s in the unpacking step, so you're not reducing peak memory usage), so you'd only bother with an <code>array</code> if initializing said <code>array</code> was easier than directly reading into the structure for whatever reason.</p> <p>If you go the star unpacking route, reading <code>.state</code> will now get you <code>int</code> values instead of len 1 <code>str</code> values. If you want to initialize with <code>int</code>, but read as one character <code>str</code>, you can use a protected name wrapped in a <code>property</code>:</p> <pre><code>class MyStruct(Structure): _fields_ = [... ("_state", c_byte), # "Protected" name int-like; constructor expects int ...] @property def state(self): return chr(self._state) @state.setter def state(self, x): if isinstance(x, basestring): x = ord(x) self._state = x </code></pre> <p>A similar technique could be used without <code>property</code>s by defining your own <code>__init__</code> that converted the <code>state</code> argument passed:</p> <pre><code>class MyStruct(Structure): _fields_ = [("init", c_uint), ("state", c_char), ...] def __init__(self, init=0, state=b'\0', *args, **kwargs): if not isinstance(state, basestring): state = chr(state) super(MyStruct, self).__init__(init, state, *args, **kwargs) </code></pre> <h2>Solution #2: Direct <code>memcpy</code>-like solutions to reduce temporaries</h2> <p>You can use some <code>array</code> specific magic to avoid the temporary Python level <code>int</code>s though (and avoid the need to change <code>state</code> to <code>c_byte</code>) without real file objects using a fake (in-memory) file-like object:</p> <pre><code>import io mystr = MyStruct() # Default initialize # Use BytesIO to gain the ability to write the raw bytes to the struct # because BytesIO's readinto isn't finicky about exact buffer formats io.BytesIO(myarr.tostring()).readinto(mystr) # In Python 3, where array implements the buffer protocol, you can simplify to: io.BytesIO(myarr).readinto(mystr) # This still performs two memcpys (one occurs internally in BytesIO), but # it's faster by avoiding a Python level method call </code></pre> <p>This only works because your non-<code>c_int</code> width attributes are followed by <code>c_int</code> width attributes (so they're padded out to four bytes anyway); if you had two <code>c_ubyte</code>/<code>c_char</code>/etc. types back to back, then you'd have problems (because one value of the <code>array</code> would initialize two fields in the struct, which does not appear to be what you want).</p> <p>If you were using Python 3, you could benefit from <code>array</code> specific magic to avoid the cost of both unpacking and the two step <code>memcpy</code> of the <code>BytesIO</code> technique (from <code>array</code> -> <code>bytes</code> -> struct). It works in Py3 because Py3's <code>array</code> type supports the buffer protocol (it didn't in Py2), and because Py3's <code>memoryview</code> features a <code>cast</code> method that lets you change the format of the <code>memoryview</code> to make it directly compatible with <code>array</code>:</p> <pre><code>mystr = MyStruct() # Default initialize # Make a view on mystr's underlying memory that behaves like a C array of # unsigned ints in native format (matching array's type code) # then perform a "memcpy" like operation using empty slice assignment # to avoid creating any Python level values. memoryview(mystr).cast('B').cast('I')[:] = myarr </code></pre> <p>Like the <code>BytesIO</code> solution, this only works because your fields all happen to pad to four bytes in size</p> <h2>Performance</h2> <p>Performance-wise, star unpacking wins for small numbers of fields, but for large numbers of fields (your case has a couple dozen), direct <code>memcpy</code> based approaches win out; in tests for a 23 field class, the <code>BytesIO</code> solution won over star unpacking on my Python 2.7 install by a factor of 2.5x (star unpacking was 2.5 microseconds, <code>BytesIO</code> was 1 microsecond).</p> <p>The <code>memoryview</code> solution scales similarly to the <code>BytesIO</code> solution, though as of 3.5, it's slightly slower than the <code>BytesIO</code> approach (likely a result of the need to construct several temporary <code>memoryview</code>s to perform the necessary casting operations and/or the <code>memoryview</code> slice assignment code being general purpose for many possible formats, so it's not simple <code>memcpy</code> in implementation). <code>memoryview</code> might scale better for much larger copies (if the losses are due to the fixed <code>cast</code> overhead), but it's rare that you'd have a struct large enough to matter; it would only be in more general purpose copying scenarios (to and from <code>ctypes</code> arrays or the like) that <code>memoryview</code> would potentially win.</p>
1
2016-08-31T14:16:45Z
[ "python", "arrays", "ctypes", "python-2.x" ]
html5lib requires setuptools version 18.5 or above; please upgrade before installing (you have 0.6)
39,162,033
<p>When i try to give a pip install on my <code>requirements.txt</code> file, it fails as mentioned below: </p> <pre><code>html5lib requires setuptools version 18.5 or above; please upgrade before installing (you have 0.6) Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-5xXCfM/html5lib/ . </code></pre> <p>I did go through some of the previous post on this where some user mentioned it got resolved by specifying :</p> <pre><code>pip install html5lib --upgrade </code></pre> <p>But when i issue the above command it tells me to update the setup tools, and when I try to update or upgrade <code>setuptools</code> it says already up to date.</p> <p>Can someone suggest me what can be done in this case?</p>
1
2016-08-26T08:42:22Z
39,162,121
<p>Are you on a mac per chance? try adding the --user flag to your pip command</p>
0
2016-08-26T08:46:33Z
[ "python", "pip" ]
html5lib requires setuptools version 18.5 or above; please upgrade before installing (you have 0.6)
39,162,033
<p>When i try to give a pip install on my <code>requirements.txt</code> file, it fails as mentioned below: </p> <pre><code>html5lib requires setuptools version 18.5 or above; please upgrade before installing (you have 0.6) Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-5xXCfM/html5lib/ . </code></pre> <p>I did go through some of the previous post on this where some user mentioned it got resolved by specifying :</p> <pre><code>pip install html5lib --upgrade </code></pre> <p>But when i issue the above command it tells me to update the setup tools, and when I try to update or upgrade <code>setuptools</code> it says already up to date.</p> <p>Can someone suggest me what can be done in this case?</p>
1
2016-08-26T08:42:22Z
39,644,482
<p>It seems there's a <a href="https://github.com/html5lib/html5lib-python/issues/280" rel="nofollow">bug</a> in older <code>html5lib</code> versions that didn't support old <code>setuptools</code> versions, this is fixed in newer <code>html5lib</code> versions.</p> <p>So you can require a newer version of <code>html5lib</code> or if you can't mess with your dependencies just upgrade your <code>setuptools</code> with:</p> <pre><code>pip install -U setuptools </code></pre>
2
2016-09-22T16:38:11Z
[ "python", "pip" ]
Spark - How many Executors and Cores are allocated to my spark job
39,162,063
<p>Spark architecture is entirely revolves around the concept of executors and cores. I would like to see practically how many executors and cores running for my spark application running in a cluster. </p> <p>I was trying to use below snippet in my application but no luck.</p> <pre><code>val conf = new SparkConf().setAppName("ExecutorTestJob") val sc = new SparkContext(conf) conf.get("spark.executor.instances") conf.get("spark.executor.cores") </code></pre> <p>Is there any way to get those values using <code>SparkContext</code> Object or <code>SparkConf</code> object etc..</p>
2
2016-08-26T08:44:12Z
39,163,142
<h1>Scala (Programmatic way) :</h1> <p><code>getExecutorStorageStatus</code> and <code>getExecutorMemoryStatus</code> both return the number of executors including driver. like below example snippet.</p> <pre><code>/** Method that just returns the current active/registered executors * excluding the driver. * @param sc The spark context to retrieve registered executors. * @return a list of executors each in the form of host:port. */ def currentActiveExecutors(sc: SparkContext): Seq[String] = { val allExecutors = sc.getExecutorMemoryStatus.map(_._1) val driverHost: String = sc.getConf.get("spark.driver.host") allExecutors.filter(! _.split(":")(0).equals(driverHost)).toList } sc.getConf.getInt("spark.executor.instances", 1) </code></pre> <p>similarly get all properties and print like below you may get cores information as well..</p> <pre><code>sc.getConf.getAll.mkString("\n") </code></pre> <p>OR </p> <pre><code>sc.getConf.toDebugString </code></pre> <p>Mostly <code>spark.executor.cores</code> for executors <code>spark.driver.cores</code> driver should have this value.</p> <h1>Python :</h1> <p><a href="https://spark.apache.org/docs/latest/api/python/pyspark.html#pyspark.SparkContext" rel="nofollow">Above methods getExecutorStorageStatus and getExecutorMemoryStatus, In python api were not implemented</a></p>
1
2016-08-26T09:36:38Z
[ "python", "scala", "hadoop", "apache-spark", "executors" ]
Spark - How many Executors and Cores are allocated to my spark job
39,162,063
<p>Spark architecture is entirely revolves around the concept of executors and cores. I would like to see practically how many executors and cores running for my spark application running in a cluster. </p> <p>I was trying to use below snippet in my application but no luck.</p> <pre><code>val conf = new SparkConf().setAppName("ExecutorTestJob") val sc = new SparkContext(conf) conf.get("spark.executor.instances") conf.get("spark.executor.cores") </code></pre> <p>Is there any way to get those values using <code>SparkContext</code> Object or <code>SparkConf</code> object etc..</p>
2
2016-08-26T08:44:12Z
40,105,334
<p>This is python Example to get number of cores (including master's) <code>def workername(): import socket return str(socket.gethostname()) anrdd=sc.parallelize(['','']) namesRDD = anrdd.flatMap(lambda e: (1,workername())) namesRDD.count()</code></p>
0
2016-10-18T10:07:16Z
[ "python", "scala", "hadoop", "apache-spark", "executors" ]
how to increment mac address in python
39,162,221
<p>I am trying to send a request with name, id.no and mac address. This process i need to do for 100 times. i mean 100 different names and id.no's and mac address. I tried doing this. I want output as name1, 1234567679 and aa:bb:cc:dd:11:22. can someone please help me. I have pasted my code and output below </p> <pre><code>for i in range (1,10): name = 'name'+str(i) print name id = 121333445500000 id += 1 print id mac = "aa:bb:cc:dd:" ee = 0 for j in range(0,9): ee1 = '0'+str(ee + j)+':' ff = 0 for k in range(0,10): ff1 = ff+k if ff1 &lt; 10: mac1 = mac + ee1 + '0' + str(ff1) print mac1 else: mac1 = mac + ee1 + str(ff1) print mac1 </code></pre> <p>Output: </p> <pre><code>name1 121333445500001 aa:bb:cc:dd:00:00 aa:bb:cc:dd:00:01 aa:bb:cc:dd:00:02 aa:bb:cc:dd:00:03 aa:bb:cc:dd:00:04 aa:bb:cc:dd:00:05 aa:bb:cc:dd:00:06 aa:bb:cc:dd:00:07 aa:bb:cc:dd:00:08 aa:bb:cc:dd:00:09 aa:bb:cc:dd:01:00 aa:bb:cc:dd:01:01 aa:bb:cc:dd:01:02 aa:bb:cc:dd:01:03 aa:bb:cc:dd:01:04 aa:bb:cc:dd:01:05 aa:bb:cc:dd:01:06 aa:bb:cc:dd:01:07 aa:bb:cc:dd:01:08 aa:bb:cc:dd:01:09 aa:bb:cc:dd:02:00 aa:bb:cc:dd:02:01 aa:bb:cc:dd:02:02 aa:bb:cc:dd:02:03 aa:bb:cc:dd:02:04 aa:bb:cc:dd:02:05 aa:bb:cc:dd:02:06 aa:bb:cc:dd:02:07 aa:bb:cc:dd:02:08 aa:bb:cc:dd:02:09 aa:bb:cc:dd:03:00 aa:bb:cc:dd:03:01 aa:bb:cc:dd:03:02 aa:bb:cc:dd:03:03 aa:bb:cc:dd:03:04 aa:bb:cc:dd:03:05 aa:bb:cc:dd:03:06 aa:bb:cc:dd:03:07 aa:bb:cc:dd:03:08 aa:bb:cc:dd:03:09 aa:bb:cc:dd:04:00 aa:bb:cc:dd:04:01 aa:bb:cc:dd:04:02 aa:bb:cc:dd:04:03 aa:bb:cc:dd:04:04 aa:bb:cc:dd:04:05 aa:bb:cc:dd:04:06 aa:bb:cc:dd:04:07 aa:bb:cc:dd:04:08 aa:bb:cc:dd:04:09 aa:bb:cc:dd:05:00 aa:bb:cc:dd:05:01 aa:bb:cc:dd:05:02 aa:bb:cc:dd:05:03 aa:bb:cc:dd:05:04 aa:bb:cc:dd:05:05 aa:bb:cc:dd:05:06 aa:bb:cc:dd:05:07 aa:bb:cc:dd:05:08 aa:bb:cc:dd:05:09 aa:bb:cc:dd:06:00 aa:bb:cc:dd:06:01 aa:bb:cc:dd:06:02 aa:bb:cc:dd:06:03 aa:bb:cc:dd:06:04 aa:bb:cc:dd:06:05 aa:bb:cc:dd:06:06 aa:bb:cc:dd:06:07 aa:bb:cc:dd:06:08 aa:bb:cc:dd:06:09 aa:bb:cc:dd:07:00 aa:bb:cc:dd:07:01 aa:bb:cc:dd:07:02 aa:bb:cc:dd:07:03 aa:bb:cc:dd:07:04 aa:bb:cc:dd:07:05 aa:bb:cc:dd:07:06 aa:bb:cc:dd:07:07 aa:bb:cc:dd:07:08 aa:bb:cc:dd:07:09 aa:bb:cc:dd:08:00 aa:bb:cc:dd:08:01 aa:bb:cc:dd:08:02 aa:bb:cc:dd:08:03 aa:bb:cc:dd:08:04 aa:bb:cc:dd:08:05 aa:bb:cc:dd:08:06 aa:bb:cc:dd:08:07 aa:bb:cc:dd:08:08 aa:bb:cc:dd:08:09 name2 121333445500001 aa:bb:cc:dd:00:00 aa:bb:cc:dd:00:01 aa:bb:cc:dd:00:02 aa:bb:cc:dd:00:03 aa:bb:cc:dd:00:04 aa:bb:cc:dd:00:05 aa:bb:cc:dd:00:06 aa:bb:cc:dd:00:07 aa:bb:cc:dd:00:08 aa:bb:cc:dd:00:09 aa:bb:cc:dd:01:00 aa:bb:cc:dd:01:01 aa:bb:cc:dd:01:02 aa:bb:cc:dd:01:03 aa:bb:cc:dd:01:04 aa:bb:cc:dd:01:05 aa:bb:cc:dd:01:06 aa:bb:cc:dd:01:07 aa:bb:cc:dd:01:08 aa:bb:cc:dd:01:09 aa:bb:cc:dd:02:00 aa:bb:cc:dd:02:01 aa:bb:cc:dd:02:02 aa:bb:cc:dd:02:03 aa:bb:cc:dd:02:04 aa:bb:cc:dd:02:05 aa:bb:cc:dd:02:06 aa:bb:cc:dd:02:07 aa:bb:cc:dd:02:08 aa:bb:cc:dd:02:09 aa:bb:cc:dd:03:00 aa:bb:cc:dd:03:01 aa:bb:cc:dd:03:02 aa:bb:cc:dd:03:03 aa:bb:cc:dd:03:04 aa:bb:cc:dd:03:05 aa:bb:cc:dd:03:06 aa:bb:cc:dd:03:07 aa:bb:cc:dd:03:08 aa:bb:cc:dd:03:09 aa:bb:cc:dd:04:00 aa:bb:cc:dd:04:01 aa:bb:cc:dd:04:02 aa:bb:cc:dd:04:03 aa:bb:cc:dd:04:04 aa:bb:cc:dd:04:05 aa:bb:cc:dd:04:06 aa:bb:cc:dd:04:07 aa:bb:cc:dd:04:08 aa:bb:cc:dd:04:09 aa:bb:cc:dd:05:00 aa:bb:cc:dd:05:01 aa:bb:cc:dd:05:02 aa:bb:cc:dd:05:03 aa:bb:cc:dd:05:04 aa:bb:cc:dd:05:05 aa:bb:cc:dd:05:06 aa:bb:cc:dd:05:07 aa:bb:cc:dd:05:08 aa:bb:cc:dd:05:09 aa:bb:cc:dd:06:00 aa:bb:cc:dd:06:01 aa:bb:cc:dd:06:02 aa:bb:cc:dd:06:03 aa:bb:cc:dd:06:04 aa:bb:cc:dd:06:05 aa:bb:cc:dd:06:06 aa:bb:cc:dd:06:07 aa:bb:cc:dd:06:08 aa:bb:cc:dd:06:09 aa:bb:cc:dd:07:00 aa:bb:cc:dd:07:01 aa:bb:cc:dd:07:02 aa:bb:cc:dd:07:03 aa:bb:cc:dd:07:04 aa:bb:cc:dd:07:05 aa:bb:cc:dd:07:06 aa:bb:cc:dd:07:07 aa:bb:cc:dd:07:08 aa:bb:cc:dd:07:09 aa:bb:cc:dd:08:00 aa:bb:cc:dd:08:01 aa:bb:cc:dd:08:02 aa:bb:cc:dd:08:03 aa:bb:cc:dd:08:04 aa:bb:cc:dd:08:05 aa:bb:cc:dd:08:06 aa:bb:cc:dd:08:07 aa:bb:cc:dd:08:08 aa:bb:cc:dd:08:09 name3 121333445500001 </code></pre>
0
2016-08-26T08:52:30Z
39,163,460
<p>Try this code</p> <pre><code>import time, random mac = "aa:bb:cc:dd:" for i in range(1,100): name = 'name'+ str(i) # getting random number for id id = int(time.time()) + random.randrange(0, 100, 1) # quotient in part 1 mac_end1 = "0" + str(int(i/10)) # remainder in part 2 mac_end2 = "0" + str(int(i%10)) mac1 = mac + mac_end1 + ":" + mac_end2 print name, id, mac1 </code></pre>
0
2016-08-26T09:52:53Z
[ "python" ]
Alternative for numpy.choose that allows an arbitrary or at least more than 32 arguments?
39,162,235
<p>With my code I'm running into an issue where the <code>numpy.choose</code> methods does not accept all the arguments since it is limited by <code>NPY_MAXARGS</code> (<code>=32</code>). Is there an alternative available, that allows an arbitrary number of argument arrays or at least more than <code>32</code> that is as fast as <code>numpy.choose</code>?</p> <pre><code>choices = [np.arange(0,100)]*100 selection = [0] * 100 np.choose(selection, choices) &gt;&gt; ValueError: Need between 2 and (32) array objects (inclusive). </code></pre> <p>Any help would be appreciated... :)</p>
2
2016-08-26T08:53:24Z
39,169,371
<p>The indices can be given as lists. Assuming that <code>selections</code> has the same length as <code>choices</code>:</p> <pre><code>b = numpy.array(choices) result = b[range(len(selections)), selections] </code></pre> <p>will give the value in choices specified by the index in selections. See it in action:</p> <pre><code>numpy.random.seed(1) b = numpy.random.randint(0,100,(5,10)) &gt;&gt;&gt; array([[37, 12, 72, 9, 75, 5, 79, 64, 16, 1], [76, 71, 6, 25, 50, 20, 18, 84, 11, 28], [29, 14, 50, 68, 87, 87, 94, 96, 86, 13], [ 9, 7, 63, 61, 22, 57, 1, 0, 60, 81], [ 8, 88, 13, 47, 72, 30, 71, 3, 70, 21]]) selections = numpy.random.randint(0,10,5) &gt;&gt;&gt; array([1, 9, 3, 4, 8]) result = b[range(len(selections)),selections] &gt;&gt;&gt;&gt; array([12, 28, 68, 22, 70]) </code></pre>
2
2016-08-26T15:05:51Z
[ "python", "numpy" ]
Alternative for numpy.choose that allows an arbitrary or at least more than 32 arguments?
39,162,235
<p>With my code I'm running into an issue where the <code>numpy.choose</code> methods does not accept all the arguments since it is limited by <code>NPY_MAXARGS</code> (<code>=32</code>). Is there an alternative available, that allows an arbitrary number of argument arrays or at least more than <code>32</code> that is as fast as <code>numpy.choose</code>?</p> <pre><code>choices = [np.arange(0,100)]*100 selection = [0] * 100 np.choose(selection, choices) &gt;&gt; ValueError: Need between 2 and (32) array objects (inclusive). </code></pre> <p>Any help would be appreciated... :)</p>
2
2016-08-26T08:53:24Z
39,170,451
<p><code>choose</code> has the 32 object limit because it broadcasts the arrays together. Consider the error messages for these two actions:</p> <pre><code>In [982]: np.arange(33).choose(np.ones((33,33))) ... ValueError: Need at least 1 and at most 32 array objects. In [983]: np.broadcast(*range(33)) ... ValueError: Need at least 1 and at most 32 array objects. </code></pre> <p>An example exploiting that broadcasting, picking values from a 2d array, 1d and scalar.</p> <pre><code>In [998]: np.diag([2,1,0]).choose((np.arange(9).reshape(3,3), 0,[.1,.2,.3])) Out[998]: array([[ 0.1, 1. , 2. ], [ 3. , 0. , 5. ], [ 6. , 7. , 8. ]]) </code></pre> <p>As <code>@Benjamin</code> shows <code>np.choose</code> can be used to select items from the successive columns of a 2d array - provided there aren't more than 32 columns</p> <pre><code>In [1002]: M=np.arange(9).reshape(3,3) In [1003]: np.array([2,0,1]).choose(M) Out[1003]: array([6, 1, 5]) In [1004]: M[[2,0,1],[0,1,2]] Out[1004]: array([6, 1, 5]) </code></pre> <p>It was in just such a context that I recall first seeing this 32 array limit to <code>choose</code>, and one of the few where I've seen <code>choose</code> used in an answer.</p> <p>It is a compiled function, <code>PyArray_Choose</code> and <code>array_choose</code></p> <p><a href="https://github.com/numpy/numpy/blob/0b2e590ec18942f8f149ab2306b80da86b04eaeb/numpy/core/src/multiarray/item_selection.c" rel="nofollow">https://github.com/numpy/numpy/blob/0b2e590ec18942f8f149ab2306b80da86b04eaeb/numpy/core/src/multiarray/item_selection.c</a></p> <p><a href="https://github.com/numpy/numpy/blob/945c308e96fb815729e8f8aeb0ad6b39b8bdf84a/numpy/core/src/multiarray/methods.c" rel="nofollow">https://github.com/numpy/numpy/blob/945c308e96fb815729e8f8aeb0ad6b39b8bdf84a/numpy/core/src/multiarray/methods.c</a></p> <p>I don't see any uses of this function in other compiled numpy code. And apart from testing, little use in rest of <code>numpy</code>.</p>
1
2016-08-26T16:06:20Z
[ "python", "numpy" ]
Fit Points With a Smooth Curve
39,162,261
<p>I want to fit a set of points on a image with a <strong>smooth</strong> curve in python. The curve may be open or closed. Moreover, I want to get the curve plotted over the image as a mask that has the same size as the image. Is there any modules or functions I can refer to? Thanks.</p>
-2
2016-08-26T08:54:45Z
39,166,624
<p>This is generally called Parametric Interpolation. There is a scipy function that does just that called <a href="http://scipy.github.io/devdocs/generated/scipy.interpolate.splprep.html" rel="nofollow">splprep</a>. The steps you are requesting are:</p> <p><strong>1)</strong> Smooth a shape (built with ordered points, if not use <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.ConvexHull.html" rel="nofollow">convex hull</a> first, check <a href="http://stackoverflow.com/questions/36763853/plotting-a-set-of-given-points-to-form-a-closed-curve-in-matplotlib/36764052#36764052">this question</a>).</p> <p><strong>NOTE:</strong> <em>for more on how to create a shape over an image check</em> <a href="http://stackoverflow.com/questions/37103604/extract-image-segment-from-polygon-with-skimage/37149857#37149857">this question</a>.</p> <p><strong>2)</strong> Use the smooth shape to build a mask over an image (lets say 2D array).</p> <p>The following recipe does that:</p> <pre><code>import numpy as np from scipy.interpolate import splprep, splev import matplotlib.pyplot as plt from matplotlib import path # Building a shape with scattered points. x = np.array([10, 10, 0, 0, 10, 10, 20, 20, 30, 30, 20, 20, 10]) + 10 y = np.array([0, 10, 10, 20, 20, 30, 30, 20, 20, 10, 10, 0, 0]) + 10 image = np.random.randint(0, 10, (50, 50)) # Smoothing the shape. # spline parameters s = 3.0 # smoothness parameter k = 2 # spline order nest = -1 # estimate of number of knots needed (-1 = maximal) t, u = splprep([x, y], s=s, k=k, nest=-1) xn, yn = splev(np.linspace(0, 1, 500), t) # Showing the original shape plt.imshow(image.T, origin='lower', interpolation='nearest', cmap='gray') plt.plot(x, y, color='b', linewidth=3) plt.xlim(0, 50) plt.ylim(0, 50) plt.show() # Showing the original shape vs smooth shape plt.imshow(image.T, origin='lower', interpolation='nearest', cmap='gray') plt.plot(x, y, color='b', linewidth=3) plt.plot(xn, yn, color='r', linewidth=3) plt.xlim(0, 50) plt.ylim(0, 50) plt.show() # Changing values inside the shape (and outside). Building a boolean mask. image1 = image.copy() image2 = image.copy() mask = np.zeros(image.shape) xx, yy = np.meshgrid(range(image.shape[0]),range(image.shape[1])) shapes = np.hstack((xn[:, np.newaxis], yn[:, np.newaxis])) p = path.Path(shapes) for i in range(image.shape[0]): for j in range(image.shape[1]): if not p.contains_point((i, j)): image1[i, j] = 0 mask[i, j] = True else: image2[i, j] = 0 # Showing changes in image for values outside shape. plt.imshow(image1.T, origin='lower', interpolation='nearest', cmap='gray') plt.plot(xn, yn, color='r', linewidth=3) plt.xlim(0, 50) plt.ylim(0, 50) plt.show() # Showing changes in image for values inside shape. plt.imshow(image2.T, origin='lower', interpolation='nearest', cmap='gray') plt.plot(xn, yn, color='r', linewidth=3) plt.xlim(0, 50) plt.ylim(0, 50) plt.show() </code></pre> <p>The code is commented for you to know what is happening at each of the plots of the results:</p> <p><a href="http://i.stack.imgur.com/FmrIe.png" rel="nofollow"><img src="http://i.stack.imgur.com/FmrIe.png" alt="Simple Shape over image"></a> 1. <em>Simple Shape over image</em></p> <p><a href="http://i.stack.imgur.com/c3QX6.png" rel="nofollow"><img src="http://i.stack.imgur.com/c3QX6.png" alt="Simple vs Smooth shape over image"></a> 2. <em>Simple vs Smooth shape over image</em></p> <p><a href="http://i.stack.imgur.com/Q6REa.png" rel="nofollow"><img src="http://i.stack.imgur.com/Q6REa.png" alt="Use values inside shape"></a> 3. <em>Use values inside shape</em></p> <p><a href="http://i.stack.imgur.com/ZLu8a.png" rel="nofollow"><img src="http://i.stack.imgur.com/ZLu8a.png" alt="Use values outside shape"></a> 4. <em>Use values outside shape</em></p>
0
2016-08-26T12:41:55Z
[ "python", "opencv", "matplotlib", "computer-vision", "skimage" ]
system cannot find the path specified in Python2.7
39,162,304
<p>I am using Python 2.7 on windows. I am getting "Calling function "tests/scripts/Script.py"... The system cannot find the path specified when the tests are executed.</p> <p>How to resolve this?</p>
-1
2016-08-26T08:57:32Z
39,162,542
<p>You need to add python Lib and Scrip path to your system environment. To do that type > Edit the system environment variables in search box of start menu. go to edit variable and add python required path to system path.</p>
0
2016-08-26T09:08:29Z
[ "python", "python-2.7" ]
Python add constant values to argparse parameter
39,162,308
<p>I have googled this around but can't seem to find if this question has been asked already. I want to have a value (say "blah") to be always present for a list option, plus additional arguments if they are provided.</p> <p>e.g.</p> <pre><code>import argparse args = argparse.ArgumentParser() args.add_argument("--foo", nargs="+") args = args.parse_args(["--foo", "bar1", "bar2", "bar3"]) args.foo.append("blah") print args.foo ['bar1', 'bar2', 'bar3', 'blah'] </code></pre>
0
2016-08-26T08:57:43Z
39,162,344
<p><code>argparse</code> has no facility to <em>add</em> a fixed set of values to <code>nargs</code> lists. </p> <p>Just do what you already do and explicitly append to the list produced. </p>
0
2016-08-26T08:59:25Z
[ "python", "argparse" ]
Python add constant values to argparse parameter
39,162,308
<p>I have googled this around but can't seem to find if this question has been asked already. I want to have a value (say "blah") to be always present for a list option, plus additional arguments if they are provided.</p> <p>e.g.</p> <pre><code>import argparse args = argparse.ArgumentParser() args.add_argument("--foo", nargs="+") args = args.parse_args(["--foo", "bar1", "bar2", "bar3"]) args.foo.append("blah") print args.foo ['bar1', 'bar2', 'bar3', 'blah'] </code></pre>
0
2016-08-26T08:57:43Z
39,162,978
<p>Inspired by <a href="http://stackoverflow.com/questions/8526675/python-argparse-optional-append-argument-with-choices">python argparse - optional append argument with choices</a>, this may be a little overkill, but it may be useful for others that want to use sets and add constant values to options:</p> <pre><code>import argparse DEFAULT = set(['blah']) class DefaultSet(argparse.Action): def __call__(self, parser, namespace, values, option_string=None): default_set = DEFAULT if values: default_set.update(v) setattr(namespace, self.dest, default_set) args = argparse.ArgumentParser() args.add_argument("--foo", default=DEFAULT, action=DefaultSet,nargs="+") args = args.parse_args(["--foo", "bar1", "bar2", "bar3"]) print args.foo set(['bar1', 'blah', 'bar3', 'bar2']) </code></pre> <p>The only problem is that the custom action is only called when foo is specified with at least 1 argument. That is why I had to include <code>DEFAULT</code> in <code>add_argument</code> definition.</p>
0
2016-08-26T09:29:02Z
[ "python", "argparse" ]
Why does statistics.variance use 'unbiased' sample variance by default?
39,162,505
<p>I have recently started using the statistics module for python.</p> <p>I've noticed that by default the variance() method returns the 'unbiased' variance or sample variance:</p> <pre><code>import statistics as st from random import randint def myVariance(data): # finds the variance of a given set of numbers xbar = st.mean(data) return sum([(x - xbar)**2 for x in data])/len(data) def myUnbiasedVariance(data): # finds the 'unbiased' variance of a given set of numbers (divides by N-1) xbar = st.mean(data) return sum([(x - xbar)**2 for x in data])/(len(data)-1) population = [randint(0, 1000) for i in range(0,100)] print myVariance(population) print myUnbiasedVariance(population) print st.variance(population) </code></pre> <p>output:</p> <pre><code>81295.8011 82116.9708081 82116.9708081 </code></pre> <p>This seems odd to me. I guess a lot of the time people are working with samples so they want a sample variance, but i would expect the default function to calculate a population variance. Does anyone know why this is?</p>
1
2016-08-26T09:06:44Z
39,195,083
<p>I would argue that almost all the time when people estimate the variance from data they work with a sample. And, by the definition of <em>unbiased estimate</em>, the expected value of the unbiased estimate of the variance equals the population variance.</p> <p>In your code, you use <code>random.randint(0, 1000)</code>, which samples from a discrete uniform distribution with 1001 possible values and variance 1000*1002/12 = 83500 (see, e.g., <a href="http://mathworld.wolfram.com/DiscreteUniformDistribution.html" rel="nofollow">MathWorld</a>). Here code that shows that, on average and when using samples as input, <code>statistics.variance()</code> gets closer to the population variance than <code>statistics.pvariance()</code>:</p> <pre><code>import statistics as st, random, numpy as np var, pvar = [], [] for i in range(10000): smpl = [random.randint(0, 1000) for j in range(10)] var.append(st.variance(smpl)) pvar.append(st.pvariance(smpl)) print "mean variance(sample): %.1f" %np.mean(var) print "mean pvariance(sample): %.1f" %np.mean(pvar) print "pvariance(population): %.1f" %st.pvariance(range(1001)) </code></pre> <p>Here sample output:</p> <pre><code>mean variance(sample): 83626.0 mean pvariance(sample): 75263.4 pvariance(population): 83500.0 </code></pre>
0
2016-08-28T19:39:21Z
[ "python", "statistics", "variance" ]
Use ipdb instead of pdb with py.test --pdb option
39,162,569
<p>I want to use <a href="https://pypi.python.org/pypi/ipdb" rel="nofollow">ipdb</a> instead of <a href="https://docs.python.org/2/library/pdb.html" rel="nofollow">pdb</a> with <a href="http://docs.pytest.org/en/latest/contents.html" rel="nofollow">py.test --pdb</a> option. Is this possible? If so, how?</p> <p>Clearly, I can use <code>import ipdb; ipdb.set_trace()</code> in the code but that requires to run the test, watch it fail, open a file, find the point of failure in said file, write the above line, re-run the tests. Lots of hassle if I could have something that by passes all of that.</p>
0
2016-08-26T09:09:29Z
39,172,917
<p>Have you tried <a href="https://github.com/mverteuil/pytest-ipdb" rel="nofollow">pytest-ipdb</a>?</p> <p>Looks like it's exactly what you are looking for?</p>
1
2016-08-26T18:46:57Z
[ "python", "py.test", "pdb", "ipdb" ]
AJAX/PYTHON : how to send json value to server
39,162,601
<p>I am a new to Ajax/Python, I don't know how to POST a json value to my python server.</p> <p>Python code: </p> <pre><code>@app.route('/ajouterContact', methods = ['POST']) def ajouterContact(): data = json.loads(request.data) #nom = request.form['nomContact']; contact.append(data) ajouter.make_response(json.dumps(contact), 201) ajouter.headers['Content-Type'] = 'application/json' </code></pre> <p>JS code</p> <pre><code>$('#buttonAjouter').click(function() { var nom = 'Tom'; var myObj = new Object(); myObj.nom = nom; var jsonText = JSON.stringify(myObj); var i = 0; $.ajax({ url: '/ajouterContact', data: jsonText, type: 'POST', dataType: "json", success: function(response) { console.log(response); }, error: function(error) { console.log(error); } }); }); </code></pre> <p>I am getting this error on server side : </p> <blockquote> <p>ValueError: No JSON object could be decoded</p> </blockquote> <p>If anyone can help me on this..<br> Thank you!</p>
0
2016-08-26T09:11:08Z
39,162,757
<p>You need to provide the contentType in your ajax request:</p> <pre><code>contentType: 'application/json;charset=UTF-8', </code></pre> <p>Then in your server try to debug something like this:</p> <pre><code>request.json </code></pre>
0
2016-08-26T09:19:31Z
[ "python", "ajax" ]
Split each element by bracket in variable and find occurrence
39,162,681
<p>I have a text file which has arrays appended to them<a href="http://i.stack.imgur.com/2B1zP.png" rel="nofollow"><img src="http://i.stack.imgur.com/2B1zP.png" alt="&#39;image&#39;"></a> What I want to do is extract it from the text file and work out how many times <code>index[2]</code> occurs for each word in the text file. For instance hablar occurs once etc. I will then use that to plot a graph. </p> <p>The problem is that when i import the file it comes as a list within a list</p> <pre><code>with open("wrongWords.txt") as file: array1 = [] array2 = [] for element in file: array1.append(element) x=array1[0] print(x) </code></pre> <p>Printing x gives me </p> <p><code>(12, 'a', 'hablar', 'to speak')(51, 'a', 'ocurrir', 'to occur/happen')(12, 'a', 'hablar', 'to speak')(2, 'a', 'poder', 'to be able')(11, 'a', 'llamar', 'to call/name')</code></p>
0
2016-08-26T09:15:02Z
39,162,820
<p>To convert your <code>string</code> into <code>list</code>, do:</p> <pre><code>&gt;&gt;&gt; s = "(12, 'a', 'hablar', 'to speak')(51, 'a', 'ocurrir', 'to occur/happen')(12, 'a', 'hablar', 'to speak')(2, 'a', 'poder', 'to be able')(11, 'a', 'llamar', 'to call/name')" &gt;&gt;&gt; s = s.replace(')(', '),(') # s = "(12, 'a', 'hablar', 'to speak'),(51, 'a', 'ocurrir', 'to occur/happen'),(12, 'a', 'hablar', 'to speak'),(2, 'a', 'poder', 'to be able'),(11, 'a', 'llamar', 'to call/name')" &gt;&gt;&gt; my_list = list(eval(s)) # my_list = [(12, 'a', 'hablar', 'to speak'), (51, 'a', 'ocurrir', 'to occur/happen'), (12, 'a', 'hablar', 'to speak'), (2, 'a', 'poder', 'to be able'), (11, 'a', 'llamar', 'to call/name')] </code></pre> <p>To get the count of each <code>key</code> (at index 2 in your case) in <code>list</code>:</p> <pre><code>&gt;&gt;&gt; my_dict = {} &gt;&gt;&gt; for item in my_list: ... my_dict[item[2]] = my_dict.get(item[2], 0) + 1 ... &gt;&gt;&gt; my_dict {'hablar': 2, 'ocurrir': 1, 'poder': 1, 'llamar': 1} </code></pre>
0
2016-08-26T09:21:56Z
[ "python", "text", "matplotlib", "find-occurrences" ]
How to find sum of list of lists using for-loop
39,162,845
<pre><code>prefer_indic = [[[0, 4, 6, 5, 45, 1], [2, 3, 5, 6, 7, 1]],[[0, 0.27, 6, 7, 32, 3], [0.01, 0.39, 0, 0, 0, 0]]] </code></pre> <p>I want to create a sum list that will add every value from every list of lists with each corresponding ones. To be accurate i want: </p> <p><code>sum = [[0+0, 4+0.27, 6+6, 5+7, 45+32, 1+3], [2+0.1, 3+0.39, 5+0, 6+0, 7+0, 1+0]]</code></p> <p>I want to do it with a for loop so that i can use the same algorithm for bigger list of lists.I made the example simple to make it more readable. I have python 2.7 .</p>
1
2016-08-26T09:23:06Z
39,162,940
<p>Use the <a href="https://docs.python.org/2/library/functions.html#zip" rel="nofollow"><code>zip()</code> function</a> to pair up elements from 2 or more lists, then use <a href="https://docs.python.org/2/library/functions.html#sum" rel="nofollow"><code>sum()</code></a> to add up the combined values:</p> <pre><code>summed = [[sum(zipped) for zipped in zip(*column)] for column in zip(*prefer_indic)] </code></pre> <p>Note the <code>zip(*prefer_indic)</code> call, which <em>transposes</em> your matrix so that you pair up the 'columns' of your nested lists, not the rows.</p> <p>If your lists are larger, it may be beneficial to using the <a href="https://docs.python.org/2/library/itertools.html#itertools.izip" rel="nofollow"><em>iterative</em> version of <code>zip</code></a>; use the <a href="https://docs.python.org/2/library/future_builtins.html#future_builtins.zip" rel="nofollow"><code>future_builtins.zip()</code> location</a> and your code is automatically forward-compatible with Python 3:</p> <pre><code>try: from future_builtins import zip except ImportError: # Python 3 summed = [[sum(zipped) for zipped in zip(*column)] for column in zip(*prefer_indic)] </code></pre> <p>Demo:</p> <pre><code>&gt;&gt;&gt; from future_builtins import zip &gt;&gt;&gt; prefer_indic = [[[0, 4, 6, 5, 45, 1], [2, 3, 5, 6, 7, 1]],[[0, 0.27, 6, 7, 32, 3], [0.01, 0.39, 0, 0, 0, 0]]] &gt;&gt;&gt; [[sum(zipped) for zipped in zip(*column)] for column in zip(*prefer_indic)] [[0, 4.27, 12, 12, 77, 4], [2.01, 3.39, 5, 6, 7, 1]] </code></pre>
3
2016-08-26T09:27:31Z
[ "python", "python-2.7", "for-loop", "sum" ]
How to find sum of list of lists using for-loop
39,162,845
<pre><code>prefer_indic = [[[0, 4, 6, 5, 45, 1], [2, 3, 5, 6, 7, 1]],[[0, 0.27, 6, 7, 32, 3], [0.01, 0.39, 0, 0, 0, 0]]] </code></pre> <p>I want to create a sum list that will add every value from every list of lists with each corresponding ones. To be accurate i want: </p> <p><code>sum = [[0+0, 4+0.27, 6+6, 5+7, 45+32, 1+3], [2+0.1, 3+0.39, 5+0, 6+0, 7+0, 1+0]]</code></p> <p>I want to do it with a for loop so that i can use the same algorithm for bigger list of lists.I made the example simple to make it more readable. I have python 2.7 .</p>
1
2016-08-26T09:23:06Z
39,163,054
<p>I would define a function that adds two lists, then use a list comprehension to compute your desired result:</p> <pre><code>def add_lists(a, b): return list(x+y for x, y in zip(a, b)) s = list(add_lists(*l) for l in zip(*prefer_indic)) </code></pre> <p>For you example</p> <pre><code>prefer_indic = [[[0, 4, 6, 5, 45, 1], [2, 3, 5, 6, 7, 1]],[[0, 0.27, 6, 7, 32, 3], [0.01, 0.39, 0, 0, 0, 0]]] </code></pre> <p>the result will be</p> <pre><code>[[0, 4.27, 12, 12, 77, 4], [2.01, 3.39, 5, 6, 7, 1]] </code></pre>
0
2016-08-26T09:32:38Z
[ "python", "python-2.7", "for-loop", "sum" ]
Python list of lists conversion into dictionary
39,162,857
<p>I'm trying to convert a list of lists into dictionary, but I'm getting troubles. Would anyone give some tips ?</p> <p>This my input:</p> <pre><code>[['Column1', 'Column2', 'Column3', 'Column4', 'Column5'], ['Value1Column1', 'Value1Column2', 'Value1Column3', 'Value1Column4', 'Value1Column5'], ['Value2Column1', 'Value2Column2', 'Value2Column3', 'Value2Column4', 'Value2Column5'], ..., ['ValueXColumn1','ValueXColumn2', 'ValueXColumn3', 'ValueXColumn4', 'ValueXColumn5']] </code></pre> <p>Having this I would like to create a dictionary, where my keys would be <strong>only</strong> elements from 1st list which are <strong>Column1, Column2...Column5</strong>. </p> <p>It's also known that for each key exact value is element from the rest of lists: </p> <p>Column1 --> Value1Column1, Value2Column1...</p> <p>Column2 --> Value1Column2, Value2Column2...</p> <p><strong>Expected result:<br></strong></p> <pre><code>"Column1": ["Value1Column1", "Value2Column1"...] </code></pre> <p>I've been trying with zip, enumurate (maybe wrongly used) and got always unexpected output. Thanks!</p>
0
2016-08-26T09:23:47Z
39,162,956
<pre><code>a = [['Column1', 'Column2', 'Column3', 'Column4', 'Column5'], ['Value1Column1', 'Value1Column2', 'Value1Column3', 'Value1Column4', 'Value1Column5'], ['Value2Column1', 'Value2Column2', 'Value2Column3', 'Value2Column4', 'Value2Column5']] [{a[0][i]: [j[i] for j in a[1:]] for i in range(len(a[0]))}] </code></pre> <p>gives</p> <pre><code>[{'Column1': ['Value1Column1', 'Value2Column1'], 'Column2': ['Value1Column2', 'Value2Column2'], 'Column3': ['Value1Column3', 'Value2Column3'], 'Column4': ['Value1Column4', 'Value2Column4'], 'Column5': ['Value1Column5', 'Value2Column5']}] </code></pre>
0
2016-08-26T09:28:14Z
[ "python", "dictionary", "data-type-conversion" ]
Python list of lists conversion into dictionary
39,162,857
<p>I'm trying to convert a list of lists into dictionary, but I'm getting troubles. Would anyone give some tips ?</p> <p>This my input:</p> <pre><code>[['Column1', 'Column2', 'Column3', 'Column4', 'Column5'], ['Value1Column1', 'Value1Column2', 'Value1Column3', 'Value1Column4', 'Value1Column5'], ['Value2Column1', 'Value2Column2', 'Value2Column3', 'Value2Column4', 'Value2Column5'], ..., ['ValueXColumn1','ValueXColumn2', 'ValueXColumn3', 'ValueXColumn4', 'ValueXColumn5']] </code></pre> <p>Having this I would like to create a dictionary, where my keys would be <strong>only</strong> elements from 1st list which are <strong>Column1, Column2...Column5</strong>. </p> <p>It's also known that for each key exact value is element from the rest of lists: </p> <p>Column1 --> Value1Column1, Value2Column1...</p> <p>Column2 --> Value1Column2, Value2Column2...</p> <p><strong>Expected result:<br></strong></p> <pre><code>"Column1": ["Value1Column1", "Value2Column1"...] </code></pre> <p>I've been trying with zip, enumurate (maybe wrongly used) and got always unexpected output. Thanks!</p>
0
2016-08-26T09:23:47Z
39,162,961
<p>This is the verbose, but straight forward version:</p> <pre><code>from collections import defaultdict keys = lst[0] rows = lst[1:] result = defaultdict(list) for row in rows: for key, value in zip(keys, row): result[key].append(value) </code></pre>
1
2016-08-26T09:28:23Z
[ "python", "dictionary", "data-type-conversion" ]
Python list of lists conversion into dictionary
39,162,857
<p>I'm trying to convert a list of lists into dictionary, but I'm getting troubles. Would anyone give some tips ?</p> <p>This my input:</p> <pre><code>[['Column1', 'Column2', 'Column3', 'Column4', 'Column5'], ['Value1Column1', 'Value1Column2', 'Value1Column3', 'Value1Column4', 'Value1Column5'], ['Value2Column1', 'Value2Column2', 'Value2Column3', 'Value2Column4', 'Value2Column5'], ..., ['ValueXColumn1','ValueXColumn2', 'ValueXColumn3', 'ValueXColumn4', 'ValueXColumn5']] </code></pre> <p>Having this I would like to create a dictionary, where my keys would be <strong>only</strong> elements from 1st list which are <strong>Column1, Column2...Column5</strong>. </p> <p>It's also known that for each key exact value is element from the rest of lists: </p> <p>Column1 --> Value1Column1, Value2Column1...</p> <p>Column2 --> Value1Column2, Value2Column2...</p> <p><strong>Expected result:<br></strong></p> <pre><code>"Column1": ["Value1Column1", "Value2Column1"...] </code></pre> <p>I've been trying with zip, enumurate (maybe wrongly used) and got always unexpected output. Thanks!</p>
0
2016-08-26T09:23:47Z
39,162,968
<p>It's really simple with <a href="http://stackoverflow.com/questions/1747817/create-a-dictionary-with-list-comprehension-in-python">dict comprehension</a> and <a href="https://docs.python.org/3.5/library/functions.html#zip" rel="nofollow">zip function</a>.</p> <pre><code>seq_of_seq = [['Column1', 'Column2', 'Column3', 'Column4', 'Column5'], ['Value1Column1', 'Value1Column2', 'Value1Column3', 'Value1Column4', 'Value1Column5'], ['Value2Column1', 'Value2Column2', 'Value2Column3', 'Value2Column4', 'Value2Column5'], ['ValueXColumn1', 'ValueXColumn2', 'ValueXColumn3', 'ValueXColumn4', 'ValueXColumn5']] d = {s[0]: s[1:] for s in zip(*seq_of_seq)} </code></pre> <p>This yields values as tuples:</p> <pre><code>{'Column1': ('Value1Column1', 'Value2Column1', 'ValueXColumn1'), 'Column2': ('Value1Column2', 'Value2Column2', 'ValueXColumn2'), 'Column3': ('Value1Column3', 'Value2Column3', 'ValueXColumn3'), 'Column4': ('Value1Column4', 'Value2Column4', 'ValueXColumn4'), 'Column5': ('Value1Column5', 'Value2Column5', 'ValueXColumn5')} </code></pre> <p>If you really need lists use:</p> <pre><code>d = {s[0]: list(s[1:]) for s in zip(*seq_of_seq)} </code></pre> <p>Result: </p> <pre><code>{'Column1': ['Value1Column1', 'Value2Column1', 'ValueXColumn1'], 'Column2': ['Value1Column2', 'Value2Column2', 'ValueXColumn2'], 'Column3': ['Value1Column3', 'Value2Column3', 'ValueXColumn3'], 'Column4': ['Value1Column4', 'Value2Column4', 'ValueXColumn4'], 'Column5': ['Value1Column5', 'Value2Column5', 'ValueXColumn5']} </code></pre>
4
2016-08-26T09:28:38Z
[ "python", "dictionary", "data-type-conversion" ]
Python access and list the files in network share with username and password
39,162,869
<p>I would like to get list of filenames(Only) from the given FileShare location using Python Language. Here is my Code snippet, but it is not running listing any files.</p> <pre><code> import os from os import walk SQLSR_USER= 'username' SQLSR_PASS= 'password' BACKUP_REPOSITORY_PATH= '\\fileshare\location' fileList = [] backup_storage_available = os.path.isdir(BACKUP_REPOSITORY_PATH) if backup_storage_available: print("Backup storage already connected.") else: print("Connecting to backup storage.") mount_command = "net use /user:" + SQLSR_USER + " " + BACKUP_REPOSITORY_PATH + " " + SQLSR_PASS os.system(mount_command) backup_storage_available = os.path.isdir(BACKUP_REPOSITORY_PATH) if backup_storage_available: print ("Connection success.") else: raise Exception("Failed to find storage directory.") for (dirpath, dirnames, filenames) in walk(backup_storage_available): fileList.extend(filenames) break if (len(fileList) &gt; 1): print "\n\n *********************Required data files are present in the FileShare*********************" else: print "\n\n ********************* No files are present to start the Next Run *********************" </code></pre> <p>Still I have a Problem with NET USE connection command listed down</p> <pre><code> mount_command = "net use /user:" + SQLSR_USER + " " + BACKUP_REPOSITORY_PATH + " " + SQLSR_PASS os.system(mount_command) backup_storage_available = os.path.isdir(BACKUP_REPOSITORY_PATH) </code></pre>
0
2016-08-26T09:24:17Z
39,205,661
<p>Finally I solved my problem using pywin32 module. Below is the code for that.</p> <pre><code> def wnet_connect(host, username, password): unc = ''.join(['\\\\', host]) try: win32wnet.WNetAddConnection2(0, None, unc, None, username, password) except Exception, err: if isinstance(err, win32wnet.error): # Disconnect previous connections if detected, and reconnect. if err[0] == 1219: win32wnet.WNetCancelConnection2(unc, 0, 0) return wnet_connect(host, username, password) raise err # Ensure required data files are present in Isilon landing zone of that application context(Eg: gwhp) def isLZFilesExist(SHAREPATH): wnet_connect(HOST, USER, PASS) path = ''.join(['\\\\', HOST, '\\', SHAREPATH.replace(':', '$')]) fileList = [] if os.path.exists(path): for (dirpath, dirnames, filenames) in walk(path): fileList.extend(filenames) break if (len(fileList) &gt; 1): print fileList print "\n\n *********************Required data files are present in the FileShare of that application context(Eg: gwhp)*********************" excelResult[0]='PASS' else: print "\n\n ********************* No files are present to start the Next Run *********************" sys.exit(0) </code></pre>
0
2016-08-29T11:51:45Z
[ "python", "python-2.7", "subprocess" ]
Regex for log lines that may be slightly different from each other- in spark
39,162,999
<p>I could write a regex for matching one log line. But my file contains some log lines which differ from the other log lines in that there are just a few extra fields or in a few, the key value pairs are mixed up. </p> <p>Eg. one log line : <code>case_id=1 event_id=35654423 date=30-12-2010 time=11.02 activity=registerrequest name=Pete costs=50 rerr="-"</code></p> <p>another one : <code>case_id=1 event_id=35654424 date=31-12-2010 time=11.07 costs=400 rerr="-" activity=examinethoroughly name=Sue rloc="-"</code></p> <p>My log pattern = <code>"^([^\s]+)\s([^\s]+)\s([^\s]+)\s([^\s]+)\s([^\s]+)\s([^\s]+)\s([^\s]+)\s([^\s]+)"</code> This is my code for grouping in spark: </p> <pre><code>match = re.search(LOG_PATTERN,line) Case_ID = match.group(1) Event_ID = match.group(2) Date = match.group(3) Time = match.group(4) Activity = match.group(5) Resource = match.group(6) Costs = match.group(7) Rerr = match.group(8) </code></pre> <p>This code would match only the 1st log line. How do i write a regex so that i can group them in spark without ignoring any of the log lines?</p>
1
2016-08-26T09:30:06Z
39,163,593
<p>I suggest you use a simple regex to grab keys and values:</p> <pre><code>rx = "(\\S+)=(\\S+)" </code></pre> <p>or</p> <pre><code>rx = "(\\w+)=(\\S+)" </code></pre> <p>See a <a href="https://regex101.com/r/jA0zB2/1" rel="nofollow">regex demo</a>.</p> <p>Then, create a dictionary with <code>re.findall</code>:</p> <pre><code>d = dict([(x,y) for x,y in re.findall(rx,line)]) </code></pre> <p>Then, you have access to each key-value.</p>
1
2016-08-26T09:59:49Z
[ "python", "regex", "apache-spark", "pyspark" ]
Mock for context-manager fails with AttributeError: __exit__
39,163,207
<p>I am trying to patch some context manager function using a Mock so I can test that the code does sensible things given good, bad, and garbage input. Here is the test code with the <code>with</code> statement in it. The patch is done in the correct place in my code.</p> <pre><code>@patch("__main__.opened_w_error") def test_get_recipe_file(self, mo): mo.return_value = (Mock(), None) mo.__enter__ = Mock(return_value=None) mo.__exit__ = Mock(return_value=None) with mo(…) as (fd, err): # AttributeError: __exit__ is raised here. print(fd) print(err) </code></pre> <p>However the <code>with mo(…) as (fd, err)</code> raises <code>AttributeError: __exit__</code>.</p> <p>The <a href="http://www.voidspace.org.uk/python/mock/magicmock.html?highlight=__exit__" rel="nofollow">documentation for mocking magic methods</a> states the you should use it as</p> <pre><code>with mo as (fd, err): … </code></pre> <p>The latter piece of code is what I am trying to mock. but that is not how I use it in my code. For those really interested, I am trying to mock <a href="https://www.python.org/dev/peps/pep-0343/" rel="nofollow">example 6 <code>opened_w_error()</code> in PEP 343</a> which deals with opening files and catching errors. Thus the code is:</p> <pre><code>with open_w_error(filename, 'r') as (fd, err): … </code></pre> <p>The latter is what I am trying to mock.</p>
1
2016-08-26T09:39:33Z
39,163,509
<p>Note that the object you pass to the <em>with</em> statement is the one that should have <code>__enter__</code> and <code>__exit__</code> methods, with the return value from <code>__enter__</code> used for the <code>as</code> construct. In your case, you are calling <code>mo(...)</code>, which returns <code>(Mock(), None)</code>, and this is not a context manager. You should move this return value to the <code>__enter__</code> method.</p> <pre><code>@patch("__main__.opened_w_error") def test_get_recipe_file(self, mo): mo.__enter__ = Mock(return_value=(Mock(), None)) mo.__exit__ = Mock(return_value=None) with mo as (fd, err): print(fd) print(err) </code></pre> <p><strong>EDIT</strong>: If you still want to call <code>mo</code>, then make its return value a context manager.</p> <pre><code>@patch("__main__.opened_w_error") def test_get_recipe_file(self, m_opened_w_error): mo = Mock() mo.__enter__ = Mock(return_value=(Mock(), None)) mo.__exit__ = Mock(return_value=None) m_opened_w_error.return_value = mo with m_opened_w_error(...) as (fd, err): print(fd) print(err) </code></pre>
1
2016-08-26T09:55:40Z
[ "python", "mocking" ]
Mock for context-manager fails with AttributeError: __exit__
39,163,207
<p>I am trying to patch some context manager function using a Mock so I can test that the code does sensible things given good, bad, and garbage input. Here is the test code with the <code>with</code> statement in it. The patch is done in the correct place in my code.</p> <pre><code>@patch("__main__.opened_w_error") def test_get_recipe_file(self, mo): mo.return_value = (Mock(), None) mo.__enter__ = Mock(return_value=None) mo.__exit__ = Mock(return_value=None) with mo(…) as (fd, err): # AttributeError: __exit__ is raised here. print(fd) print(err) </code></pre> <p>However the <code>with mo(…) as (fd, err)</code> raises <code>AttributeError: __exit__</code>.</p> <p>The <a href="http://www.voidspace.org.uk/python/mock/magicmock.html?highlight=__exit__" rel="nofollow">documentation for mocking magic methods</a> states the you should use it as</p> <pre><code>with mo as (fd, err): … </code></pre> <p>The latter piece of code is what I am trying to mock. but that is not how I use it in my code. For those really interested, I am trying to mock <a href="https://www.python.org/dev/peps/pep-0343/" rel="nofollow">example 6 <code>opened_w_error()</code> in PEP 343</a> which deals with opening files and catching errors. Thus the code is:</p> <pre><code>with open_w_error(filename, 'r') as (fd, err): … </code></pre> <p>The latter is what I am trying to mock.</p>
1
2016-08-26T09:39:33Z
39,164,160
<p>The issue is when you're calling <code>mo(..)</code> the object it is returning(<code>tuple</code>) doesn't have <code>__enter__</code> and <code>__exit__</code> attributes on it.</p> <p>To fix this assign <code>mo</code> to <code>mo</code>'s <code>return_value</code> so that the context manager attributes you're setting on it can still be found.</p> <pre><code>@patch("__main__.opened_w_error") def test_get_recipe_file(self, mo): mo.return_value = mo mo.__enter__ = Mock(return_value=(Mock(), None)) mo.__exit__ = Mock(return_value=None) with mo('file', 'r') as (fd, err): print(fd) print(err) mo.assert_called_once_with('file', 'r') # Should be True </code></pre>
1
2016-08-26T10:29:47Z
[ "python", "mocking" ]
Python HMAC hashed value encoding to base64
39,163,297
<p>I am trying to make a twitter auth with the help of django middleware, where I calculate the signature of a request like this (<a href="https://dev.twitter.com/oauth/overview/creating-signatures" rel="nofollow">https://dev.twitter.com/oauth/overview/creating-signatures</a>):</p> <pre><code> key = b"MY_KEY&amp;" raw_init = "POST" + "&amp;" + quote("https://api.twitter.com/1.1/oauth/request_token", safe='') raw_params = &lt;some_params&gt; raw_params = quote(raw_params, safe='') #byte encoding for HMAC, otherwise it returns "expected bytes or bytearray, but got 'str'" raw_final = bytes(raw_init + "&amp;" + raw_params, encoding='utf-8') hashed = hmac.new(key, raw_final, sha1) request.raw_final = hashed # here are my problems: I need a base64 encoded string, but get the error "'bytes' object has no attribute 'encode'" request.auth_header = hashed.digest().encode("base64").rstrip('\n') </code></pre> <p>As you can see, there is no way to base64 encode a 'bytes' object. </p> <p>The proposed solution was here: <a href="http://stackoverflow.com/questions/8338661/implementaion-hmac-sha1-in-python">Implementaion HMAC-SHA1 in python</a></p>
0
2016-08-26T09:43:40Z
39,165,115
<p>The trick is to use <code>base64</code> module directly instead of str/byte encoding, which supports binary.</p> <blockquote> <p>You can fit it like this (untested in your context, should work):</p> </blockquote> <pre><code>import base64 #byte encoding for HMAC, otherwise it returns "expected bytes or bytearray, but got 'str'" raw_final = bytes(raw_init + "&amp;" + raw_params, encoding='utf-8') hashed = hmac.new(key, raw_final, sha1) request.raw_final = hashed # here directly use base64 module, and since it returns bytes, just decode it request.auth_header = base64.b64encode(hashed.digest()).decode() </code></pre> <blockquote> <p>For test purposes, find below a standalone, working example (python 3 compatible, Python 2.x users have to remove the "ascii" parameter when creating the <code>bytes</code> string.):</p> </blockquote> <pre><code>from hashlib import sha1 import hmac import base64 # key = CONSUMER_SECRET&amp; #If you dont have a token yet key = bytes("CONSUMER_SECRET&amp;TOKEN_SECRET","ascii") # The Base String as specified here: raw = bytes("BASE_STRING","ascii") # as specified by oauth hashed = hmac.new(key, raw, sha1) print(base64.b64encode(hashed.digest()).decode()) </code></pre> <blockquote> <p>result:</p> </blockquote> <pre><code>Rh3xUffks487KzXXTc3n7+Hna6o= </code></pre> <p>PS: the answer your provided does not work anymore with Python 3. It's python 2 only.</p>
0
2016-08-26T11:20:30Z
[ "python", "django", "twitter", "base64", "hmacsha1" ]
How does one copy the users on protected ranges of Google Sheets with the REST API?
39,163,323
<p>I am trying to copy a Google sheet using an HTTP get request. The following is an excerpt from my code.</p> <pre><code> data = {"title": name_gdocs, "description": record_url, "parents": fields_dict['parents']} request_url = "https://www.googleapis.com/drive/v2/files/%s/copy?access_token=%s" % (template_id, access_token) headers = {'Content-type': 'application/json', 'Accept': 'text/plain'} data_json = json.dumps(data) req = urllib2.Request(request_url, data_json, headers) content = urllib2.urlopen(req, timeout=TIMEOUT).read() content = json.loads(content) </code></pre> <p>The sheet is coppied and so are the protected ranges from the sheet but the copied document's protected ranges are only able to be accessed by the owner as apposed to the original document's specified users.</p> <p>I can verify that the users that had access to the original document still have access in the new new one. They just lost access to the protected range.</p> <p>Is there some sort of flag I can use to make a deep copy or something of the like?</p> <p>Additionally, I would prefer doing it, only, with the drive API because I don't have access to the sheets API for this project. Otherwise I would just use that.</p>
1
2016-08-26T09:45:04Z
39,185,515
<p>The solution <em>is</em> to use the Sheets API. The Drive API does not have the functionality to duplicate the owners on the protected ranges. Keep in mind that I used the REST API but the same function calls should essentially be made with language specific libraries.</p> <h1>Making the copy</h1> <p>The url syntax, as specified in the <a href="https://developers.google.com/drive/v2/reference/files/copy" rel="nofollow">documentation</a> to make the copy is <code>POST https://www.googleapis.com/drive/v2/files/{fileId}/copy</code></p> <p>This can be called with something like:</p> <pre><code>data = {"title": name_of_doc, "description": short_description, "parents": list_of_parent_folders} # On absence of parents folder,the copy will be places in the root directory of the drive. data_json = json.dumps(data) request_url = "https://www.googleapis.com/drive/v2/files/%s/copy?access_token=%s" % (template_id, access_token) headers = {'Content-type': 'application/json', 'Accept': 'text/plain'} req = urllib2.Request(request_url, data_json, headers) content_json = urllib2.urlopen(req, timeout=TIMEOUT).read() content = json.loads(content_json) </code></pre> <h1>Getting the protected-range owners</h1> <p>The <a href="https://developers.google.com/sheets/reference/rest/v4/spreadsheets/get" rel="nofollow">documentation</a> says that the request needs to use the GET method as follows <code>GET https://sheets.googleapis.com/v4/spreadsheets/{spreadsheetId}</code></p> <p>Note: The function <code>update_protected_range_to_google_sheet</code> will be defined later on</p> <pre><code>if content.get('id') and content.get('mimeType','') == 'application/vnd.google-apps.spreadsheet': # Make sure that the document is a Google Sheet request_url = "https://sheets.googleapis.com/v4/spreadsheets/%s?access_token=%s" % (template_id, access_token) s_req = urllib2.Request(request_url, None, headers) s_content = urllib2.urlopen(s_req, timeout=TIMEOUT).read() s_content = json.loads(s_content) for sheet in s_content.get('sheets', []): for pr in sheet.get('protectedRanges', []): update_protected_range_to_google_sheet(access_token, content.get('id'), pr) </code></pre> <h1>Applying the owners</h1> <p>The <a href="https://developers.google.com/sheets/samples/ranges" rel="nofollow">documentation</a> says to use the batch update call to the Sheets API as the name suggests, many requests can be done at once but in this case, the function will be called once per update for illustrative purposes. Here is the function I used that will be called:</p> <pre><code>def update_protected_range_to_google_sheet(self,access_token, sheet_id,range_info): headers = {'Content-type': 'application/json', 'Accept': 'text/plain'} request_url = "https://sheets.googleapis.com/v4/spreadsheets/%s:batchUpdate?access_token=%s" % (sheet_id, access_token) data = { "requests": [ { "updateProtectedRange": { "protectedRange": range_info, "fields": "namedRangeId,warningOnly,editors" } } ] } data_json = json.dumps(data) req = urllib2.Request(request_url, data_json, headers) content_json = urllib2.urlopen(req, timeout=TIMEOUT).read() content = json.loads(content_json) </code></pre> <h1>Conclusion</h1> <p>The main reason I couldn't use the Sheets API was that the system I was using, had a custom built wrapper around the Drive API and the authentication was hardcoded to point to a project owned by the library's creator.</p> <p>This wouldn't do, so I created my own project on the <a href="https://console.cloud.google.com/" rel="nofollow">console</a> and generated a token from that. The new project had the Drive API enabled <em>as well</em> as the Sheets API - something the original project apparently didn't have.</p>
0
2016-08-27T20:34:20Z
[ "python", "http", "google-drive-sdk" ]
Scraping a website that requires authentication
39,163,352
<p>I know this question might seem quite straight forward, but I have tried every suggestion and none has worked.</p> <p>I want to build a Python script that checks my school website to see if new grades have been put up. However I cannot for the life of me figure out how to scrape it.</p> <p>The website redirects to a different page to login. I have tried all the scripts and answers I could find but I am lost.</p> <p>I use Python 3, the website is in a <code>https://blah.schooldomate.state.edu.country/website/grades/summary.aspx</code> format</p> <p>The username section contains the following:</p> <p><code>&lt;input class="txt" id="username" name="username" type="text" autocomplete="off" style="cursor: auto;"&gt;</code></p> <p>The password is the name except it contains an <code>onfocus</code> HTML element.</p> <p>One successfully authenticated, I am automatically redirected to the correct page.</p> <p>I have tried:</p> <p>using Python 2's cookielib and Mechanize</p> <p>Using HTTPBasicAuth</p> <p>Passing the information as a dict to a requests.get()</p> <p>Trying out many different peoples code including answers I found on this site</p>
0
2016-08-26T09:46:47Z
39,164,406
<p>You can try with requests: <a href="http://docs.python-requests.org/en/master/" rel="nofollow">http://docs.python-requests.org/en/master/</a></p> <p>from the web site:</p> <pre><code>import requests r = requests.get('https://api.github.com/user', auth=('user', 'pass')) </code></pre>
0
2016-08-26T10:43:33Z
[ "python" ]
Scraping a website that requires authentication
39,163,352
<p>I know this question might seem quite straight forward, but I have tried every suggestion and none has worked.</p> <p>I want to build a Python script that checks my school website to see if new grades have been put up. However I cannot for the life of me figure out how to scrape it.</p> <p>The website redirects to a different page to login. I have tried all the scripts and answers I could find but I am lost.</p> <p>I use Python 3, the website is in a <code>https://blah.schooldomate.state.edu.country/website/grades/summary.aspx</code> format</p> <p>The username section contains the following:</p> <p><code>&lt;input class="txt" id="username" name="username" type="text" autocomplete="off" style="cursor: auto;"&gt;</code></p> <p>The password is the name except it contains an <code>onfocus</code> HTML element.</p> <p>One successfully authenticated, I am automatically redirected to the correct page.</p> <p>I have tried:</p> <p>using Python 2's cookielib and Mechanize</p> <p>Using HTTPBasicAuth</p> <p>Passing the information as a dict to a requests.get()</p> <p>Trying out many different peoples code including answers I found on this site</p>
0
2016-08-26T09:46:47Z
39,166,053
<p>Maybe you can use Selenium library.</p> <p>I let you my code example:</p> <pre><code>from selenium import webdriver def loging(): browser = webdriver.Firefox() browser.get("www.your_url.com") #Edit the XPATH of Loging INPUT username xpath_username = "//input[@class='username']" #Edit the XPATH of Loging INPUT password xpath_password = "//input[@class='password']" #THIS will write the YOUR_USERNAME/pass in the xpath (Custom function) click_xpath(browser, xpath_username, "YOUR_USERNAME") click_xpath(browser, xpath_username, "YOUR_PASSWORD") #THEN SCRAPE WHAT YOU NEED #Here is the custom function #If NO input, will only click on the element (on a button for example) def click_xpath(self, browser, xpath, input="", time_wait=10): try: browser.implicitly_wait(time_wait) wait = WebDriverWait(browser, time_wait) search = wait.until(EC.element_to_be_clickable((By.XPATH, xpath))) search.click() sleep(1) #Write in the element if input: search.send_keys(str(input) + Keys.RETURN) return search except Exception as e: #print("ERROR-click_xpath: "+xpath) return False </code></pre>
0
2016-08-26T12:12:16Z
[ "python" ]
Evaluating Logistic regression with cross validation
39,163,354
<p>I would like to use cross validation to test/train my dataset and evaluate the performance of the logistic regression model on the entire dataset and not only on the test set (e.g. 25%). </p> <p>These concepts are totally new to me and am not very sure if am doing it right. I would be grateful if anyone could advise me on the right steps to take where I have gone wrong. Part of my code is shown below.</p> <p>Also, how can I plot ROCs for "y2" and "y3" on the same graph with the current one?</p> <p>Thank you</p> <pre><code>import pandas as pd Data=pd.read_csv ('C:\\Dataset.csv',index_col='SNo') feature_cols=['A','B','C','D','E'] X=Data[feature_cols] Y=Data['Status'] Y1=Data['Status1'] # predictions from elsewhere Y2=Data['Status2'] # predictions from elsewhere from sklearn.linear_model import LogisticRegression logreg=LogisticRegression() logreg.fit(X_train,y_train) from sklearn.cross_validation import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0) from sklearn import metrics, cross_validation predicted = cross_validation.cross_val_predict(logreg, X, y, cv=10) metrics.accuracy_score(y, predicted) from sklearn.cross_validation import cross_val_score accuracy = cross_val_score(logreg, X, y, cv=10,scoring='accuracy') print (accuracy) print (cross_val_score(logreg, X, y, cv=10,scoring='accuracy').mean()) from nltk import ConfusionMatrix print (ConfusionMatrix(list(y), list(predicted))) #print (ConfusionMatrix(list(y), list(yexpert))) # sensitivity: print (metrics.recall_score(y, predicted) ) import matplotlib.pyplot as plt probs = logreg.predict_proba(X)[:, 1] plt.hist(probs) plt.show() # use 0.5 cutoff for predicting 'default' import numpy as np preds = np.where(probs &gt; 0.5, 1, 0) print (ConfusionMatrix(list(y), list(preds))) # check accuracy, sensitivity, specificity print (metrics.accuracy_score(y, predicted)) #ROC CURVES and AUC # plot ROC curve fpr, tpr, thresholds = metrics.roc_curve(y, probs) plt.plot(fpr, tpr) plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.0]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate)') plt.show() # calculate AUC print (metrics.roc_auc_score(y, probs)) # use AUC as evaluation metric for cross-validation from sklearn.cross_validation import cross_val_score logreg = LogisticRegression() cross_val_score(logreg, X, y, cv=10, scoring='roc_auc').mean() </code></pre>
1
2016-08-26T09:46:52Z
39,169,661
<p>You got it almost right. <code>cross_validation.cross_val_predict</code> gives you predictions for the entire dataset. You just need to remove <code>logreg.fit</code> earlier in the code. Specifically, what it does is the following: It divides your dataset in to <code>n</code> folds and in each iteration it leaves one of the folds out as the test set and trains the model on the rest of the folds (<code>n-1</code> folds). So, in the end you will get predictions for the entire data. </p> <p>Let's illustrate this with one of the built-in datasets in sklearn, iris. This dataset contains 150 training samples with 4 features. <code>iris['data']</code> is <code>X</code> and <code>iris['target']</code> is <code>y</code></p> <pre><code>In [15]: iris['data'].shape Out[15]: (150, 4) </code></pre> <p>To get predictions on the entire set with cross validation you can do the following:</p> <pre><code>from sklearn.linear_model import LogisticRegression from sklearn import metrics, cross_validation from sklearn import datasets iris = datasets.load_iris() predicted = cross_validation.cross_val_predict(LogisticRegression(), iris['data'], iris['target'], cv=10) print metrics.accuracy_score(iris['target'], predicted) Out [1] : 0.9537 print metrics.classification_report(iris['target'], predicted) Out [2] : precision recall f1-score support 0 1.00 1.00 1.00 50 1 0.96 0.90 0.93 50 2 0.91 0.96 0.93 50 avg / total 0.95 0.95 0.95 150 </code></pre> <p>So, back to your code. All you need is this:</p> <pre><code>from sklearn import metrics, cross_validation logreg=LogisticRegression() predicted = cross_validation.cross_val_predict(logreg, X, y, cv=10) print metrics.accuracy_score(y, predicted) print metrics.classification_report(y, predicted) </code></pre> <p>For plotting ROC in multi-class classification, you can follow <a href="http://scikit-learn.org/stable/auto_examples/model_selection/plot_roc.html" rel="nofollow">this tutorial</a> which gives you something like the following:</p> <p><img src="http://i.stack.imgur.com/o2RR9.png" width="300" height="300"></p> <p>In general, sklearn has very good tutorials and documentation. I strongly recommend reading their <a href="http://scikit-learn.org/stable/modules/cross_validation.html#cross-validation" rel="nofollow">tutorial on cross_validation</a>.</p>
1
2016-08-26T15:22:20Z
[ "python", "scikit-learn", "logistic-regression", "cross-validation" ]
Django Rest Framework upload multiply images at once with serializer
39,163,363
<p>I had some research on web for this problem on DRF. When one image is in post DRF works great. But when 3 or 5 images are in one post there is problem that Django save only first image from POST query and others are not saved in database. The question is how to properly handle multiply images upload in one post.</p> <h1>Description</h1> <blockquote> <p>Django version</p> </blockquote> <ul> <li>1.10</li> </ul> <blockquote> <p>Rest framework version</p> </blockquote> <ul> <li>3.4.6</li> </ul> <blockquote> <p>Python version</p> </blockquote> <ul> <li>3.5</li> </ul> <p>Here is my code what I was trying to do:</p> <h1>models</h1> <pre><code>class UserModel(AbstractEmailUser): first_name = models.CharField(max_length=30, db_index=True) last_name = models.CharField(max_length=50, db_index=True) details = JSONField(null=True, blank=True, db_index=True) avatar = models.ImageField(blank=True, null=True, upload_to='avatar') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return str(self.email) class UserImages(models.Model): image = models.ImageField(upload_to='images', db_index=True) user = models.ForeignKey('UserModel',related_name='user') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return str(self.user) </code></pre> <p>Here in models I have related field from User to UserImages. For purpose on POST query from postman I manual add ID from user to handle FK.</p> <h1>serializer</h1> <pre><code>class SerializerUserImages(serializers.ModelSerializer): class Meta: model = UserImages def create(self, validated_data): imgs = UserImages.objects.create(**validated_data) return imgs </code></pre> <p>Maybe here I must do some for loop to accomplish save method for multiply images.</p> <h1>views</h1> <pre><code>class UploadImages(APIView): authentication_classes = (JSONWebTokenAuthentication,) @parser_classes((FormParser, MultiPartParser, FileUploadParser)) def post(self, request, format=None): serializer = SerializerUserImages(data=request.data) if serializer.is_valid(): serializer.save() return Response(data={"msg": serializer.data}, status=status.HTTP_200_OK) else: return Response(data={"msg": serializer.errors}, status=status.HTTP_406_NOT_ACCEPTABLE) </code></pre> <p>All parsers are included for handling this post query.</p> <p>This is output from <strong>request.data</strong> = <code>&lt;QueryDict: {'image': [&lt;InMemoryUploadedFile: top_20_cro.png (image/png)&gt;, &lt;InMemoryUploadedFile: images.jpg (image/jpeg)&gt;], 'user': ['2', '2']}&gt;</code></p> <p>This is copy of request POST from POSTMAN:</p> <pre><code>POST /api/images/ HTTP/1.1 Host: 127.0.0.1:8000 Authorization: JWT eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJvcmlnX2lhdCI6MTQ3MjIwMTcwMSwiZXhwIjoxNDcyMjMxNzAxLCJ1c2VyX2lkIjoyLCJlbWFpbCI6Im1hcmluLmJyZWthbG9AZ21haWwuY29tIiwidXNlcm5hbWUiOiJtYXJpbi5icmVrYWxvQGdtYWlsLmNvbSJ9.Fi3kmXJ44E_qhHHioniQ-cqri-u2ELU-XmpE_1oJ4Fk Cache-Control: no-cache Postman-Token: 1e53ac06-ed37-ff6e-2dc5-117976b86a5e Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW ------WebKitFormBoundary7MA4YWxkTrZu0gW Content-Disposition: form-data; name="image"; filename="" Content-Type: ------WebKitFormBoundary7MA4YWxkTrZu0gW Content-Disposition: form-data; name="user" 2 ------WebKitFormBoundary7MA4YWxkTrZu0gW Content-Disposition: form-data; name="filename" image ------WebKitFormBoundary7MA4YWxkTrZu0gW Content-Disposition: form-data; name="user" 2 ------WebKitFormBoundary7MA4YWxkTrZu0gW Content-Disposition: form-data; name="filename" image ------WebKitFormBoundary7MA4YWxkTrZu0gW Content-Disposition: form-data; name="image"; filename="" Content-Type: ------WebKitFormBoundary7MA4YWxkTrZu0gW-- </code></pre> <p>How can this be handled without some great magic, is there some easy logic that I missed up.</p>
0
2016-08-26T09:47:29Z
39,163,492
<p>Try setting filenames for your images, I mean replace <code>filename=""</code> with something like <code>filename="image-1"</code>, <code>filename="image-2"</code>, etc. Files should have different filenames or they override each other.</p>
0
2016-08-26T09:54:52Z
[ "python", "django", "image", "rest", "file-upload" ]
Django Rest Framework upload multiply images at once with serializer
39,163,363
<p>I had some research on web for this problem on DRF. When one image is in post DRF works great. But when 3 or 5 images are in one post there is problem that Django save only first image from POST query and others are not saved in database. The question is how to properly handle multiply images upload in one post.</p> <h1>Description</h1> <blockquote> <p>Django version</p> </blockquote> <ul> <li>1.10</li> </ul> <blockquote> <p>Rest framework version</p> </blockquote> <ul> <li>3.4.6</li> </ul> <blockquote> <p>Python version</p> </blockquote> <ul> <li>3.5</li> </ul> <p>Here is my code what I was trying to do:</p> <h1>models</h1> <pre><code>class UserModel(AbstractEmailUser): first_name = models.CharField(max_length=30, db_index=True) last_name = models.CharField(max_length=50, db_index=True) details = JSONField(null=True, blank=True, db_index=True) avatar = models.ImageField(blank=True, null=True, upload_to='avatar') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return str(self.email) class UserImages(models.Model): image = models.ImageField(upload_to='images', db_index=True) user = models.ForeignKey('UserModel',related_name='user') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return str(self.user) </code></pre> <p>Here in models I have related field from User to UserImages. For purpose on POST query from postman I manual add ID from user to handle FK.</p> <h1>serializer</h1> <pre><code>class SerializerUserImages(serializers.ModelSerializer): class Meta: model = UserImages def create(self, validated_data): imgs = UserImages.objects.create(**validated_data) return imgs </code></pre> <p>Maybe here I must do some for loop to accomplish save method for multiply images.</p> <h1>views</h1> <pre><code>class UploadImages(APIView): authentication_classes = (JSONWebTokenAuthentication,) @parser_classes((FormParser, MultiPartParser, FileUploadParser)) def post(self, request, format=None): serializer = SerializerUserImages(data=request.data) if serializer.is_valid(): serializer.save() return Response(data={"msg": serializer.data}, status=status.HTTP_200_OK) else: return Response(data={"msg": serializer.errors}, status=status.HTTP_406_NOT_ACCEPTABLE) </code></pre> <p>All parsers are included for handling this post query.</p> <p>This is output from <strong>request.data</strong> = <code>&lt;QueryDict: {'image': [&lt;InMemoryUploadedFile: top_20_cro.png (image/png)&gt;, &lt;InMemoryUploadedFile: images.jpg (image/jpeg)&gt;], 'user': ['2', '2']}&gt;</code></p> <p>This is copy of request POST from POSTMAN:</p> <pre><code>POST /api/images/ HTTP/1.1 Host: 127.0.0.1:8000 Authorization: JWT eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJvcmlnX2lhdCI6MTQ3MjIwMTcwMSwiZXhwIjoxNDcyMjMxNzAxLCJ1c2VyX2lkIjoyLCJlbWFpbCI6Im1hcmluLmJyZWthbG9AZ21haWwuY29tIiwidXNlcm5hbWUiOiJtYXJpbi5icmVrYWxvQGdtYWlsLmNvbSJ9.Fi3kmXJ44E_qhHHioniQ-cqri-u2ELU-XmpE_1oJ4Fk Cache-Control: no-cache Postman-Token: 1e53ac06-ed37-ff6e-2dc5-117976b86a5e Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW ------WebKitFormBoundary7MA4YWxkTrZu0gW Content-Disposition: form-data; name="image"; filename="" Content-Type: ------WebKitFormBoundary7MA4YWxkTrZu0gW Content-Disposition: form-data; name="user" 2 ------WebKitFormBoundary7MA4YWxkTrZu0gW Content-Disposition: form-data; name="filename" image ------WebKitFormBoundary7MA4YWxkTrZu0gW Content-Disposition: form-data; name="user" 2 ------WebKitFormBoundary7MA4YWxkTrZu0gW Content-Disposition: form-data; name="filename" image ------WebKitFormBoundary7MA4YWxkTrZu0gW Content-Disposition: form-data; name="image"; filename="" Content-Type: ------WebKitFormBoundary7MA4YWxkTrZu0gW-- </code></pre> <p>How can this be handled without some great magic, is there some easy logic that I missed up.</p>
0
2016-08-26T09:47:29Z
39,163,493
<p>Simply add</p> <pre><code>many=True </code></pre> <p>with the serializer initializer. For eg.:</p> <pre><code>serializer = SerializerUserImages(data=request.data, many=True) </code></pre> <p>This should do the trick. </p> <p>Also have a look at <a href="http://www.django-rest-framework.org/api-guide/serializers/#listserializer" rel="nofollow">ListSerializers</a></p>
0
2016-08-26T09:54:55Z
[ "python", "django", "image", "rest", "file-upload" ]
Django Rest Framework upload multiply images at once with serializer
39,163,363
<p>I had some research on web for this problem on DRF. When one image is in post DRF works great. But when 3 or 5 images are in one post there is problem that Django save only first image from POST query and others are not saved in database. The question is how to properly handle multiply images upload in one post.</p> <h1>Description</h1> <blockquote> <p>Django version</p> </blockquote> <ul> <li>1.10</li> </ul> <blockquote> <p>Rest framework version</p> </blockquote> <ul> <li>3.4.6</li> </ul> <blockquote> <p>Python version</p> </blockquote> <ul> <li>3.5</li> </ul> <p>Here is my code what I was trying to do:</p> <h1>models</h1> <pre><code>class UserModel(AbstractEmailUser): first_name = models.CharField(max_length=30, db_index=True) last_name = models.CharField(max_length=50, db_index=True) details = JSONField(null=True, blank=True, db_index=True) avatar = models.ImageField(blank=True, null=True, upload_to='avatar') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return str(self.email) class UserImages(models.Model): image = models.ImageField(upload_to='images', db_index=True) user = models.ForeignKey('UserModel',related_name='user') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return str(self.user) </code></pre> <p>Here in models I have related field from User to UserImages. For purpose on POST query from postman I manual add ID from user to handle FK.</p> <h1>serializer</h1> <pre><code>class SerializerUserImages(serializers.ModelSerializer): class Meta: model = UserImages def create(self, validated_data): imgs = UserImages.objects.create(**validated_data) return imgs </code></pre> <p>Maybe here I must do some for loop to accomplish save method for multiply images.</p> <h1>views</h1> <pre><code>class UploadImages(APIView): authentication_classes = (JSONWebTokenAuthentication,) @parser_classes((FormParser, MultiPartParser, FileUploadParser)) def post(self, request, format=None): serializer = SerializerUserImages(data=request.data) if serializer.is_valid(): serializer.save() return Response(data={"msg": serializer.data}, status=status.HTTP_200_OK) else: return Response(data={"msg": serializer.errors}, status=status.HTTP_406_NOT_ACCEPTABLE) </code></pre> <p>All parsers are included for handling this post query.</p> <p>This is output from <strong>request.data</strong> = <code>&lt;QueryDict: {'image': [&lt;InMemoryUploadedFile: top_20_cro.png (image/png)&gt;, &lt;InMemoryUploadedFile: images.jpg (image/jpeg)&gt;], 'user': ['2', '2']}&gt;</code></p> <p>This is copy of request POST from POSTMAN:</p> <pre><code>POST /api/images/ HTTP/1.1 Host: 127.0.0.1:8000 Authorization: JWT eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJvcmlnX2lhdCI6MTQ3MjIwMTcwMSwiZXhwIjoxNDcyMjMxNzAxLCJ1c2VyX2lkIjoyLCJlbWFpbCI6Im1hcmluLmJyZWthbG9AZ21haWwuY29tIiwidXNlcm5hbWUiOiJtYXJpbi5icmVrYWxvQGdtYWlsLmNvbSJ9.Fi3kmXJ44E_qhHHioniQ-cqri-u2ELU-XmpE_1oJ4Fk Cache-Control: no-cache Postman-Token: 1e53ac06-ed37-ff6e-2dc5-117976b86a5e Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW ------WebKitFormBoundary7MA4YWxkTrZu0gW Content-Disposition: form-data; name="image"; filename="" Content-Type: ------WebKitFormBoundary7MA4YWxkTrZu0gW Content-Disposition: form-data; name="user" 2 ------WebKitFormBoundary7MA4YWxkTrZu0gW Content-Disposition: form-data; name="filename" image ------WebKitFormBoundary7MA4YWxkTrZu0gW Content-Disposition: form-data; name="user" 2 ------WebKitFormBoundary7MA4YWxkTrZu0gW Content-Disposition: form-data; name="filename" image ------WebKitFormBoundary7MA4YWxkTrZu0gW Content-Disposition: form-data; name="image"; filename="" Content-Type: ------WebKitFormBoundary7MA4YWxkTrZu0gW-- </code></pre> <p>How can this be handled without some great magic, is there some easy logic that I missed up.</p>
0
2016-08-26T09:47:29Z
39,166,607
<p>Ok here is my some logic about this problem, so I hope someone will use this code (hack) for this purpose:</p> <h1>Serializer change</h1> <pre><code>class SerializerTest(serializers.Serializer): image = serializers.ListField(child=serializers.ImageField(required=True)) def create(self, validated_data): for attr, value in validated_data.items(): if attr == 'image': for x in value: c = UserImages.objects.create(image=x, user_id=UserModel.objects.get(id=self.context['request'].user.id).id) c.save() return validated_data </code></pre> <p>I have updated my serialzer for just one field <strong>img</strong>. And use for loop to extract images from POST. As you can see i call query to store images to database on FK user. This work's very good.</p> <h1>Views</h1> <pre><code>class UploadImages(APIView): authentication_classes = (JSONWebTokenAuthentication,) @parser_classes((FormParser, MultiPartParser, FileUploadParser)) def post(self, request, format=None): serializer = SerializerTest(data=request.data, context={'request':request}) if serializer.is_valid(): serializer.save() if len(serializer.data['image']) &gt; 0: que = UserImages.objects.filter(user=request.user.id) ser = SerializerUserImages(que, many=True) return Response(data={"msg": ser.data}, status=status.HTTP_200_OK) else: return Response(data={"msg": 'Provide images!'}, status=status.HTTP_406_NOT_ACCEPTABLE) else: return Response(data={"msg": serializer.errors}, status=status.HTTP_406_NOT_ACCEPTABLE) </code></pre>
0
2016-08-26T12:41:01Z
[ "python", "django", "image", "rest", "file-upload" ]
Is thre a better way to build it so it print all attributes from class/parent-class
39,163,495
<p>I have a <code>Student</code> class extending <code>Person</code> class, both class implemented <code>__str__</code> to list out all attributes in both <code>Person</code> and <code>Student</code> class. </p> <p>However, I am having issues with trying to do a print of <code>__str__</code> in the <code>__init__</code> function as below. </p> <pre><code>class Person(object): def __init__(self, n): self.name = n print Person.__str__(self) def __str__(self): return "%15s%s\n" % ("Name: ", self.name) class Student(Person): def __init__(self, n, sid, d): Person.__init__(self,n) self.sid = sid self.degree = d print Student.__str__(self) def __str__(self): return Person.__str__(self) + "%15s%s\n%15s%s\n" % ("StudentID: ", self.sid, "Degree: ", self.degree) </code></pre> <p>When I execute the following</p> <pre><code>Jeff = Person("Jeff") Cameron = Student('Cameron', 'U2314313', "Social Science") </code></pre> <p>it would produce something like:</p> <pre><code>Name: Jeff Name: Cameron Name: Cameron StudentID:...... Degree:...... </code></pre> <p>When initializing <code>Student</code>, it's calling <code>Student.__str__(self)</code>, and subsequently call <code>Person.__str__(self)</code> in order to bring back the name. </p> <p>Just wondering if there's a better way to build the the structure so it's more usable and inline with the OO concept. </p> <p>The result that I want is when I do the <code>__str__</code> for both <code>Student</code> or <code>Person</code>, it would list out all attributes, such as:</p> <pre><code>Name: Jeff Name: Cameron StudentID:...... Degree:...... </code></pre> <p>and when I do something like <code>print Cameron</code>, it would still give me </p> <pre><code>Name: Cameron StudentID:...... Degree:...... </code></pre> <p>I know my code is duplicating it at the moment, but I can't figure out a way to make it work the way I intended... Help please. </p>
2
2016-08-26T09:54:58Z
39,163,560
<p>Yes there is. Use <a href="https://docs.python.org/3.5/library/functions.html#super" rel="nofollow"><code>super</code></a> which calls "parent's" function realization. I'm quoting parent because it is little different than in other programming languages. There is awesome presentation by Raymond Hettinger on Pycon 2015 <a href="https://www.youtube.com/watch?v=EiOglTERPEo" rel="nofollow">https://www.youtube.com/watch?v=EiOglTERPEo</a>.</p> <pre><code>class Person(object): def __init__(self, n): self.name = n print self.__str__() def __str__(self): return "%15s%s\n" % ("Name: ", self.name) class Student(Person): def __init__(self, n, sid, d): Person.__init__(self,n) self.sid = sid self.degree = d print self.__str__() def __str__(self): return super().__str__() + "%15s%s\n%15s%s\n" % ("StudentID: ", self.sid, "Degree: ", self.degree) </code></pre> <p>Here as you see when we need to call method of current class we just do <code>self.method()</code>, but if we need to call parent method we do <code>super().method()</code></p> <p>And i would suggest using <a href="https://docs.python.org/3.5/library/stdtypes.html#str.format" rel="nofollow"><code>format</code></a> for string formating because it is more clear and readable.</p> <pre><code>class Person(object): def __init__(self, n): self.name = n print self.__str__() def __str__(self): return "Name: {}\n".format(self.name) class Student(Person): def __init__(self, n, sid, d): Person.__init__(self,n) self.sid = sid self.degree = d print self.__str__() def __str__(self): return super().__str__() + "StudentID: {}\nDegree: {}\n".format(self.sid, self.degree) </code></pre>
1
2016-08-26T09:58:12Z
[ "python", "class", "oop", "initialization" ]
Is thre a better way to build it so it print all attributes from class/parent-class
39,163,495
<p>I have a <code>Student</code> class extending <code>Person</code> class, both class implemented <code>__str__</code> to list out all attributes in both <code>Person</code> and <code>Student</code> class. </p> <p>However, I am having issues with trying to do a print of <code>__str__</code> in the <code>__init__</code> function as below. </p> <pre><code>class Person(object): def __init__(self, n): self.name = n print Person.__str__(self) def __str__(self): return "%15s%s\n" % ("Name: ", self.name) class Student(Person): def __init__(self, n, sid, d): Person.__init__(self,n) self.sid = sid self.degree = d print Student.__str__(self) def __str__(self): return Person.__str__(self) + "%15s%s\n%15s%s\n" % ("StudentID: ", self.sid, "Degree: ", self.degree) </code></pre> <p>When I execute the following</p> <pre><code>Jeff = Person("Jeff") Cameron = Student('Cameron', 'U2314313', "Social Science") </code></pre> <p>it would produce something like:</p> <pre><code>Name: Jeff Name: Cameron Name: Cameron StudentID:...... Degree:...... </code></pre> <p>When initializing <code>Student</code>, it's calling <code>Student.__str__(self)</code>, and subsequently call <code>Person.__str__(self)</code> in order to bring back the name. </p> <p>Just wondering if there's a better way to build the the structure so it's more usable and inline with the OO concept. </p> <p>The result that I want is when I do the <code>__str__</code> for both <code>Student</code> or <code>Person</code>, it would list out all attributes, such as:</p> <pre><code>Name: Jeff Name: Cameron StudentID:...... Degree:...... </code></pre> <p>and when I do something like <code>print Cameron</code>, it would still give me </p> <pre><code>Name: Cameron StudentID:...... Degree:...... </code></pre> <p>I know my code is duplicating it at the moment, but I can't figure out a way to make it work the way I intended... Help please. </p>
2
2016-08-26T09:54:58Z
39,163,565
<p>You may use the <code>getmembers</code> function of <a href="https://docs.python.org/3/library/inspect.html#inspect.getmembers" rel="nofollow"><code>inspect</code></a> module to get the all the members of the class dynamically. </p> <p>Generic function to <code>return</code> attributes based on passed <code>class</code> or <code>class's object</code> can be define as:</p> <pre><code>import inspect def get_attributes(class_object): attributes = inspect.getmembers(class_object, lambda a:not(inspect.isroutine(a))) return [a for a in attributes if not(a[0].startswith('__') and a[0].endswith('__'))] </code></pre> <p>Now the demonstration, on HOW this will work:</p> <pre><code># Parent class class MyClass(object): a = '12' b = '34' # Child class class MyChildClass(MyClass): c = '20' def __init__(self): self.x = 20 get_attributes(MyClass) &lt;-- Parent Class # returns: [('a', '12'), ('b', '34')] # Return all the class attributes of "MyClass" get_attributes(MyChildClass) &lt;-- Child Class # returns: [('a', '12'), ('b', '34'), ('c', '20')] # Returns all the class attributes of "MyChildClass" get_attributes(MyChildClass()) &lt;-- Object Of Child Class # returns: [('a', '12'), ('b', '34'), ('c', '20'), ('x', 20)] # Returns all the class + object attributes of "MyChildClass's object" </code></pre>
0
2016-08-26T09:58:37Z
[ "python", "class", "oop", "initialization" ]
Pyephem calculate current solar time
39,163,549
<p>I am trying to calculate the local solar time based on UTC hour and longitude. I have looked through the <code>ephem</code> package but was not able to identify a direct method to do so. Similar questions on this matter either evoke the calculation of fixed positions (sunrise, moon, sunset) (e.g. <a href="http://stackoverflow.com/questions/2637293/calculating-dawn-and-sunset-times-using-pyephem">Calculating dawn and sunset times using PyEphem</a>) or receive suggestions of simplified methods (e.g. <a href="http://stackoverflow.com/questions/13314626/local-solar-time-function-from-utc-and-longitude">Local solar time function from UTC and longitude</a>). Is there any alternative to the aforementioned solutions?</p> <p>Thanks in advance</p>
1
2016-08-26T09:57:46Z
39,184,871
<p>To compute local solar time, I think that you can just ask for the current right ascension of the point directly beneath the location (its nadir point), and subtract the right ascension of the Sun to learn exactly how far from local midnight it is: </p> <pre><code>from ephem import Sun, Observer, pi, hours dt = '2016/08/27 19:19' sun = Sun() sun.compute(dt) boston = Observer() boston.lat = '42.37' boston.lon = '-71.03' boston.date = dt ra, dec = boston.radec_of('0', '-90') print 'Sun right ascension:', sun.ra print 'Boston nadir right ascension:', ra print 'Solar time:', hours((ra - sun.ra) % (2 * pi)), 'hours' </code></pre> <p>Could you try out this approach and see whether it gives the numbers you expect to reasonable precision?</p>
0
2016-08-27T19:21:40Z
[ "python", "pyephem" ]
How to append elements to a list by using reduceByKey in pyspark
39,163,703
<p>I'm kind of stuck trying to solve a problem in pyspark. After do same calculations by using map function, I have a RDD that contains a list of dicts in this way:</p> <pre><code>[{key1: tuple1}, {key1: tuple2}....{key2: tuple1}, {keyN: tupleN}] </code></pre> <p>I pretend to append for each key a list with all the tuples with the same key, obtaining something like:</p> <pre><code>[{key1: [tuple1, tuple2, tuple3...]}, {key2: [tuple1, tuple2....]}] </code></pre> <p>I think an example it's more illustrative:</p> <pre><code>[{0: (0, 1.0)}, {0: (1, 0.0)}, {1: (0, 0.0)}, {1: (1, 1.0)}, {2:(0,0.0)}... ] </code></pre> <p>And I would like to obtain list of dicts like this:</p> <pre><code>[{0: [(0, 1.0), (1, 0.0)}, {1: [(0, 0.0), (1, 1.0)]}, {2:[(0,0.0),...]},...] </code></pre> <p>I'm trying to avoid using "combineByKey" function because it lasts too much time, there is any possibility to do that with "reduceByKey"?? </p> <p>Thanks you all very much.</p>
0
2016-08-26T10:06:17Z
39,163,839
<p>Here's a possible solution without using reduceByKey but just python builtin functions:</p> <pre><code>from collections import defaultdict inp = [{0: (0, 1.0)}, {0: (1, 0.0)}, {1: (0, 0.0)}, {1: (1, 1.0)}, {2: (0, 0.0)}] out = defaultdict(list) for v in inp: for k, v1 in v.iteritems(): out[k].append(v1) out = [{k: v} for k, v in out.iteritems()] print out </code></pre>
0
2016-08-26T10:13:23Z
[ "python", "append", "pyspark", "rdd", "reduce" ]
How to get rows affected in a UPDATE statement by PyMSQL
39,163,776
<p>See the title,I need to update some rows on mysql database by PyMYSQL and I want to know <strong>how many rows had been changed.</strong></p> <p>code: <code> import pymysql db = pymysql.connect(xxxx) cur = db.cursor() sql = "update TABLE set A = 'abc' where B = 'def'" cur.execute(sql, params) db.commit() </code></p>
0
2016-08-26T10:10:03Z
39,163,989
<p>Mysql provides a special call that will help you achieve exactly that: <code>mysql-affected-rows</code>. This function is especially useful on updates as it will return only the number of rows that were affected, not the ones where the updated value was similar. Documentation is <a href="https://dev.mysql.com/doc/refman/5.6/en/mysql-affected-rows.html" rel="nofollow">here</a>.</p> <p>How to use this in Python? The <a href="http://mysql-python.sourceforge.net/MySQLdb-1.2.2/public/MySQLdb.cursors.BaseCursor-class.html#execute" rel="nofollow">return</a> of <code>execute</code> command will return you exactly this.</p> <pre><code>affected_rows = cur.execute(sql, params) </code></pre>
1
2016-08-26T10:20:51Z
[ "python", "mysql", "pymysql" ]
How to get rows affected in a UPDATE statement by PyMSQL
39,163,776
<p>See the title,I need to update some rows on mysql database by PyMYSQL and I want to know <strong>how many rows had been changed.</strong></p> <p>code: <code> import pymysql db = pymysql.connect(xxxx) cur = db.cursor() sql = "update TABLE set A = 'abc' where B = 'def'" cur.execute(sql, params) db.commit() </code></p>
0
2016-08-26T10:10:03Z
39,164,309
<p>You can do this by <code>cursor.rowcount</code> after executing stage. Ff return value of this is opposite of 0 it means one or more rows are affected.</p>
0
2016-08-26T10:38:57Z
[ "python", "mysql", "pymysql" ]
How to insert huge CSV file at once into SQL Server in python?
39,163,849
<p>I have a large CSV file and I want to insert it all at once, instead of row by row. This is my code:</p> <pre><code>import pypyodbc import csv con = pypyodbc.connect('driver={SQL Server};' 'server=server_name;' 'database=DB-name;' 'trusted_connection=true') cur = con.cursor() csfile = open('out2.csv','r') csv_data = csv.reader(csfile) for row in csv_data: try: cur.execute("BULK INSERT INTO Table_name(Attribute, error, msg, Value, Success, TotalCount, SerialNo)" "VALUES (?, ?, ?, ?, ?, ?, ?)", row) except Exception: time.sleep(60) cur.close() con.commit() con.close() </code></pre>
1
2016-08-26T10:14:05Z
39,164,253
<p>It really depends on your system resources. You can store CSV file in memory and then insert it into database. But if your CSV file is larger than your RAM there should be some Time issue. You can save each row of csv file as an element in python List.here is my code:</p> <pre><code>csvRows = [] csvFileObj = open('yourfile.csv', 'r') readerObj = csv.reader(csvFileObj) for row in readerObj: element1 = row[0] ....... csvRows.append((element1,element2,...)) </code></pre> <p>after that read element of the list and insert it to your db. I don't think there is a direct way to insert All csv rows into sqldb at once. you need some preprocessing.</p>
0
2016-08-26T10:35:35Z
[ "python", "sql-server", "csv" ]
Openpyxl - create styles as variables
39,163,882
<p>I want apply formats to excel cells (change default fonts and cells fills). I can set the cell attributes one by one:</p> <pre><code>from openpyxl.styles import PatternFill, Border, Side, Alignment, Protection, Font, Color ws1.cell(row=1,column=1).font=Font(color=colors.WHITE,size=9) ws1.cell(row=1,column=1).fill=PatternFill(fill_type="solid", start_color='0000FF', end_color='0000FF') ...and so on </code></pre> <p>Is there a more efficient way of doing this, by creating template styles, so I can only write something like</p> <pre><code>ws1.cell(row=1,column=1).style=TemplateStyle </code></pre>
0
2016-08-26T10:15:26Z
39,859,531
<p>Maybe 'named styles' are an option. I think this is what @Charlie Clark was talking about. You can find a rather limited explanation on the <a href="http://openpyxl.readthedocs.io/en/default/styles.html#creating-a-named-style" rel="nofollow">openpyxl 2.4.0 documentation</a></p> <p>This could look something like the following. </p> <pre><code>from openpyxl.styles import NamedStyle, Font, PatternFill template_style = NamedStyle(name="template_style") template_style.font = Font(color=colors.WHITE,size=9) template_style.fill = PatternFill(fill_type="solid", start_color='0000FF', end_color='0000FF') ws1.cell(row=1, column=1).style = template_style </code></pre> <p>I am not sure how to reference to the name inside the brackets of NamedStyle, but I do know that it does not need to be the same as the variable to which it is associated to. Since the documentation uses both the same name for the variable and name in brackets, I choose to do the same.</p>
0
2016-10-04T18:42:06Z
[ "python", "styles", "openpyxl" ]
Determine column value based on 2 other columns
39,164,079
<p>There are 2 column, Label1 and Label2. Both of them are cluster labels using different methods. </p> <pre><code> Label1 Label2 0 0 1024 1 1 1024 2 2 1025 3 3 1026 4 3 1027 5 4 1028 </code></pre> <p>I wanna get the final cluster label based these 2 columns. Compared each row, as long as one of these two labels are same, they are in the same cluster.</p> <p>For example: row 0 and row 1 have label 2 in common, row 3 and row 4 have label1 in common, thus row0 and row1 in the same group and row3 and row4 in the same group. So the results I'd like to have:</p> <pre><code> Label1 Label2 Cluster ID 0 0 1024 0 1 1 1024 0 2 2 1025 1 3 3 1026 2 4 3 1027 2 5 4 1028 3 </code></pre> <p>What's the best way to do this? Any help would be appreciated.</p> <p>Edited: I think I didn't give a good example. Acutally, labels are not necessarily in any order:</p> <pre><code> Label1 Label2 0 0 1024 1 1 1023 2 2 1025 3 3 1024 4 3 1027 5 4 1022 </code></pre>
1
2016-08-26T10:26:03Z
39,164,930
<p>Not sure I've understood correctly your question but here's a possible way to identify clusters:</p> <pre><code>import pandas as pd import collections df = pd.DataFrame( {'Label1': [0, 1, 2, 3, 3, 4], 'Label2': [1024, 1024, 1025, 1026, 1027, 1028]}) df['Cluster ID'] = [0] * 6 counter1 = {k: v for k, v in collections.Counter( df['Label1']).iteritems() if v &gt; 1} counter1 = counter1.keys() counter2 = {k: v for k, v in collections.Counter( df['Label2']).iteritems() if v &gt; 1} counter2 = counter2.keys() len1 = len(counter1) len2 = len(counter2) index_cluster = len1 + len2 for index, row in df.iterrows(): if row['Label2'] in counter2: df.loc[index, 'Cluster ID'] = counter2.index(row['Label2']) elif row['Label1'] in counter1: df.loc[index, 'Cluster ID'] = counter1.index(row['Label1']) + len2 else: df.loc[index, 'Cluster ID'] = index_cluster index_cluster += 1 print df </code></pre>
1
2016-08-26T11:10:41Z
[ "python", "pandas", "dataframe" ]
Determine column value based on 2 other columns
39,164,079
<p>There are 2 column, Label1 and Label2. Both of them are cluster labels using different methods. </p> <pre><code> Label1 Label2 0 0 1024 1 1 1024 2 2 1025 3 3 1026 4 3 1027 5 4 1028 </code></pre> <p>I wanna get the final cluster label based these 2 columns. Compared each row, as long as one of these two labels are same, they are in the same cluster.</p> <p>For example: row 0 and row 1 have label 2 in common, row 3 and row 4 have label1 in common, thus row0 and row1 in the same group and row3 and row4 in the same group. So the results I'd like to have:</p> <pre><code> Label1 Label2 Cluster ID 0 0 1024 0 1 1 1024 0 2 2 1025 1 3 3 1026 2 4 3 1027 2 5 4 1028 3 </code></pre> <p>What's the best way to do this? Any help would be appreciated.</p> <p>Edited: I think I didn't give a good example. Acutally, labels are not necessarily in any order:</p> <pre><code> Label1 Label2 0 0 1024 1 1 1023 2 2 1025 3 3 1024 4 3 1027 5 4 1022 </code></pre>
1
2016-08-26T10:26:03Z
39,165,298
<p>Here is how you can implement this:</p> <ol> <li><p>Check previous row for same value for the two columns</p></li> <li><p>If either of the values is same, do not increment cluster number and add to cluster list</p></li> <li><p>If none of the values is same, increment cluster number and add to cluster list</p></li> <li><p>Add cluster list as column to the dataframe.</p></li> </ol> <p>Code:</p> <pre><code>import pandas as pd df=pd.DataFrame([[0,1,2,3,4,5],[0,1,2,3,3,4],[1024,1024,1025,1026,1027,1028]]).T cluster_num = 0 cluster_list = [] for i,row in df.iterrows(): if i!=0: # check previous row if df.loc[i-1][1]==row[1] or df.loc[i-1][2]==row[2]: # add to previous cluster cluster_list.append(cluster_num) else: # create new cluster cluster_num+=1 cluster_list.append(cluster_num) else: cluster_list.append(cluster_num) #Add the list as column df.insert(3,3,cluster_list) </code></pre>
1
2016-08-26T11:30:25Z
[ "python", "pandas", "dataframe" ]
Determine column value based on 2 other columns
39,164,079
<p>There are 2 column, Label1 and Label2. Both of them are cluster labels using different methods. </p> <pre><code> Label1 Label2 0 0 1024 1 1 1024 2 2 1025 3 3 1026 4 3 1027 5 4 1028 </code></pre> <p>I wanna get the final cluster label based these 2 columns. Compared each row, as long as one of these two labels are same, they are in the same cluster.</p> <p>For example: row 0 and row 1 have label 2 in common, row 3 and row 4 have label1 in common, thus row0 and row1 in the same group and row3 and row4 in the same group. So the results I'd like to have:</p> <pre><code> Label1 Label2 Cluster ID 0 0 1024 0 1 1 1024 0 2 2 1025 1 3 3 1026 2 4 3 1027 2 5 4 1028 3 </code></pre> <p>What's the best way to do this? Any help would be appreciated.</p> <p>Edited: I think I didn't give a good example. Acutally, labels are not necessarily in any order:</p> <pre><code> Label1 Label2 0 0 1024 1 1 1023 2 2 1025 3 3 1024 4 3 1027 5 4 1022 </code></pre>
1
2016-08-26T10:26:03Z
39,166,174
<p>IIUC, you could group the clusters as follows:</p> <p>Taking the difference between the row and it's next row , filling the topmost row with 0 and finding it's cumulative sum for both the Labels[1 and 2].</p> <pre><code>In [2]: label1_ = df['Label1'].diff().fillna(0).cumsum() In [3]: label2_ = df['Label2'].diff().fillna(0).cumsum() </code></pre> <p>Concatenating these to a new dataframe and dropping the duplicated values separately for both Labels[1 and 2]. Followed by <code>reset_index</code> to get back the default integer index.</p> <pre><code>In [4]: df_ = pd.concat([label1_, label2_], axis=1).drop_duplicates(['Label1']) \ .drop_duplicates(['Label2']) \ .reset_index() </code></pre> <p>Assigning the index values to a new column, Cluster ID.</p> <pre><code>In [5]: df_['Cluster_ID'] = df_.index In [6]: df_.set_index('index', inplace=True) In [7]: df['Cluster_ID'] = df_['Cluster_ID'] </code></pre> <p>Replacing <code>Nan</code> values with it's previous finite value and casting the final answer as an integer.</p> <pre><code>In [8]: df.fillna(method='ffill').astype(int) Out[8]: Label1 Label2 Cluster_ID 0 0 1024 0 1 1 1024 0 2 2 1025 1 3 3 1026 2 4 3 1027 2 5 4 1028 3 </code></pre>
2
2016-08-26T12:17:45Z
[ "python", "pandas", "dataframe" ]
Determine column value based on 2 other columns
39,164,079
<p>There are 2 column, Label1 and Label2. Both of them are cluster labels using different methods. </p> <pre><code> Label1 Label2 0 0 1024 1 1 1024 2 2 1025 3 3 1026 4 3 1027 5 4 1028 </code></pre> <p>I wanna get the final cluster label based these 2 columns. Compared each row, as long as one of these two labels are same, they are in the same cluster.</p> <p>For example: row 0 and row 1 have label 2 in common, row 3 and row 4 have label1 in common, thus row0 and row1 in the same group and row3 and row4 in the same group. So the results I'd like to have:</p> <pre><code> Label1 Label2 Cluster ID 0 0 1024 0 1 1 1024 0 2 2 1025 1 3 3 1026 2 4 3 1027 2 5 4 1028 3 </code></pre> <p>What's the best way to do this? Any help would be appreciated.</p> <p>Edited: I think I didn't give a good example. Acutally, labels are not necessarily in any order:</p> <pre><code> Label1 Label2 0 0 1024 1 1 1023 2 2 1025 3 3 1024 4 3 1027 5 4 1022 </code></pre>
1
2016-08-26T10:26:03Z
39,169,864
<p>Try this: Use np.where and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.duplicated.html" rel="nofollow">pandas.duplicated</a></p> <pre><code>df = df.sort_values(['Label1', 'Label2']) df['Cluster'] = np.where( (df.Label1.duplicated()) | (df.Label2.duplicated()),0,1).cumsum() print df Label1 Label2 Cluster 0 0 1024 1 1 1 1024 1 2 2 1025 2 3 3 1026 3 4 3 1027 3 5 4 1028 4 </code></pre>
2
2016-08-26T15:33:11Z
[ "python", "pandas", "dataframe" ]
How to append characters to a string being used as a python dictionary key (when there are multiple entries related to that string)?
39,164,114
<p>I am pulling out sequence coordinates from the output file produced by HMMER (finds DNA sequences, matching a query, in a genome assembly file).</p> <p>I create a python dictionary where the key is the source sequence name (a string), and the value is a list comprising the start and end coordinates of the target sequence. However, HMMER often finds multiple matches on a single source sequence (contig/chromosome).</p> <p>This means that as I add to the dictionary, if I come across multiple matches on a contig, each is overwritten by the following match.</p> <p>E.g. HMMER finds the following matches:</p> <blockquote> <p>Name Start End</p> <p>4415 16723 17556</p> <p>127 1290 1145</p> <p>1263 34900 37834</p> <p>4415 2073 3899</p> <p>4415 4580 6004</p> </blockquote> <p>But this results in the following dictionary (I want separate entries for each match):</p> <blockquote> <p>{'127': ['1290', '1145'], '1263': ['34900', '37834'], '4415': ['4580', '6004']}</p> </blockquote> <p>How can I append a letter to the key so that subsequent matches are unique and do not overwrite the previous ones, i.e. 4415, 4415a, 4415b, and so on?</p> <pre><code>matches = {} for each line of HMMER file: split the line make a list of fields 4 &amp; 5 (the coordinates) # at this stage I need a way of checking whether the key (sequenceName) # is already in the dictionary (easy), and if it is, appending a letter # to sequenceName to make it unique matches[sequenceName] = list </code></pre>
1
2016-08-26T10:27:22Z
39,164,299
<p>It's not a proper way to go to create different keys while the are equal, instead you can use a list for your values and preserve the coordinates in it, for duplicate keys. You can use <code>collections.defaultdict()</code> for this aim:</p> <pre><code>&gt;&gt;&gt; coords = [['4415', '16723', '17556'], ['127', '1290', '1145'], ['1263', '34900', '37834'], ['4415', '2073', '3899'], ['4415', '4580', '6004']] &gt;&gt;&gt; from collections import defaultdict &gt;&gt;&gt; &gt;&gt;&gt; d = defaultdict(list) &gt;&gt;&gt; &gt;&gt;&gt; for i, j, k in coords: ... d[i].append((j, k)) ... &gt;&gt;&gt; d defaultdict(&lt;type 'list'&gt;, {'1263': [('34900', '37834')], '4415': [('16723', '17556'), ('2073', '3899'), ('4580', '6004')], '127': [('1290', '1145')]}) </code></pre> <p>Besides, the idea of adding a character at the end of the keys in not optimum, because you need to have the count of keys always and you are not aware of this number so you have to generate new suffix.</p> <p>But as an alternative if you only use the count of the keys you can create different ones by preserving the keys in a <code>Counter()</code> object and adding the count at the trailing of the key:</p> <pre><code>&gt;&gt;&gt; from collections import Counter &gt;&gt;&gt; d = {} &gt;&gt;&gt; c = Counter() &gt;&gt;&gt; for i, j, k in coords: ... c.update((i,)) ... d["{}_{}".format(i, c[i])] = (j, k) ... &gt;&gt;&gt; d {'4415_1': ('16723', '17556'), '4415_3': ('4580', '6004'), '4415_2': ('2073', '3899'), '127_1': ('1290', '1145'), '1263_1': ('34900', '37834')} </code></pre>
0
2016-08-26T10:38:16Z
[ "python", "dictionary", "key", "unique" ]
How to append characters to a string being used as a python dictionary key (when there are multiple entries related to that string)?
39,164,114
<p>I am pulling out sequence coordinates from the output file produced by HMMER (finds DNA sequences, matching a query, in a genome assembly file).</p> <p>I create a python dictionary where the key is the source sequence name (a string), and the value is a list comprising the start and end coordinates of the target sequence. However, HMMER often finds multiple matches on a single source sequence (contig/chromosome).</p> <p>This means that as I add to the dictionary, if I come across multiple matches on a contig, each is overwritten by the following match.</p> <p>E.g. HMMER finds the following matches:</p> <blockquote> <p>Name Start End</p> <p>4415 16723 17556</p> <p>127 1290 1145</p> <p>1263 34900 37834</p> <p>4415 2073 3899</p> <p>4415 4580 6004</p> </blockquote> <p>But this results in the following dictionary (I want separate entries for each match):</p> <blockquote> <p>{'127': ['1290', '1145'], '1263': ['34900', '37834'], '4415': ['4580', '6004']}</p> </blockquote> <p>How can I append a letter to the key so that subsequent matches are unique and do not overwrite the previous ones, i.e. 4415, 4415a, 4415b, and so on?</p> <pre><code>matches = {} for each line of HMMER file: split the line make a list of fields 4 &amp; 5 (the coordinates) # at this stage I need a way of checking whether the key (sequenceName) # is already in the dictionary (easy), and if it is, appending a letter # to sequenceName to make it unique matches[sequenceName] = list </code></pre>
1
2016-08-26T10:27:22Z
39,165,538
<p>You can do something like this:</p> <pre><code>matches = {'127': ['1290', '1145'], '1263': ['34900', '37834'], '4415': ['4580', '6004']} # sample key_name key_name = '4415' if key_name in matches.keys(): for i in xrange(1,26): if key_name+chr(ord('a') + i) not in matches.keys(): matches[key_name+chr(ord('a') + i)] = #your value </code></pre> <p>This will increment your key_names as 4415a, 4415b...</p>
0
2016-08-26T11:45:41Z
[ "python", "dictionary", "key", "unique" ]
Django : authenticate() is not working for users created by register page, but working for those users who were created by admin
39,164,249
<p>I want to make a register/login API for users. Problem is like this : If I create user via admin site, login is working properly.</p> <p>If I create user via register page made by me, login isn't working.(authenticate() function is returning None, even though that user is still in user table.)</p> <p>I go to admin site, go to the link to change password and give the same password again. After that I can login successfully.</p> <p>I think problem is either in saving password or login. I have crossed checked a lot but couldn't figure out. I am giving all files. You may go through important code.</p> <p>models.py </p> <pre class="lang-py prettyprint-override"><code>from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User from datetime import datetime class Recruiter(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) company_name = models.CharField(max_length=120) HR_office_number = models.CharField(max_length=15) HR_mobile_number = models.CharField(max_length=15) def __str__(self): return self.user.username </code></pre> <p>forms.py </p> <pre class="lang-py prettyprint-override"><code>from django import forms from .models import Recruiter, User from django.core.exceptions import ValidationError class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput(), max_length=128) confirm_password = forms.CharField(widget=forms.PasswordInput(), max_length=128) class Meta: model = User fields = ['first_name', 'last_name', 'username', 'email'] def __init__(self, *args, **kwargs): super(UserForm, self).__init__(*args, **kwargs) self.fields['first_name'].required = True self.fields['last_name'].required = True self.fields['email'].required = True self.fields['username'].help_text = None def clean_confirm_password(self): password1 = self.cleaned_data.get('password') password2 = self.cleaned_data.get('confirm_password') if not (password1 and password2): raise forms.ValidationError("You must confirm your password") elif password1 != password2: raise forms.ValidationError("Your passwords do not match") return password1 class RecruiterForm(forms.ModelForm): class Meta: model = Recruiter fields = ('company_name', 'HR_mobile_number', 'HR_office_number') </code></pre> <p>views.py </p> <pre class="lang-py prettyprint-override"><code>from django.shortcuts import render from django.contrib.auth.models import User from .models import Recruiter from .forms import RecruiterForm, UserForm, RecruiterLoginForm from django.urls import reverse from django.http import HttpResponse,HttpResponseRedirect from django.db import IntegrityError from django.contrib.auth import authenticate, login, logout def register(request): context = request.POST registered = False if request.method == 'POST': user_form = UserForm(data=request.POST) recruiter_form = RecruiterForm(data=request.POST) if user_form.is_valid() and recruiter_form.is_valid(): user = user_form.save() try: user.set_password(user.password) user.save() except IntegrityError as e: user.delete() return HttpResponse(e.message) try: recruiter = recruiter_form.save(commit=False) recruiter.user = user recruiter.save() except IntegrityError as e: recruiter.delete() return HttpResponse(e.message) registered = True else: pass #print form.errors else: recruiter_form = RecruiterForm() user_form = UserForm() return render(request, 'recruiter/register.html', {'user_form':user_form, 'recruiter_form':recruiter_form, 'registered':registered}, context) def login_recruiter(request): context = request.POST if request.user.is_authenticated(): return HttpResponse("Logged in") if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) print user if user: if user.is_active: login(request, user) return HttpResponse("Success") else: return HttpResponse("Not active") else: return HttpResponse("Invalid") else: return render(request, 'recruiter/login_recruiter.html', {}, context) </code></pre> <p>register.html </p> <pre class="lang-py prettyprint-override"><code>{% if registered %} &lt;h1&gt;Registered&lt;/h1&gt;&lt;br /&gt; {% else %} &lt;form id="user_form" method="post" action="{% url 'recruiter:register' %}" enctype="multipart/form-data"&gt; {% csrf_token %} {{ user_form.as_p}} {{ recruiter_form.as_p}} &lt;input type="submit" name="submit" value="Register" /&gt; &lt;/form&gt; {% endif %} </code></pre> <p>login_recruiter.html </p> <pre class="lang-py prettyprint-override"><code>&lt;form id="login_form" method="post" action="{% url 'recruiter:login_recruiter' %}"&gt; {% csrf_token %} Username: &lt;input type="text" name="username" value="" size="120" /&gt; &lt;br /&gt; Password: &lt;input type="password" name="password" value="" size="120" /&gt; &lt;br /&gt; &lt;input type="submit" value="submit" /&gt; &lt;/form&gt; </code></pre>
0
2016-08-26T10:35:22Z
39,164,579
<p>The issue is in how you set the password. You've excluded the password from the list of fields on the model form, so it is not set on save. So doing <code>user.set_password(user.password)</code> is effectively setting the password to the hash of None. Instead, do this:</p> <pre><code>user = user_form.save(commit=False) user.set_password(user_form.cleaned_data['password'] user.save() </code></pre> <p>Note that even in your original code there was no way setting the password could cause IntegrityError, so that try/except was unnecessary; it's even more so now, so you should remove it.</p>
0
2016-08-26T10:53:02Z
[ "python", "django", "django-views" ]
Django : authenticate() is not working for users created by register page, but working for those users who were created by admin
39,164,249
<p>I want to make a register/login API for users. Problem is like this : If I create user via admin site, login is working properly.</p> <p>If I create user via register page made by me, login isn't working.(authenticate() function is returning None, even though that user is still in user table.)</p> <p>I go to admin site, go to the link to change password and give the same password again. After that I can login successfully.</p> <p>I think problem is either in saving password or login. I have crossed checked a lot but couldn't figure out. I am giving all files. You may go through important code.</p> <p>models.py </p> <pre class="lang-py prettyprint-override"><code>from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User from datetime import datetime class Recruiter(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) company_name = models.CharField(max_length=120) HR_office_number = models.CharField(max_length=15) HR_mobile_number = models.CharField(max_length=15) def __str__(self): return self.user.username </code></pre> <p>forms.py </p> <pre class="lang-py prettyprint-override"><code>from django import forms from .models import Recruiter, User from django.core.exceptions import ValidationError class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput(), max_length=128) confirm_password = forms.CharField(widget=forms.PasswordInput(), max_length=128) class Meta: model = User fields = ['first_name', 'last_name', 'username', 'email'] def __init__(self, *args, **kwargs): super(UserForm, self).__init__(*args, **kwargs) self.fields['first_name'].required = True self.fields['last_name'].required = True self.fields['email'].required = True self.fields['username'].help_text = None def clean_confirm_password(self): password1 = self.cleaned_data.get('password') password2 = self.cleaned_data.get('confirm_password') if not (password1 and password2): raise forms.ValidationError("You must confirm your password") elif password1 != password2: raise forms.ValidationError("Your passwords do not match") return password1 class RecruiterForm(forms.ModelForm): class Meta: model = Recruiter fields = ('company_name', 'HR_mobile_number', 'HR_office_number') </code></pre> <p>views.py </p> <pre class="lang-py prettyprint-override"><code>from django.shortcuts import render from django.contrib.auth.models import User from .models import Recruiter from .forms import RecruiterForm, UserForm, RecruiterLoginForm from django.urls import reverse from django.http import HttpResponse,HttpResponseRedirect from django.db import IntegrityError from django.contrib.auth import authenticate, login, logout def register(request): context = request.POST registered = False if request.method == 'POST': user_form = UserForm(data=request.POST) recruiter_form = RecruiterForm(data=request.POST) if user_form.is_valid() and recruiter_form.is_valid(): user = user_form.save() try: user.set_password(user.password) user.save() except IntegrityError as e: user.delete() return HttpResponse(e.message) try: recruiter = recruiter_form.save(commit=False) recruiter.user = user recruiter.save() except IntegrityError as e: recruiter.delete() return HttpResponse(e.message) registered = True else: pass #print form.errors else: recruiter_form = RecruiterForm() user_form = UserForm() return render(request, 'recruiter/register.html', {'user_form':user_form, 'recruiter_form':recruiter_form, 'registered':registered}, context) def login_recruiter(request): context = request.POST if request.user.is_authenticated(): return HttpResponse("Logged in") if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) print user if user: if user.is_active: login(request, user) return HttpResponse("Success") else: return HttpResponse("Not active") else: return HttpResponse("Invalid") else: return render(request, 'recruiter/login_recruiter.html', {}, context) </code></pre> <p>register.html </p> <pre class="lang-py prettyprint-override"><code>{% if registered %} &lt;h1&gt;Registered&lt;/h1&gt;&lt;br /&gt; {% else %} &lt;form id="user_form" method="post" action="{% url 'recruiter:register' %}" enctype="multipart/form-data"&gt; {% csrf_token %} {{ user_form.as_p}} {{ recruiter_form.as_p}} &lt;input type="submit" name="submit" value="Register" /&gt; &lt;/form&gt; {% endif %} </code></pre> <p>login_recruiter.html </p> <pre class="lang-py prettyprint-override"><code>&lt;form id="login_form" method="post" action="{% url 'recruiter:login_recruiter' %}"&gt; {% csrf_token %} Username: &lt;input type="text" name="username" value="" size="120" /&gt; &lt;br /&gt; Password: &lt;input type="password" name="password" value="" size="120" /&gt; &lt;br /&gt; &lt;input type="submit" value="submit" /&gt; &lt;/form&gt; </code></pre>
0
2016-08-26T10:35:22Z
39,166,353
<p>Use the below code to solve it..</p> <pre><code>def register(request, template_name="registration/register.html"): if request.method == "POST": postdata = request.POST.copy() username = postdata.get('username', '') email = postdata.get('email', '') password = postdata.get('password', '') # check if user does not exist if User.objects.filter(username=username).exists(): username_unique_error = True if User.objects.filter(email=email).exists(): email_unique_error = True else : create_new_user = User.objects.create_user(username, email, password) create_new_user.save() user = authenticate(username=username, password=password) login(request, user) if create_new_user is not None: if create_new_user.is_active: return HttpResponseRedirect('/profile') else: print("The password is valid, but the account has been disabled!") return render(request, template_name, locals()) def log_in(request, template_name="registration/login.html"): page_title = "Login" if request.method == "POST": postdata = request.POST.copy() username = postdata.get('username', '') password = postdata.get('password', '') try: user = authenticate(username=username, password=password) login(request, user) return HttpResponseRedirect('/profile') except : error = True return render(request, template_name, locals()) </code></pre>
0
2016-08-26T12:27:06Z
[ "python", "django", "django-views" ]
Inserting data to table psycopg2 with no duplicates
39,164,347
<p>I am new to psycopg2. I have to insert data into the table with no duplicates. So, first I created a temporary table where I dumped all the data. And then, I check and add the data to the actual table. Here is the code till now:</p> <pre><code>for eachline in content: pmid ,first_name, last_name,initial,article_title,journal,language = eachline.split("\t") cur.execute ("INSERT INTO AUTHOR_PMID(pmid, Author_lastname, Author_firstname, Author_initial,Article_title) SELECT DISTINCT (pmid, Author_lastname, Author_firstname, Author_initial,Article_title) FROM AUTHOR_PMID WHERE NOT EXISTS (SELECT "X" FROM AUTHOR_pmid_temp WHERE AUTHOR_pmid_temp.pmid = AUTHOR_PMID.pmid AND AUTHOR_pmid_temp.Author_lastname = AUTHOR_PMID.Author_lastname AND AUTHOR_pmid_temp.Author_firstname = AUTHOR_PMID.Author_firstname AND AUTHOR_pmid_temp.Author_initial = AUTHOR_PMID.Author_initial AND AUTHOR_pmid_temp.Article_title = AUTHOR_PMID.Article_title);") con.commit() error: syntax error. </code></pre> <p>Where am i going wrong?</p>
0
2016-08-26T10:40:31Z
39,164,660
<p>Try inserting query with triple quotes instead of single like below</p> <pre><code>for eachline in content: pmid ,first_name, last_name,initial,article_title,journal,language = eachline.split("\t") cur.execute ("""INSERT INTO AUTHOR_PMID(pmid, Author_lastname, Author_firstname, Author_initial,Article_title) SELECT DISTINCT (pmid, Author_lastname, Author_firstname, Author_initial,Article_title) FROM AUTHOR_PMID WHERE NOT EXISTS (SELECT "X" FROM AUTHOR_pmid_temp WHERE AUTHOR_pmid_temp.pmid = AUTHOR_PMID.pmid AND AUTHOR_pmid_temp.Author_lastname = AUTHOR_PMID.Author_lastname AND AUTHOR_pmid_temp.Author_firstname = AUTHOR_PMID.Author_firstname AND AUTHOR_pmid_temp.Author_initial = AUTHOR_PMID.Author_initial AND AUTHOR_pmid_temp.Article_title = AUTHOR_PMID.Article_title);""") con.commit() </code></pre> <p>For more info, please <a href="http://initd.org/psycopg/docs/usage.html#passing-parameters-to-sql-queries" rel="nofollow">check here</a> !!!</p>
1
2016-08-26T10:56:18Z
[ "python", "psycopg2" ]
Best way to create a similarity matrix for given set of items with tags
39,164,482
<p>We have data in format:</p> <pre><code>{ '1': ['Lathi Charge', 'NIT', 'Nirmal Singh'] '2': ['Kangana Ranaut', 'Hrithik Roshan'] '3': ['Hrithik Roshan', 'mohenjo daro', 'release date'], '4': ['NIT', 'Placements'] ... } </code></pre> <p>Keys of dictionary are items and values are tags associated with them. Numbers of entries are around 10 million, We want to calculate similarity between each items?</p> <p>One more question associated with same is if any new entry comes on run time what would be best way to calculate its similarity with existing entries.</p>
1
2016-08-26T10:48:24Z
39,183,722
<p>There's only one similarity score that I can think of which would reliably handle the data you're looking at (it looks like your data is similar to that which would be gathered in a corpus study where documents are represented as bags of words, each potentially containing several words not present in the other documents in the corpus): that's cosine similarity. <a href="http://blog.christianperone.com/2013/09/machine-learning-cosine-similarity-for-vector-space-models-part-iii/" rel="nofollow">Here</a> is a pretty good explanation with some python code to go along.</p>
0
2016-08-27T17:11:46Z
[ "python", "nlp", "scikit-learn" ]
Python strip Google Alerts URL
39,164,524
<p>I've currently got a dataframe filled with Google Alert URLS that look like:</p> <pre><code>link = 'https://www.google.com/url?rct=j&amp;sa=t&amp;url=http://3dprint.com/4353/littledlper-dlp-3d-printer-kickstarter/&amp;ct=ga&amp;cd=CAEYBCoSODQ1OTg1ODMwMzQwNDUzMTUxMhw2NTFlMTg3MTI1ZGE4Nzc3OmNvLnVrOmVuOkdC&amp;usg=AFQjCNF0HOEhqIZHEpdkH1eVdXt-JRBF3Q' </code></pre> <p>and I just want the part following <code>url=</code> and before the junk.</p> <pre><code>http://3dprint.com/4353/littledlper-dlp-3d-printer-kickstarter/ </code></pre> <p>I used <code>urllib.parse.urlparse(link)</code> to get a list of URL elements...</p> <pre><code>parsed = ParseResult(scheme='https', netloc='www.google.com', path='/url', params='', query='rct=j&amp;sa=t&amp;url=http://3dprint.com/4353/littledlper-dlp-3d-printer-kickstarter/&amp;ct=ga&amp;cd=CAEYBCoSODQ1OTg1ODMwMzQwNDUzMTUxMhw2NTFlMTg3MTI1ZGE4Nzc3OmNvLnVrOmVuOkdC&amp;usg=AFQjCNF0HOEhqIZHEpdkH1eVdXt-JRBF3Q', fragment='') </code></pre> <p>but even then <code>parsed[4]</code> only breaks it down to...</p> <pre><code>'rct=j&amp;sa=t&amp;url=http://3dprint.com/4353/littledlper-dlp-3d-printer-kickstarter/&amp;ct=ga&amp;cd=CAEYBCoSODQ1OTg1ODMwMzQwNDUzMTUxMhw2NTFlMTg3MTI1ZGE4Nzc3OmNvLnVrOmVuOkdC&amp;usg=AFQjCNF0HOEhqIZHEpdkH1eVdXt-JRBF3Q' </code></pre> <p>I found <a href="http://stackoverflow.com/questions/39088532/i-need-to-strip-a-google-alerts-url">other</a> <a href="http://stackoverflow.com/questions/15777513/extract-original-url-from-google-alerts-link">queries</a> on Stack with this same question but they were in other programming languages than Python.</p> <p>Any ideas on a Python approach?</p>
1
2016-08-26T10:50:38Z
39,164,685
<p>You may use a regex on <code>parsed[4]</code> to extract that URL:</p> <pre><code>(?:^|&amp;)url=([^&amp;]+) </code></pre> <p>See the <a href="https://regex101.com/r/sG7yY1/1" rel="nofollow">regex demo</a></p> <p><em>Details</em>:</p> <ul> <li><code>(?:^|&amp;)</code> - either start of string or <code>&amp;</code></li> <li><code>url=</code> - literal text <code>url=</code></li> <li><code>([^&amp;]+)</code> - Group 1 capturing one or more symbols other than <code>&amp;</code>.</li> </ul> <p><a href="https://ideone.com/BtRIlP" rel="nofollow">Python demo</a>:</p> <pre><code>import re p = re.compile(r'(?:^|&amp;)url=([^&amp;]+)') s = "rct=j&amp;sa=t&amp;url=http://3dprint.com/4353/littledlper-dlp-3d-printer-kickstarter/&amp;ct=ga&amp;cd=CAEYBCoSODQ1OTg1ODMwMzQwNDUzMTUxMhw2NTFlMTg3MTI1ZGE4Nzc3OmNvLnVrOmVuOkdC&amp;usg=AFQjCNF0HOEhqIZHEpdkH1eVdXt-JRBF3Q" mObj = p.search(s) if mObj: print(mObj.group(1)) </code></pre>
1
2016-08-26T10:57:40Z
[ "python", "regex", "urllib2" ]
How can i use autocomplete in IDE in this case in python
39,164,599
<pre><code>class Event(object): can_i_autocomplete_this = True class App(object): def decorator(self, func): self.func = func def call(): self.func(Event()) app = App() @app.decorator def hello(something): print(something.can_i_autocomplete_this) app.call() </code></pre> <p>I use decorator like this. but in this case, <code>something</code> parameter in hello method autocomplete doesn't work in IDE(pycharm). (must support python 2.7)</p> <p>how can i use autocomplete in this case?</p> <p>thank you.</p>
0
2016-08-26T10:54:06Z
39,331,253
<p>Usages of function are not analyzed in inferring types of parameters.</p> <p>You could specify type of parameter inside doc:</p> <pre><code>@app.decorator def hello(something): """ :param something: :type something: Event :return: """ print(something.can_i_autocomplete_this) </code></pre> <p>or using type hinting syntax (since Python 3.5):</p> <pre><code>@app.decorator def hello(something: Event): print(something.can_i_autocomplete_this) </code></pre>
2
2016-09-05T13:05:22Z
[ "python", "autocomplete", "pycharm", "python-decorators" ]
Membership checking in Numpy ndarray
39,164,636
<p>I have written a script that evaluates if some entry of <code>arr</code> is in <code>check_elements</code>. My approach does <em>not</em> compare single entries, but whole vectors inside of <code>arr</code>. Thus, the script checks if <code>[8, 3]</code>, <code>[4, 5]</code>, ... is in <code>check_elements</code>.</p> <p>Here's an example: </p> <pre><code>import numpy as np # arr.shape -&gt; (2, 3, 2) arr = np.array([[[8, 3], [4, 5], [6, 2]], [[9, 0], [1, 10], [7, 11]]]) # check_elements.shape -&gt; (3, 2) # generally: (n, 2) check_elements = np.array([[4, 5], [9, 0], [7, 11]]) # rslt.shape -&gt; (2, 3) rslt = np.zeros((arr.shape[0], arr.shape[1]), dtype=np.bool) for i, j in np.ndindex((arr.shape[0], arr.shape[1])): if arr[i, j] in check_elements: # &lt;-- condition is checked against # the whole last dimension rslt[i, j] = True else: rslt[i, j] = False </code></pre> <p>Now:</p> <pre><code>print(rslt) </code></pre> <p>...would print:</p> <pre><code>[[False True False] [ True False True]] </code></pre> <p>For getting the indices of I use:</p> <pre><code>print(np.transpose(np.nonzero(rslt))) </code></pre> <p>...which prints the following:</p> <pre><code>[[0 1] # arr[0, 1] -&gt; [4, 5] -&gt; is in check_elements [1 0] # arr[1, 0] -&gt; [9, 0] -&gt; is in check_elements [1 2]] # arr[1, 2] -&gt; [7, 11] -&gt; is in check_elements </code></pre> <p>This task would be easy and performant if I would check a condition on single values, like <code>arr &gt; 3</code> or <code>np.where(...)</code>, but I am <em>not</em> interested in single values. I want to check a condition against the whole last dimension (or slices of it).</p> <p><strong>My question is</strong>: is there a faster way to achieve the same result? Am I right that vectorized attempts and things like <code>np.where</code> can <em>not</em> be used for my problem, because they always operate on single values and not on a whole dimension or slices of that dimension?</p>
2
2016-08-26T10:55:21Z
39,164,996
<p>The <a href="https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP" rel="nofollow">numpy_indexed</a> package (disclaimer: I am its author) contains functionality to perform these kind of queries; specifically, containment relations for nd (sub)arrays:</p> <pre><code>import numpy_indexed as npi flatidx = npi.indices(arr.reshape(-1, 2), check_elements) idx = np.unravel_index(flatidx, arr.shape[:-1]) </code></pre> <p>Note that the implementation is fully vectorized under the hood. </p> <p>Also, note that with this approach, the order of the indices in idx match with the order of check_elements; the first item in idx are the row and col of the first item in check_elements. This information is lost when using an approach along the lines you posted above, or when using one of the alternative suggested answers, which will give you the idx sorted by their order of appearance in arr instead, which is often undesirable.</p>
2
2016-08-26T11:13:46Z
[ "python", "numpy", "indexing" ]
Membership checking in Numpy ndarray
39,164,636
<p>I have written a script that evaluates if some entry of <code>arr</code> is in <code>check_elements</code>. My approach does <em>not</em> compare single entries, but whole vectors inside of <code>arr</code>. Thus, the script checks if <code>[8, 3]</code>, <code>[4, 5]</code>, ... is in <code>check_elements</code>.</p> <p>Here's an example: </p> <pre><code>import numpy as np # arr.shape -&gt; (2, 3, 2) arr = np.array([[[8, 3], [4, 5], [6, 2]], [[9, 0], [1, 10], [7, 11]]]) # check_elements.shape -&gt; (3, 2) # generally: (n, 2) check_elements = np.array([[4, 5], [9, 0], [7, 11]]) # rslt.shape -&gt; (2, 3) rslt = np.zeros((arr.shape[0], arr.shape[1]), dtype=np.bool) for i, j in np.ndindex((arr.shape[0], arr.shape[1])): if arr[i, j] in check_elements: # &lt;-- condition is checked against # the whole last dimension rslt[i, j] = True else: rslt[i, j] = False </code></pre> <p>Now:</p> <pre><code>print(rslt) </code></pre> <p>...would print:</p> <pre><code>[[False True False] [ True False True]] </code></pre> <p>For getting the indices of I use:</p> <pre><code>print(np.transpose(np.nonzero(rslt))) </code></pre> <p>...which prints the following:</p> <pre><code>[[0 1] # arr[0, 1] -&gt; [4, 5] -&gt; is in check_elements [1 0] # arr[1, 0] -&gt; [9, 0] -&gt; is in check_elements [1 2]] # arr[1, 2] -&gt; [7, 11] -&gt; is in check_elements </code></pre> <p>This task would be easy and performant if I would check a condition on single values, like <code>arr &gt; 3</code> or <code>np.where(...)</code>, but I am <em>not</em> interested in single values. I want to check a condition against the whole last dimension (or slices of it).</p> <p><strong>My question is</strong>: is there a faster way to achieve the same result? Am I right that vectorized attempts and things like <code>np.where</code> can <em>not</em> be used for my problem, because they always operate on single values and not on a whole dimension or slices of that dimension?</p>
2
2016-08-26T10:55:21Z
39,165,059
<p>Here is a Numpythonic approach using <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow"><em>broadcasting</em></a>:</p> <pre><code>&gt;&gt;&gt; (check_elements == arr[:,:,None]).reshape(2, 3, 6).any(axis=2) array([[False, True, False], [ True, False, True]], dtype=bool) </code></pre>
2
2016-08-26T11:17:39Z
[ "python", "numpy", "indexing" ]
Membership checking in Numpy ndarray
39,164,636
<p>I have written a script that evaluates if some entry of <code>arr</code> is in <code>check_elements</code>. My approach does <em>not</em> compare single entries, but whole vectors inside of <code>arr</code>. Thus, the script checks if <code>[8, 3]</code>, <code>[4, 5]</code>, ... is in <code>check_elements</code>.</p> <p>Here's an example: </p> <pre><code>import numpy as np # arr.shape -&gt; (2, 3, 2) arr = np.array([[[8, 3], [4, 5], [6, 2]], [[9, 0], [1, 10], [7, 11]]]) # check_elements.shape -&gt; (3, 2) # generally: (n, 2) check_elements = np.array([[4, 5], [9, 0], [7, 11]]) # rslt.shape -&gt; (2, 3) rslt = np.zeros((arr.shape[0], arr.shape[1]), dtype=np.bool) for i, j in np.ndindex((arr.shape[0], arr.shape[1])): if arr[i, j] in check_elements: # &lt;-- condition is checked against # the whole last dimension rslt[i, j] = True else: rslt[i, j] = False </code></pre> <p>Now:</p> <pre><code>print(rslt) </code></pre> <p>...would print:</p> <pre><code>[[False True False] [ True False True]] </code></pre> <p>For getting the indices of I use:</p> <pre><code>print(np.transpose(np.nonzero(rslt))) </code></pre> <p>...which prints the following:</p> <pre><code>[[0 1] # arr[0, 1] -&gt; [4, 5] -&gt; is in check_elements [1 0] # arr[1, 0] -&gt; [9, 0] -&gt; is in check_elements [1 2]] # arr[1, 2] -&gt; [7, 11] -&gt; is in check_elements </code></pre> <p>This task would be easy and performant if I would check a condition on single values, like <code>arr &gt; 3</code> or <code>np.where(...)</code>, but I am <em>not</em> interested in single values. I want to check a condition against the whole last dimension (or slices of it).</p> <p><strong>My question is</strong>: is there a faster way to achieve the same result? Am I right that vectorized attempts and things like <code>np.where</code> can <em>not</em> be used for my problem, because they always operate on single values and not on a whole dimension or slices of that dimension?</p>
2
2016-08-26T10:55:21Z
39,165,104
<p>You can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.in1d.html" rel="nofollow"><code>np.in1d</code></a> even though it is meant for 1D arrays by giving it a 1D view of your array, containing one element per last axis:</p> <pre><code>arr_view = arr.view((np.void, arr.dtype.itemsize*arr.shape[-1])).ravel() check_view = check_elements.view((np.void, check_elements.dtype.itemsize*check_elements.shape[-1])).ravel() </code></pre> <p>will give you two 1D arrays, which contain a <code>void</code> type version of you 2 element arrays along the last axis. Now you can check, which of the elements in <code>arr</code> is also in <code>check_view</code> by doing:</p> <pre><code>flatResult = np.in1d(arr_view, check_view) </code></pre> <p>This will give a flattened array, which you can then reshape to the shape of <code>arr</code>, dropping the last axis:</p> <pre><code>print(flatResult.reshape(arr.shape[:-1])) </code></pre> <p>which will give you the desired result:</p> <pre><code>array([[False, True, False], [ True, False, True]], dtype=bool) </code></pre>
1
2016-08-26T11:19:53Z
[ "python", "numpy", "indexing" ]
Invert 0 and 1 in a binary array
39,164,786
<p>Is there a function in Numpy to invert 0 and 1 in a binary array? If</p> <pre><code>a = np.array([0, 1, 0, 1, 1]) </code></pre> <p>I would like to get:</p> <pre><code>b = [1, 0, 1, 0, 0] </code></pre> <p>I use:</p> <pre><code>b[a==0] = 1 b[a==1] = 0 </code></pre> <p>but maybe it already exist something in Numpy to do this.</p>
0
2016-08-26T11:02:55Z
39,164,837
<p>A functional approach:</p> <pre><code>&gt;&gt;&gt; np.logical_not(a).astype(int) array([1, 0, 1, 0, 0]) </code></pre>
3
2016-08-26T11:06:11Z
[ "python", "numpy" ]
Invert 0 and 1 in a binary array
39,164,786
<p>Is there a function in Numpy to invert 0 and 1 in a binary array? If</p> <pre><code>a = np.array([0, 1, 0, 1, 1]) </code></pre> <p>I would like to get:</p> <pre><code>b = [1, 0, 1, 0, 0] </code></pre> <p>I use:</p> <pre><code>b[a==0] = 1 b[a==1] = 0 </code></pre> <p>but maybe it already exist something in Numpy to do this.</p>
0
2016-08-26T11:02:55Z
39,164,876
<p>you can simply do:</p> <pre><code>In[1]:b=1-a In[2]:b Out[2]: array([1, 0, 1, 0, 0]) </code></pre> <p>or </p> <pre><code>In[22]:b=(~a.astype(bool)).astype(int) Out[22]: array([1, 0, 1, 0, 0]) </code></pre>
5
2016-08-26T11:07:55Z
[ "python", "numpy" ]
global legend for all subplots
39,164,828
<p>I create an n x n matrix of matplot subplots which contain the same type of curve (lets name them signal1 and signal2):</p> <pre><code>n=5 f, axarr = plt.subplots(n,n) for i,signal_generator in enumerate(signal_generators): y=i%n x=(i-y)/n axarr[x, y].plot(signal_generator.signal1) axarr[x, y].plot(signal_generator.signal2) </code></pre> <p>Since the 2 signals in each subplot each represent the same types, I want to use a figure global legend with the two entries 'signal1' 'signal2', rather then attaching the same legend to each subplot.</p> <p>How would I do that?</p>
-1
2016-08-26T11:05:41Z
39,170,018
<p>One way to do it is to force some extra space below the plots. Then you can fit the legend right there and have one "global" legend.</p> <pre><code>import matplotlib.pyplot as plt import numpy as np plt.close('all') fig, axlist = plt.subplots(3, 3) for ax in axlist.flatten(): line1, = ax.plot(np.random.random(100), label='data1') line2, = ax.plot(np.random.random(100), label='data2') line3, = ax.plot(np.random.random(100), 'o', label='data3') fig.subplots_adjust(top=0.9, left=0.1, right=0.9, bottom=0.12) # create some space below the plots by increasing the bottom-value axlist.flatten()[-2].legend(loc='upper center', bbox_to_anchor=(0.5, -0.12), ncol=3) # it would of course be better with a nicer handle to the middle-bottom axis object, but since I know it is the second last one in my 3 x 3 grid... fig.show() </code></pre> <p>Now there will be an label below the second last (bottom middle) axis area, thanks to the <code>bbox_to_anchor=(x, y)</code> with a negative y-value. Depending on how many different subplots you have, and how many different lines you plot in each subplot it might be better to keep proper track of the different line-objects. Maybe append them to a list.</p> <p>For me it the output figure looks like</p> <p><a href="http://i.stack.imgur.com/Ac24E.png" rel="nofollow"><img src="http://i.stack.imgur.com/Ac24E.png" alt="enter image description here"></a></p> <p>Does this give you want you were looking for?</p>
1
2016-08-26T15:42:24Z
[ "python", "matplotlib", "subplot" ]
Multiprocessing in Python crashes when code reaches start()
39,164,865
<p>I am new in Python. I tried to use some multiprocessing to make my work faster. First I tried an example and everything worked fine. Here is the code:</p> <pre><code>from multiprocessing import Process import time def f(name, n, m): if name == 'bob': time.sleep(2) print 'hello', name, ' ', n, m def h(): g(1, 2, 3) def g(a, s, d): p = Process(target=f, args=('bob', a, s,)) t = Process(target=f, args=('helen', s, d,)) p.start() t.start() t.join() p.join() print("END") if __name__ == '__main__': print("Start") h() </code></pre> <p>After that I used the same technique to my code and errors appeared. This is a part of the problematic code:</p> <pre><code>if __name__ == "__main__": night_crawler_steam() def night_crawler_steam(): . . . multi_processing(max_pages, url, dirname) . . . def multi_processing(max_pages, url, dirname): page = 1 while page &lt;= max_pages: my_url = str(url) + str(page) soup = my_soup(my_url) fgt = Process(target=find_game_titles, args=(soup, page, dirname,)) fl = Process(target=find_links, args=(soup, page, dirname,)) fgt.start() #&lt;-----------Here is the problem fl.start() fgt.join() fl.join() page += 1 def find_links(soup, page, dirname): . . . def find_game_titles(soup, page, dirname): . . . </code></pre> <p>When the interpreter reaches fgt.start() some errors appear:</p> <pre><code>Traceback (most recent call last): File "C:/Users/��������/Desktop/MY PyWORK/NightCrawler/NightCrawler.py", line 120, in &lt;module&gt; night_crawler_steam() File "C:/Users/��������/Desktop/MY PyWORK/NightCrawler/NightCrawler.py", line 23, in night_crawler_steam Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; multi_processing(max_pages, url, dirname) File "C:/Users/��������/Desktop/MY PyWORK/NightCrawler/NightCrawler.py", line 47, in multi_processing fgt.start() File "C:\Python27\lib\multiprocessing\process.py", line 130, in start self._popen = Popen(self) File "C:\Python27\lib\multiprocessing\forking.py", line 277, in __init__ File "C:\Python27\lib\multiprocessing\forking.py", line 381, in main dump(process_obj, to_child, HIGHEST_PROTOCOL) File "C:\Python27\lib\multiprocessing\forking.py", line 199, in dump self = load(from_parent) File "C:\Python27\lib\pickle.py", line 1384, in load ForkingPickler(file, protocol).dump(obj) File "C:\Python27\lib\pickle.py", line 224, in dump self.save(obj) File "C:\Python27\lib\pickle.py", line 331, in save self.save_reduce(obj=obj, *rv) File "C:\Python27\lib\pickle.py", line 425, in save_reduce return Unpickler(file).load() File "C:\Python27\lib\pickle.py", line 864, in load save(state) File "C:\Python27\lib\pickle.py", line 286, in save f(self, obj) # Call unbound method with explicit self File "C:\Python27\lib\pickle.py", line 655, in save_dict dispatch[key](self) File "C:\Python27\lib\pickle.py", line 886, in load_eof self._batch_setitems(obj.iteritems()) File "C:\Python27\lib\pickle.py", line 687, in _batch_setitems raise EOFError save(v) EOFError </code></pre> <p>This goes on and on till <code>RuntimeError: maximum recursion depth exceeded</code></p> <p>Any idea would be helpful!</p>
0
2016-08-26T11:07:27Z
39,166,000
<p>There seems to be a problem with <a href="https://docs.python.org/2/library/pickle.html" rel="nofollow">pickling</a> <code>soup</code> (see <a href="https://docs.python.org/2/library/multiprocessing.html#programming-guidelines" rel="nofollow">Programming Guidelines</a>) so a simple solution would be to move the call <code>my_soup(my_url)</code> into the target functions like so:</p> <pre><code>def multi_processing(max_pages, url, dirname): p=Pool() # using a pool is not necessary to fix your problem for page in xrange(1,max_pages+1): my_url = str(url) + str(page) p.apply_async(find_game_titles, (my_url, page, dirname)) p.apply_async(find_links, (my_url, page, dirname)) p.close() p.join() def find_links(url,page, dirname): soup=my_soup(url) #function body from before def find_game_titles(url, page, dirname): soup=my_soup(url) #function body from before </code></pre> <p>(Of course you can also pass soup in a pickle-able format but depending on what <code>my_soup</code> does exactly it might or might not be worth it.)</p> <p>While not totally necessary it is normal to put the <code>if __name__=="__main__":</code> part in the end of the file.</p> <p>Also you migth want to have a look at <a href="https://docs.python.org/2/library/multiprocessing.html#module-multiprocessing.pool" rel="nofollow">multiprocessing.Pool</a>'s other methods as they may fit better, depending on what your functions do. </p>
0
2016-08-26T12:09:17Z
[ "python", "python-2.7", "multiprocessing", "python-multiprocessing" ]
Define blender Propertys in a Cycle
39,164,889
<p>I am trying to define a number blender property that is the same as the face of a cube, without defyning them manually.</p> <p>So something like this:</p> <pre><code>atr = bpy.types.Scene for i in range(0,20): //Define a intProperty to do stuffs. </code></pre> <p>And the call them separately in the panel draw function, is it possible?</p>
0
2016-08-26T11:08:36Z
39,190,526
<p>There are two ways to add new properties to objects in blender. A simple dynamic way is to use <a href="https://www.blender.org/api/blender_python_api_current/info_quickstart.html#custom-properties" rel="nofollow">custom properties</a> by assigning a value to a key as if the object was a dictionary. This is the same as using the custom properties panel in the <a href="https://www.blender.org/manual/editors/properties/introduction.html" rel="nofollow">object properties</a>. To access this value in your script you keep using the dictionary style - <code>obj['myprop0']</code></p> <pre><code>import bpy obj = bpy.context.object for i in range(0,20): obj['myprop'+str(i)] = i </code></pre> <p>A more structured way that allows type checking so that you can for example only assign an int to the property, is to add the <a href="https://www.blender.org/api/blender_python_api_current/bpy.props.html" rel="nofollow">property to the object class definition</a>, these also show in the custom properties panel but show as "API Defined". To do this with generated property names means you want to execute a piece of code that you generate. This method creates a true property that you access the same as other properties in the class definition - <code>obj.myprop0</code></p> <pre><code>import bpy for i in range(0,20): cmd = 'bpy.types.Object.myprop{} = bpy.props.IntProperty()'.format(i) exec(compile(cmd, 'myprops', 'exec')) </code></pre> <p>Be aware that both approaches occupy the same namespace, so if you use the same property name in both methods you will be accessing the same property and both methods of displaying the property will work. The <code>bpy.props</code> definitions override the dictionary style properties.</p> <p>Each approach is accessed a little differently when displaying the property in a panel. For the dictionary style property you use <code>row.prop(obj,'["myprop'+str(i)+'"]')</code> while when using <code>bpy.props</code> you use <code>row.prop(obj,'myprop'+str(i))</code> - note that the first approach you use a property name that is contained in <code>[]</code> like accessing any dictionary value.</p> <pre><code>import bpy class myPanel(bpy.types.Panel): """Creates a Panel in the Object properties window""" bl_label = "My properties Panel" bl_idname = "OBJECT_PT_myprops" bl_space_type = 'PROPERTIES' bl_region_type = 'WINDOW' bl_context = "object" def draw(self, context): layout = self.layout obj = context.object row = layout.row() row.label('dynamic properties') for i in range(0,20): row = layout.row() row.prop(obj,'["myprop'+str(i)+'"]') row = layout.row() row.label('structured properties') for i in range(0,20): row = layout.row() row.prop(obj,'myprop'+str(i)) bpy.utils.register_class(myPanel) </code></pre>
0
2016-08-28T10:54:29Z
[ "python", "properties", "blender" ]
How install and use another version python(python 2.7) on linux with the default python version is python 2.6
39,164,943
<p>There is a default python version, namely python 2.6, on the GPU server with Linux OS. Now I want to install a new python version on the server from its source, namely python 2.7. I should not change the default python version since I am not the administrator and some reason. So what should I do? </p>
0
2016-08-26T11:11:19Z
39,165,141
<p>You can install your new version of Python. It should be accessible with the <code>python27</code> command (which may be a symbolic link). Then you will just have to check that the <code>python</code> symbolic link still points to <code>python26</code>.</p> <p>Doing this, <code>python</code> will keep on execute Python 2.6 while <code>python27</code> will execute Python 2.7</p>
0
2016-08-26T11:21:24Z
[ "python", "linux", "python-2.7" ]
How install and use another version python(python 2.7) on linux with the default python version is python 2.6
39,164,943
<p>There is a default python version, namely python 2.6, on the GPU server with Linux OS. Now I want to install a new python version on the server from its source, namely python 2.7. I should not change the default python version since I am not the administrator and some reason. So what should I do? </p>
0
2016-08-26T11:11:19Z
39,165,757
<p>You can use <code>virtualenv</code>, to execute your programm in an environment with python 2.7.</p> <p>Install <code>virtualenv</code> and <a href="https://virtualenvwrapper.readthedocs.io/en/latest/" rel="nofollow"><code>virtualenvwrapper</code></a> (for comfotable use.)</p> <p><code>mkvirtualenv -p &lt;your-python-version&gt;</code> would then start a virtual environment where the desired python version is the default.</p>
0
2016-08-26T11:57:15Z
[ "python", "linux", "python-2.7" ]
How install and use another version python(python 2.7) on linux with the default python version is python 2.6
39,164,943
<p>There is a default python version, namely python 2.6, on the GPU server with Linux OS. Now I want to install a new python version on the server from its source, namely python 2.7. I should not change the default python version since I am not the administrator and some reason. So what should I do? </p>
0
2016-08-26T11:11:19Z
39,174,922
<p>To build on Tryph's answer, you can install that new version to your home directory, then in a directory specified within your PATH (like in .bash_profile), you can point to that directory and within there create a sym-link that points to the new python.</p> <p>For instance, if you have a bin folder in your home directory that is specified in the path</p> <p> ln -s /bin/python ~/bin/python</p>
0
2016-08-26T21:34:34Z
[ "python", "linux", "python-2.7" ]
Pycharm py.test coverage 'Coverage' object has no attribute 'export'
39,164,944
<p>I'm trying to run a py.test with coverage in pycharm. On my home pc it works like a charm, however on my laptop I'm getting this stacktrace</p> <pre><code>/home/david/PycharmProjects/pyCardDeck/virtualenv/bin/python /opt/pycharm/helpers/coverage_runner/run_coverage.py run --omit=\"/opt/pycharm/helpers*\" /opt/pycharm/helpers/pycharm/pytestrunner.py -p pytest_teamcity /home/david/PycharmProjects/pyCardDeck tests Testing started at 13:15 ... ============================= test session starts ============================== platform linux -- Python 3.5.2, pytest-3.0.1, py-1.4.31, pluggy-0.3.1 rootdir: /home/david/PycharmProjects/pyCardDeck, inifile: plugins: cov-2.3.1 collected 35 items tests/test_card.py .. tests/test_deck.py ..............................Traceback (most recent call last): File "/opt/pycharm/helpers/coverage_runner/run_coverage.py", line 44, in &lt;module&gt; main() File "/home/david/PycharmProjects/pyCardDeck/virtualenv/lib/python3.5/site-packages/coverage/cmdline.py", line 753, in main ... ========================== 35 passed in 0.89 seconds =========================== status = CoverageScript().command_line(argv) File "/home/david/PycharmProjects/pyCardDeck/virtualenv/lib/python3.5/site-packages/coverage/cmdline.py", line 480, in command_line return self.do_run(options, args) File "/home/david/PycharmProjects/pyCardDeck/virtualenv/lib/python3.5/site-packages/coverage/cmdline.py", line 638, in do_run self.coverage.export() AttributeError: 'Coverage' object has no attribute 'export' Process finished with exit code 1 </code></pre> <p>Running py.test --cov manually works, so it's something inside of Pycharm magic. My laptop is running with Pycharm 2016.1.4 and coverage 4.2</p>
0
2016-08-26T11:11:23Z
39,187,098
<p>That line in cmdline.py should read <code>self.coverage.save()</code>. It's never said <code>export</code>. You should reinstall coverage.py. I have no idea what changed it.</p>
1
2016-08-28T00:55:30Z
[ "python", "pycharm", "py.test", "coverage.py" ]
referencing multiple lists and dictionaries in novelty ways
39,165,032
<p>first post so please forgive formatting etc.</p> <p>I was trying to create a program that gave an alarm time based on whether it was a week day / weekend and whether it was a vacation</p> <p>heres the code:</p> <pre><code>days = {0:"sun", 1:"mon", 2:"tue", 3:"wed", 4:"thurs", 5:"fri", 6:"sat", } types = {"weekdays": ["mon", "tue", "wed", "thurs", "fri"], "weekend": ["sun", "sat"] } times = {"7:00":"weekdays", "10:00":"weekend"} #vacation = False def alarm_clock(day, vacation): x = days[day] #for i in days: if vacation == False: y = list(times.keys())[list(times.values()).index()]#incomplete function that should return "weekend" or "weekday" based on input return (list(times.keys())[list(times.values()).index(#function that returns either "weekend" or weekday" here# y )]) ## checks the entered number in days; that value is then checked in both lists in types to see whether it is in "weekend" or "weekdays"; that value is then used to give the final time of alarm (7:00 or 10:00) </code></pre> <p>This is in python 3.4 and currently returns the error when alarm_clock(1,False) is entered into shell</p> <pre><code>TypeError: index() takes at least 1 argument (0 given) </code></pre> <p>i wasn't expecting this to work, Im looking for advice on how to do things differently.</p> <p>Im sorry if this is a stupid question, maybe im just bad and i should gitgud</p>
0
2016-08-26T11:16:22Z
39,167,083
<p>I give you credit for apologising for the formatting, but if you want people to help you with your code, they have to understand it.</p> <h3>Possible issue</h3> <p>I don't know if I see it correctly but on the line where <em>'y'</em> is defined, there is an empty <em>'.index()'</em> function ( possibly the one causing TypeErrors?)</p> <p>Idk really, since the code is half incomplete I can't be totally sure.</p>
0
2016-08-26T13:07:26Z
[ "python", "list", "dictionary" ]
Python help, reading and writing to a txt file
39,165,060
<p>I have posted the relevant part of my code below. Before that are just load functions, which I am pretty sure have no errors.</p> <p>I am recieving error</p> <pre><code>IndexError: list index out of range( "namestaj["Naziv"] = deon[1]") </code></pre> <p>Does anyone see something out of order?</p> <pre><code>#load furniture from a txt file def ucitajNamestaj(): listaNamestaja = open("namestaj.txt", "r").readlines() namestaj = [] for red in listaNamestaja: namestaj.append(stringToNamestaj(red)) return namestaj #String to Furniture, dictionary def stringToNamestaj(red): namestaj = {} deon = red.strip().split("|") namestaj["Sifra"] = deon[0] namestaj["Naziv"] = deon[1] namestaj["Boja"] = deon[2] namestaj["Kolicina"] = int(deon[3]) namestaj["Cena"] = float(deon[4]) namestaj["Kategorija"] = deon[5] namestaj["Dostupan"] = deon[6] return namestaj </code></pre>
-1
2016-08-26T11:17:39Z
39,165,299
<p>Couple of things first, try always to provide a <a href="http://stackoverflow.com/help/mcve">mcve</a> and make sure you use properly the SO code directives, otherwise your question is unreadable.</p> <p>Now, probably what's happening is your file has some empty lines and you're not skipping those, try this:</p> <pre><code>def ucitajNamestaj(): listaNamestaja = open("namestaj.txt", "r").readlines() namestaj = [] for red in listaNamestaja: if red.strip() == "": continue namestaj.append(stringToNamestaj(red)) return namestaj def stringToNamestaj(red): namestaj = {} deon = red.strip().split("|") namestaj["Sifra"] = deon[0] namestaj["Naziv"] = deon[1] namestaj["Boja"] = deon[2] namestaj["Kolicina"] = int(deon[3]) namestaj["Cena"] = float(deon[4]) namestaj["Kategorija"] = deon[5] namestaj["Dostupan"] = deon[6] return namestaj </code></pre>
0
2016-08-26T11:30:33Z
[ "python", "eclipse", "pydev" ]
What is the best way to split long line with several exceptions?
39,165,071
<p>Say I have next code:</p> <pre><code>try: ... except (some_lib.LongNameError1, lib.LongNameError2, lib.LongNameError3, lib.LongNameError3) as e: print str(e) </code></pre> <p>As you can see line with exceptions is too long.</p> <p>I need to split it to meet requirement about a maximum of line length of 79 characters and keep readability at the same time.</p> <p>Actually I've tried to look through standard library code examples but haven't find any suited example.</p>
0
2016-08-26T11:18:15Z
39,165,153
<p>You could take advantage of using parenthesis like this:</p> <pre><code>try: ... except (some_lib.LongNameError1, some_lib.LongNameError2, some_lib.LongNameError3, some_lib.LongNameError4, some_lib.LongNameErrorN) as e: ... </code></pre>
4
2016-08-26T11:22:01Z
[ "python", "python-2.7", "exception" ]
Taking mean along columns with masks in Python
39,165,078
<p>I have a 2D array containing data from some measurements. I have to take mean along each column considering good data only. Hence I have another 2D array of the same shape which contains 1s and 0s showing whether data at that (i,j) is good or bad. Some of the "bad" data can be nan as well.</p> <pre><code>def mean_exc_mask(x, mas): #x is the real data arrray #mas tells if the data at the location is good/bad sum_array = np.zeros(len(x[0])) avg_array = np.zeros(len(x[0])) items_array = np.zeros(len(x[0])) for i in range(0, len(x[0])): #We take a specific column first for j in range(0, len(x)): #And then parse across rows if mas[j][i]==0: #If the data is good sum_array[i]= sum_array[i] + x[j][i] items_array[i]=items_array[i] + 1 if items_array[i]==0: # If none of the data is good for a particular column avg_array[i] = np.nan else: avg_array[i] = float(sum_array[i])/items_array[i] return avg_array </code></pre> <p>I am getting all values as nan!</p> <p>Any ideas of what's going on wrong here or someother way?</p>
0
2016-08-26T11:18:39Z
39,165,283
<p>The code seems to work for me, but you can do it a whole lot simpler by using the build-in aggregation in Numpy:</p> <p><code>(x*(m==0)).sum(axis=0)/(m==0).sum(axis=0)</code></p> <p>I tried it with:</p> <p><code>x=np.array([[-0.32220561, -0.93043128, 0.37695923],[ 0.08824206, -0.86961453, -0.54558324],[-0.40942331, -0.60216952, 0.17834533]])</code> and <code>m=array([[1, 1, 0],[1, 0, 0],[1, 1, 1]])</code></p> <p>If you post example data, it is often easier to give a qualified answer.</p>
1
2016-08-26T11:29:10Z
[ "python", "arrays", "numpy", "mask" ]
How can I connect a git repository to heroku app
39,165,085
<p>I'm trying to connect my heroku app to git repository.And also I can't able to push an existing repository with heroku app.While I'm trying to push with</p> <pre><code>git push heroku master </code></pre> <p>I found </p> <pre><code>fatal: 'heroku' does not appear to be a git repository fatal: Could not read from remote repository. </code></pre> <p>How can I solve this?</p>
0
2016-08-26T11:19:08Z
39,170,238
<p>That error means that: in your current project you have not yet 'initialized' Heroku.</p> <p>Are you creating a NEW Heroku app? If so, you can run the following command to fix things:</p> <pre><code>heroku create </code></pre> <p>If you're trying to work with an EXISTING Heroku app, you need to setup your 'heroku remote' by doing the following:</p> <pre><code>git remote add heroku https://git.heroku.com/your-app-name.git </code></pre>
0
2016-08-26T15:54:14Z
[ "python", "heroku", "github" ]
drawing svg in python with paths not shapes or convert them
39,165,287
<p>I'm making a microscope filter generator, first it draws svg image then they are converted in 3D for 3d printing.</p> <p>I used 'svgwrite'</p> <p>However this librayry generates svg with shapes (line, circle, etc), at the time I didn't know but every 3D conversion librayry/softwares needs the svg to contain path.</p> <p>Is there a librayry that generates svg files with path (but allow me in the script to draw easily circles, lines, etc?) </p> <p>Or is there a way to convert those svg shape to svg path?</p> <p>example of my current svg with shape :</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;svg baseProfile="tiny" height="100%" version="1.2" width="100%" xmlns="http://www.w3.org/2000/svg" xmlns:ev="http://www.w3.org/2001/xml-events" xmlns:xlink="http://www.w3.org/1999/xlink"&gt; &lt;defs /&gt; &lt;circle cx="270" cy="270" fill="white" r="135.0" stroke="black" stroke-width="10" /&gt; &lt;circle cx="270" cy="270" r="25.0" /&gt; &lt;line stroke="black" stroke-width="10" x1="270" x2="270" y1="270" y2="135.0" /&gt; &lt;line stroke="black" stroke-width="10" x1="270" x2="405.0" y1="270" y2="347.9423" /&gt; &lt;line stroke="black" stroke-width="10" x1="270" x2="135.0" y1="270" y2="347.9423" /&gt; &lt;/svg&gt; </code></pre> <p>Thanks.</p> <p>PS : note that I have to do this programaticaly because I intend to generate a lot of filters.</p>
8
2016-08-26T11:29:25Z
39,206,499
<p>Line and Circle have a straightforward translation to a Path entity, using MoveTo/LineTo/EllipticalArc.</p> <p>It shouldn't be a great deal to just replace those lines in the Xml source and keep all the rest, with a home-made script.</p>
0
2016-08-29T12:35:05Z
[ "python", "svg" ]
drawing svg in python with paths not shapes or convert them
39,165,287
<p>I'm making a microscope filter generator, first it draws svg image then they are converted in 3D for 3d printing.</p> <p>I used 'svgwrite'</p> <p>However this librayry generates svg with shapes (line, circle, etc), at the time I didn't know but every 3D conversion librayry/softwares needs the svg to contain path.</p> <p>Is there a librayry that generates svg files with path (but allow me in the script to draw easily circles, lines, etc?) </p> <p>Or is there a way to convert those svg shape to svg path?</p> <p>example of my current svg with shape :</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;svg baseProfile="tiny" height="100%" version="1.2" width="100%" xmlns="http://www.w3.org/2000/svg" xmlns:ev="http://www.w3.org/2001/xml-events" xmlns:xlink="http://www.w3.org/1999/xlink"&gt; &lt;defs /&gt; &lt;circle cx="270" cy="270" fill="white" r="135.0" stroke="black" stroke-width="10" /&gt; &lt;circle cx="270" cy="270" r="25.0" /&gt; &lt;line stroke="black" stroke-width="10" x1="270" x2="270" y1="270" y2="135.0" /&gt; &lt;line stroke="black" stroke-width="10" x1="270" x2="405.0" y1="270" y2="347.9423" /&gt; &lt;line stroke="black" stroke-width="10" x1="270" x2="135.0" y1="270" y2="347.9423" /&gt; &lt;/svg&gt; </code></pre> <p>Thanks.</p> <p>PS : note that I have to do this programaticaly because I intend to generate a lot of filters.</p>
8
2016-08-26T11:29:25Z
39,300,480
<p>I have already written some stuff for my own needs to process some similar tasks with SVG elements, like evaluating of bounding boxes, transformations and so on. Thus, this task seems relatively simple for me to implement such a conversion. All you need for it is only knowledge of what paths "d" attribute consists from - there is actually a list of lines, eliptical arcs and bezier curves (you even do not need the most complicated latters). See this useful tutorial if you're interested in customization of this - <a href="http://tutorials.jenkov.com/svg/path-element.html" rel="nofollow">http://tutorials.jenkov.com/svg/path-element.html</a></p> <p>But when I had started to answering you, I found a recent ready-for-use library which seems perfectly fit on you needs. </p> <p>It is available using "pip install svgpathtools" (see manual there) — <a href="https://pypi.python.org/pypi/svgpathtools/" rel="nofollow">https://pypi.python.org/pypi/svgpathtools/</a></p> <p>So, you may initially create high-level objects, like</p> <pre><code>Line(start, end) Arc(start, radius, rotation, large_arc, sweep, end) # See docstring for a detailed explanation of these parameters, # but you're definetely able to create cirlces that way </code></pre> <p>And then just make a high-level Path object from them</p> <pre><code>path = Path(*segemnts) # segments are decribed above - Line(), Arc(), etc </code></pre> <p>Now you are able to get path.d() string and just build an XML representation using your desired attributes (stroke, stroke-width, etc), since the main svg-path data is stored exactly in "d" attribute, which value you are already have.</p> <p>In addition, your referred <em>svgwrite</em> lib also already provides a way to build XML representation</p> <pre><code>svgwrite.path.Path(d=path.d(), stroke='black', **extra) # **extra is every other common SVG attribute as keyword arguments </code></pre> <p>Probably even the <em>svgpathtools</em> itself has it (I hasn't figured all it advantages yet)</p> <p>Ask me in comment, please, if something is still unanswered.</p>
1
2016-09-02T20:46:36Z
[ "python", "svg" ]
Capturing screenshot and parsing data from the captured image
39,165,347
<p>I need to write a desktop application that performs the following operations. I'm thinking of using Python as the programming language, but I'd be more than glad to switch, if there's an appropriate approach or library in any other languages.</p> <p>The file I wish to capture is an HWP file, that only certain word processors can run.</p> <ol> <li><p>Capture the entire HWP document in an image, might span multiple pages (>10 and &lt;15)</p></li> <li><p>The HWP file contains an MCQ formatted quiz</p></li> <li><p>Parse the data from the image that is separate out the questions and answers and save them as separate image files.</p></li> </ol> <p>I have looked into the following python library, but am still not able to figure out how to perform both 1 and 3.</p> <p><a href="https://pypi.python.org/pypi/pyscreenshot" rel="nofollow">https://pypi.python.org/pypi/pyscreenshot</a></p> <p>Any help would be appreciated.</p>
0
2016-08-26T11:33:42Z
39,171,923
<p>If i got it correctly , you need to extract text from image. For this one you should use an OCR like tesseract. Before using an OCR, try to clear noises from image. To split the image try to add some unique strings to distinguish between the quiz Q/A</p>
0
2016-08-26T17:40:59Z
[ "python", "image", "parsing", "screenshot" ]
Why can I not grab certain tags using BeautifulSoup?
39,165,468
<p>I want to get the number of votes on quora answers(In this specific case the number "13"):</p> <p><a href="http://i.stack.imgur.com/scoHP.png" rel="nofollow">Image of the element I want to grab:</a></p> <p>What I have tried:</p> <pre><code>import requests from bs4 import BeautifulSoup url1 = "https://www.quora.com/Have-you-ever-made-your-dad-cry-If-so-how-and-what-did-you-do-afterwards" res = requests.get(url1) res.raise_for_status() soup = BeautifulSoup(res.content, "html.parser") z = soup.find('span', {'class': 'count'}) print(z) </code></pre> <p>I don't get anything. I have tried to get the parent tag but that didn't work either. However, this work on most other sites. What is going on here? </p>
1
2016-08-26T11:41:38Z
39,165,628
<p>You have the picture but not the data structure, so this may or may not be correct -- But based on previous BeautifulSoup issues try this:</p> <pre><code>z = soup.find('span', class_='count') </code></pre> <p>Depending on the content, print z probably won't work. It'll probably print an object identifier. print(z.text) is more likely to work</p>
0
2016-08-26T11:50:41Z
[ "python", "web-scraping", "beautifulsoup" ]
Why can I not grab certain tags using BeautifulSoup?
39,165,468
<p>I want to get the number of votes on quora answers(In this specific case the number "13"):</p> <p><a href="http://i.stack.imgur.com/scoHP.png" rel="nofollow">Image of the element I want to grab:</a></p> <p>What I have tried:</p> <pre><code>import requests from bs4 import BeautifulSoup url1 = "https://www.quora.com/Have-you-ever-made-your-dad-cry-If-so-how-and-what-did-you-do-afterwards" res = requests.get(url1) res.raise_for_status() soup = BeautifulSoup(res.content, "html.parser") z = soup.find('span', {'class': 'count'}) print(z) </code></pre> <p>I don't get anything. I have tried to get the parent tag but that didn't work either. However, this work on most other sites. What is going on here? </p>
1
2016-08-26T11:41:38Z
39,165,659
<p>It seems you need to be registered in Quora first, otherwise you <a href="http://screencast.com/t/yHAag3Fn" rel="nofollow">won't get directly</a> the information you're looking for, make sure that information is available to you first</p>
0
2016-08-26T11:52:07Z
[ "python", "web-scraping", "beautifulsoup" ]
Change values of a column in CSV file using python
39,165,533
<p>I am new to python and just need a small help.</p> <p>We have a Pipe delimited CSV file which looks like this </p> <pre><code>DATE|20160101 ID | Name | Address | City | State | Zip | Phone | OPEID | IPEDS | 10 | A... | 210 W.. | Mo.. | AL... | '31.. | 334.. | '01023 | 10063 | 20 | B... | 240 N.. | Ne.. | Ut... | '21.. | 335.. | '01024 | 10064 | </code></pre> <p>Every value of Zip and OPEID columns has apostrophes in the beginning </p> <p>So we wish to create a new CSV file where apostrophes are removed from each value of these 2 columns.</p> <p>The new file should then look like this:</p> <pre><code>DATE|20160101 ID | Name | Address | City | State | Zip | Phone | OPEID | IPEDS | 10 | A... | 210 W.. | Mo.. | AL... | 31.. | 334.. | 01023 | 10063 | 20 | B... | 240 N.. | Ne.. | Ut... | 21.. | 335.. | 01024 | 10064 | </code></pre> <p>This code works for copying data without removing apostrophes</p> <pre><code>import os import csv file1 = "D:\CSV\File1.csv" with open(file1, 'rb') as csvfile: reader = csv.reader(csvfile, delimiter = '|') path = "D:/CSV/New" if not os.path.exists(path): os.makedirs(path) writer = csv.writer(open(path+"File2"+".csv", 'wb'), delimiter = '|') for row in reader: writer.writerow(row) csvfile.close() </code></pre>
-1
2016-08-26T11:45:20Z
39,166,125
<p>The code below would be the same for all file formats. The fact that it is a *.csv doesn't change a thing. What it actually does, is that it goes in the file from which you want to remove the apostrophes, <code>my_csv_in</code>, and parses it line by line each time replacing them with nothing (a.k.a removing). The modified lines are written in a second file, <code>my_csv_out</code>.</p> <pre><code>my_csv_in = r'full_file_path_to_csv_in.csv' my_csv_out = r'full_file_path_to_csv_out.csv' with open(my_csv_in, 'r') as f_in: with open(my_csv_out, 'w') as f_out: for line in f_in: f_out.write(line.replace("'", '')) </code></pre> <p>There are probably better ways to do this that take advantage of the file being a *.csv and using the <code>csv</code> library. You can take a look at the <a href="https://docs.python.org/3/library/csv.html#csv.Dialect.quoting" rel="nofollow"><code>quoting options</code></a> in the <a href="https://docs.python.org/3/library/csv.html" rel="nofollow">documentation</a>.</p>
0
2016-08-26T12:15:18Z
[ "python", "csv" ]
Change values of a column in CSV file using python
39,165,533
<p>I am new to python and just need a small help.</p> <p>We have a Pipe delimited CSV file which looks like this </p> <pre><code>DATE|20160101 ID | Name | Address | City | State | Zip | Phone | OPEID | IPEDS | 10 | A... | 210 W.. | Mo.. | AL... | '31.. | 334.. | '01023 | 10063 | 20 | B... | 240 N.. | Ne.. | Ut... | '21.. | 335.. | '01024 | 10064 | </code></pre> <p>Every value of Zip and OPEID columns has apostrophes in the beginning </p> <p>So we wish to create a new CSV file where apostrophes are removed from each value of these 2 columns.</p> <p>The new file should then look like this:</p> <pre><code>DATE|20160101 ID | Name | Address | City | State | Zip | Phone | OPEID | IPEDS | 10 | A... | 210 W.. | Mo.. | AL... | 31.. | 334.. | 01023 | 10063 | 20 | B... | 240 N.. | Ne.. | Ut... | 21.. | 335.. | 01024 | 10064 | </code></pre> <p>This code works for copying data without removing apostrophes</p> <pre><code>import os import csv file1 = "D:\CSV\File1.csv" with open(file1, 'rb') as csvfile: reader = csv.reader(csvfile, delimiter = '|') path = "D:/CSV/New" if not os.path.exists(path): os.makedirs(path) writer = csv.writer(open(path+"File2"+".csv", 'wb'), delimiter = '|') for row in reader: writer.writerow(row) csvfile.close() </code></pre>
-1
2016-08-26T11:45:20Z
39,166,163
<p>To remove apostrophes you can use the <a href="https://docs.python.org/2/library/string.html" rel="nofollow">replace function</a>, you just need to get the content of every cell one by one, and replace the apostrophes with:</p> <pre><code>new = old.replace("'", "") </code></pre> <p>More simply, open your csv file with any file editor and search and replace for "'".</p>
0
2016-08-26T12:17:07Z
[ "python", "csv" ]
Change values of a column in CSV file using python
39,165,533
<p>I am new to python and just need a small help.</p> <p>We have a Pipe delimited CSV file which looks like this </p> <pre><code>DATE|20160101 ID | Name | Address | City | State | Zip | Phone | OPEID | IPEDS | 10 | A... | 210 W.. | Mo.. | AL... | '31.. | 334.. | '01023 | 10063 | 20 | B... | 240 N.. | Ne.. | Ut... | '21.. | 335.. | '01024 | 10064 | </code></pre> <p>Every value of Zip and OPEID columns has apostrophes in the beginning </p> <p>So we wish to create a new CSV file where apostrophes are removed from each value of these 2 columns.</p> <p>The new file should then look like this:</p> <pre><code>DATE|20160101 ID | Name | Address | City | State | Zip | Phone | OPEID | IPEDS | 10 | A... | 210 W.. | Mo.. | AL... | 31.. | 334.. | 01023 | 10063 | 20 | B... | 240 N.. | Ne.. | Ut... | 21.. | 335.. | 01024 | 10064 | </code></pre> <p>This code works for copying data without removing apostrophes</p> <pre><code>import os import csv file1 = "D:\CSV\File1.csv" with open(file1, 'rb') as csvfile: reader = csv.reader(csvfile, delimiter = '|') path = "D:/CSV/New" if not os.path.exists(path): os.makedirs(path) writer = csv.writer(open(path+"File2"+".csv", 'wb'), delimiter = '|') for row in reader: writer.writerow(row) csvfile.close() </code></pre>
-1
2016-08-26T11:45:20Z
39,166,199
<p>It worked for me... Try this.</p> <pre><code>res=[] with open('hi.csv','rb') as f: content=csv.reader(f,delimiter='|') for row in content: for str in range (len(row)): row[str]=row[str].replace('\'','') res.append(row) f.close() with open('hi.csv','wb') as ff: sw=csv.writer(ff,delimiter='|',quoting=csv.QUOTE_MINIMAL) for rows in res: sw.writerow(rows) ff.close() </code></pre>
0
2016-08-26T12:19:43Z
[ "python", "csv" ]
Change values of a column in CSV file using python
39,165,533
<p>I am new to python and just need a small help.</p> <p>We have a Pipe delimited CSV file which looks like this </p> <pre><code>DATE|20160101 ID | Name | Address | City | State | Zip | Phone | OPEID | IPEDS | 10 | A... | 210 W.. | Mo.. | AL... | '31.. | 334.. | '01023 | 10063 | 20 | B... | 240 N.. | Ne.. | Ut... | '21.. | 335.. | '01024 | 10064 | </code></pre> <p>Every value of Zip and OPEID columns has apostrophes in the beginning </p> <p>So we wish to create a new CSV file where apostrophes are removed from each value of these 2 columns.</p> <p>The new file should then look like this:</p> <pre><code>DATE|20160101 ID | Name | Address | City | State | Zip | Phone | OPEID | IPEDS | 10 | A... | 210 W.. | Mo.. | AL... | 31.. | 334.. | 01023 | 10063 | 20 | B... | 240 N.. | Ne.. | Ut... | 21.. | 335.. | 01024 | 10064 | </code></pre> <p>This code works for copying data without removing apostrophes</p> <pre><code>import os import csv file1 = "D:\CSV\File1.csv" with open(file1, 'rb') as csvfile: reader = csv.reader(csvfile, delimiter = '|') path = "D:/CSV/New" if not os.path.exists(path): os.makedirs(path) writer = csv.writer(open(path+"File2"+".csv", 'wb'), delimiter = '|') for row in reader: writer.writerow(row) csvfile.close() </code></pre>
-1
2016-08-26T11:45:20Z
39,166,470
<p>You can do it very efficiently with Pandas--this will be good if your file is very large:</p> <pre><code>import pandas as pd import sys with open('t.txt') as infile: title = next(infile) infile.seek(0) table = pd.read_csv(infile, '|', header=1, dtype=str) table.rename(columns={'Unnamed: 9':''}, inplace=True) table[' Zip '] = table[' Zip '].str.replace("'", "") table[' OPEID '] = table[' OPEID '].str.replace("'", "") sys.stdout.write(title) table.to_csv(sys.stdout, '|', index=False) </code></pre>
0
2016-08-26T12:33:02Z
[ "python", "csv" ]
Assert value for key in cookie dict
39,165,567
<p>I've just started working with python test automation, and I'm trying to assert that a certain cookie with a certain value is being set when clicking on a certain button. I'm automating tests using splinter, and so far I have this:</p> <pre><code>cookie_bar = browser.find_link_by_text('Yes') manage_cookies = browser.find_link_by_text('Manage cookies') if not manage_cookies: if cookie_bar: browser.find_link_by_text('Yes').first.click() else: browser.find_link_by_text('Hide this message').first.click() if manage_cookies: browser.find_link_by_text('Manage cookies').first.click() browser.driver.switch_to_window(browser.windows[-1].name) browser.find_by_text('Accept Cookies').first.click() browser.driver.switch_to_window(browser.windows[-1].name) cookies_list = browser.cookies.all() </code></pre> <p>The "browser.cookies.all()" method returns a dict of {'cookie1': 'value1', 'cookie2': 'value2', etc.}; I'm trying to assert that "cookie1" comes back with value "value1", but so far nothing I've tried has worked, as they all come with some sort of "unhashable" error:</p> <pre><code>assert ['cookie1' == 'value1'] in cookies_list # TypeError: unhashable type: 'list' assert [{'cookie1': 'value1'}] in cookies_list # TypeError: unhashable type: 'list' assert {'cookie1': 'value1'} in cookies_list # TypeError: unhashable type: 'dict' assert {'cookie1', 'value1'} in cookies_list #TypeError: unhashable type: 'set' </code></pre> <p>Now, I've never worked with python before, so maybe it's something really simple that's escaping me, but I can't for the life of me figure it out. I can assert them individually, but what I really need is, in the simplest terms:</p> <pre><code>assert 'cookie1' with value 'value1' in cookies_list </code></pre> <p>Is there a way to do that?</p>
0
2016-08-26T11:47:15Z
39,166,032
<p>You are saying that <code>browser.cookies.all()</code> return a dict, therefore, you should use it as a dict and not as a list.</p> <p>For example you can do:</p> <pre><code>assert cookies_list.get('cookie1', None) == 'value1' </code></pre> <p>Find some more info about dictionary <a href="https://docs.python.org/2/tutorial/datastructures.html#dictionaries" rel="nofollow">here</a></p> <p>To check multiples values: Create another dict we the expected values:</p> <pre><code>expected = {'cookie1': 'value1', 'cookie2': 'value2'} </code></pre> <p>Edit to improve answer: And then iterate on all keys of the dict.</p> <pre><code>for key in expected.keys(): assert cookies_list.get(key, None) == expected[key] </code></pre>
1
2016-08-26T12:11:13Z
[ "python", "cookies", "automated-tests", "splinter" ]
want to store elements in array or list using python
39,165,577
<p>I am learning python. I want to store one by one element in array or list. this is my code. </p> <pre><code>for u in durl: p2 = requests.get(u) tree = html.fromstring(p2.content) dcode.append = tree.xpath(ecode) print(dcode) </code></pre> <p>in dcode variable the elements are overriding not appending. i want to insert it one by one. please help me. </p>
0
2016-08-26T11:47:42Z
39,165,648
<p><code>tree.xpath(...)</code> returns a list so if you want to merge it with an existing list <code>dcode</code> of selected elements, you might do</p> <pre><code>dcode.extend(tree.xpath(ecode)) </code></pre>
0
2016-08-26T11:51:38Z
[ "python", "arrays", "list", "python-2.7" ]
want to store elements in array or list using python
39,165,577
<p>I am learning python. I want to store one by one element in array or list. this is my code. </p> <pre><code>for u in durl: p2 = requests.get(u) tree = html.fromstring(p2.content) dcode.append = tree.xpath(ecode) print(dcode) </code></pre> <p>in dcode variable the elements are overriding not appending. i want to insert it one by one. please help me. </p>
0
2016-08-26T11:47:42Z
39,165,856
<p>append is a method not a variable so if you want to append <code>tree.xpath(ecode)</code> to <code>dcode</code> then you should write <code>dcode.append(tree.xpath(ecode))</code> rather than <code>dcode.append =</code> which is an assignment not a method call.</p>
2
2016-08-26T12:02:13Z
[ "python", "arrays", "list", "python-2.7" ]
want to store elements in array or list using python
39,165,577
<p>I am learning python. I want to store one by one element in array or list. this is my code. </p> <pre><code>for u in durl: p2 = requests.get(u) tree = html.fromstring(p2.content) dcode.append = tree.xpath(ecode) print(dcode) </code></pre> <p>in dcode variable the elements are overriding not appending. i want to insert it one by one. please help me. </p>
0
2016-08-26T11:47:42Z
39,166,135
<p>You can do it this way, it appends new value to the list and it makes more sense...sort of data structure</p> <pre><code>def main(decode=[]): for u in durl: p2 = requests.get(u) tree = html.fromstring(p2.content) dcode.append(tree.xpath(ecode)) print(dcode) </code></pre>
0
2016-08-26T12:15:49Z
[ "python", "arrays", "list", "python-2.7" ]
How to send data to Python script from C#
39,165,595
<p>i have been experimented with Python from C# and i do not know how to execute a Python script and write It commands/data. I have been looking this link: "<a href="https://code.msdn.microsoft.com/windowsdesktop/C-and-Python-interprocess-171378ee" rel="nofollow">https://code.msdn.microsoft.com/windowsdesktop/C-and-Python-interprocess-171378ee</a>"</p> <p>But only show how to read Python script output, not how to write something once the script is open/execute.</p> <p>For example, i want to open a python script (from C Sharp) and send it some data from C # to a raw_input() función. </p> <p>Can you help me? Links, examples, all is welcome... I am lost now.</p> <p>PS: i dont want to use ironpython</p> <p>C# Example:</p> <pre><code>private void button1_Click(object sender, EventArgs e) { string python = @"C:\Python27\python.exe";; string myPythonApp = "myscript/test01.py"; ProcessStartInfo myProcessStartInfo = new ProcessStartInfo(python); myProcessStartInfo.UseShellExecute = false myProcessStartInfo.CreateNoWindow = true myProcessStartInfo.RedirectStandardOutput = true myProcessStartInfo.RedirectStandardInput = true; myProcessStartInfo.Arguments = myPythonApp; //&lt;&gt;//---------------ISSUE?-------------------------------- Process myProcessW = new Process(); Process myProcessR = new Process();// myProcessW.StartInfo = myProcessStartInfo; myProcessR.StartInfo = myProcessStartInfo; myProcessW.Start(); myProcessR.Start(); StreamWriter myStreamWriter = myProcessW.StandardInput; string inputText; inputText = textBox1.Text; myStreamWriter.WriteLine(inputText); // &lt;--OK! myProcessW.WaitForExit(); myProcessW.Close(); // StreamReader myStreamReader = myProcessR.StandardOutput; MessageBox.Show("01"); //For Debug, is executed string myString = myStreamReader.ReadLine(); MessageBox.Show("02"); //For Debug, is NOT executed label1.Text = myString; myProcessR.WaitForExit(); myProcessR.Close(); //&lt;&gt;//---------------/ISSUE?-------------------------------- } </code></pre> <p>Python Example (myscript/test01.py) :</p> <pre><code> aaa = raw_input("&gt; ") print "Ok, you say:",aaa </code></pre> <p>IMPORTANT Update: I found if i set "myProcessStartInfo.RedirectStandardInput = false", "RedirectStandardOutput" will work, but i will not write...</p>
4
2016-08-26T11:48:48Z
39,165,894
<p>Do you need that the C# program and the python one work at the same time? If no, you can gather all the data from the C# program and send them to the python script either as arguments in the command line, or in a file that the two programs share.</p> <p>To use arguments in a python script you can use the <a href="https://docs.python.org/2/library/argparse.html#module-argparse" rel="nofollow">argparse module</a>.</p>
0
2016-08-26T12:04:01Z
[ "c#", "python" ]
Zipline: momentum pipeline example - TypeError: a float is required
39,165,596
<p>I have been trying to run the example on Zipline called <code>momentum_pipeline.py</code>. It is just not running properly, I'm calling the following on terminal:</p> <pre><code>python -m zipline run -f momentum_pipeline.py --start 2000-1-1 --end 2014-1-1 --output pipeline.pickle </code></pre> <p>The output is an error on Terminal saying <code>TypeError: a float is required.</code></p> <p>This is the error log on the screenshot:</p> <p><a href="http://i.stack.imgur.com/eNHKF.png" rel="nofollow"><img src="http://i.stack.imgur.com/eNHKF.png" alt="enter image description here"></a></p> <p>The error seems to relate to this line in the file:</p> <pre><code> File "momentum_pipeline.py", line 68, in before_trading_start context.pipeline_data = pipeline_output('my_pipeline') </code></pre> <p>Not sure why it refers to a TypeError related to a float. That line should return a panda dataFrame. You can view the file on github here: <a href="https://github.com/quantopian/zipline/blob/master/zipline/examples/momentum_pipeline.py" rel="nofollow">https://github.com/quantopian/zipline/blob/master/zipline/examples/momentum_pipeline.py</a></p> <p>How do I run this example successfully?</p>
0
2016-08-26T11:48:49Z
39,264,953
<p>I think the date range I was using was too long (from 2000 - 2014) therefore some of the data was not available. I think Quantopian only has stock market data from 2002 only. If you change the date range to the ones found on the test_args, the example will work:</p> <pre><code>return { # We run through october of 2013 because DELL is in the test data and # it went private on 2013-10-29. 'start': pd.Timestamp('2013-10-07', tz='utc'), 'end': pd.Timestamp('2013-11-30', tz='utc'), 'capital_base': 100000, } </code></pre>
0
2016-09-01T07:13:31Z
[ "python", "zipline" ]
Using Forms in Django - Adding people to a specific date
39,165,670
<p>I've searched the site, which has been extremely helpful with other issues being that I'm new to Django. I can't seem to figure out how to add people to a date/event. </p> <p><a href="http://i.stack.imgur.com/g2OC2.png" rel="nofollow">Models</a></p> <pre><code>class PeopleList(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) phone_number = models.CharField(null='True', max_length=12) MALE = 'M' FEMALE = 'F' GENDER_CHOICES = ( (MALE, 'Male'), (FEMALE, 'Female'), ) gender = models.CharField( max_length=6, choices=GENDER_CHOICES, ) def __str__(self): return "%s %s" % (self.first_name, self.last_name) class Date(models.Model): HARDWARE_SHOW = 'Hardware Show' METAL_SHOW = 'Metal Show' MEETING_NAME_CHOICES = ( (HARDWARE_SHOW, 'Hardware Show'), (METAL_SHOW, 'Metal Show'), ) meeting_name = models.CharField( max_length=50, choices=MEETING_NAME_CHOICES, ) date_of_meeting = models.DateField() def __str__(self): return "%s - %s" % (self.meeting_name, self.date_of_meeting) class MeetingAttendance(models.Model): meeting_date = models.ForeignKey('Date', on_delete=models.CASCADE) person = models.ForeignKey('PeopleList', on_delete=models.CASCADE) attended = models.BooleanField() def __str__(self): return "%s - %s" % (self.person, self.meeting_date) </code></pre> <p>My models are a PeopleList (which is people we'd invite to each event). The form for this works great and I can add people to this growing list. The Date model shows Dates that we will have events. The form for this works well since I can continue to add more dates of events. And the MeetingAttendance is the model where I'd like to add people to a date so I can see who went to the event, but when I create a form for it, it isn't coming out how I'd like. It gives me dropdowns since I'm using Foreign Key, but I just want everyone's names (non-editable), the meeting date (non-editable), and then a checkbox to click off if they came or not.</p> <p>What I'm trying to do is be able to open up an event date (and I don't believe I'm routing the date to url correctly, but thats a separate issue), see a list of everyone on our PeopleList and then check-off if they attended to event or not. From there, on the same page (further down) I'd like to show the actual attendance to that specific event (PeopleList who attended that specific date). I kept changing around my detail view, and now it's a bit of a mess.</p> <p><a href="http://i.stack.imgur.com/p7L1x.png" rel="nofollow">Event Detail View</a></p> <pre><code>def meeting_detail(request, pk): attended = MeetingAttendance.objects.filter(meeting_date__pk=pk, attended='True') people = PeopleList.objects.all().order_by('last_name') if request.method == "POST": form = MeetingFormSet(request.POST) if form.is_valid(): formset = form.save(commit=False) formset.save() return redirect('meeting_detail', pk=pk) else: form = MeetingFormSet() context = { 'form': form, 'attended': attended, 'people': people, } return render(request, 'statistics/meeting_detail.html', context) </code></pre> <p>URLs</p> <pre><code>urlpatterns = [ url(r'^$', views.date_list, name='date_list'), url(r'^meeting/(?P&lt;pk&gt;\d+)/$', views.meeting_detail, name='meeting_detail'), url(r'^date/new/$', views.date_new, name='date_new'), </code></pre> <p>Forms:</p> <pre><code>class DateForm(forms.ModelForm): class Meta: model = Date fields = ('meeting_name', 'date_of_meeting',) class MeetingForm(forms.ModelForm): class Meta: model = PeopleList fields = ('first_name', 'last_name', 'phone_number', 'gender',) </code></pre> <p>Any ideas on the easiest way to put this together based on what I currently have?</p> <p>Thank you!</p>
0
2016-08-26T11:52:46Z
39,165,939
<p>If i understand you correctly, you want to sort by date and check people on the list based on the date... you can use django order by to do that( query based on date and fetch people that matches, let me know if you need practical proof so i can add it.</p>
0
2016-08-26T12:06:12Z
[ "python", "django" ]
Using Forms in Django - Adding people to a specific date
39,165,670
<p>I've searched the site, which has been extremely helpful with other issues being that I'm new to Django. I can't seem to figure out how to add people to a date/event. </p> <p><a href="http://i.stack.imgur.com/g2OC2.png" rel="nofollow">Models</a></p> <pre><code>class PeopleList(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) phone_number = models.CharField(null='True', max_length=12) MALE = 'M' FEMALE = 'F' GENDER_CHOICES = ( (MALE, 'Male'), (FEMALE, 'Female'), ) gender = models.CharField( max_length=6, choices=GENDER_CHOICES, ) def __str__(self): return "%s %s" % (self.first_name, self.last_name) class Date(models.Model): HARDWARE_SHOW = 'Hardware Show' METAL_SHOW = 'Metal Show' MEETING_NAME_CHOICES = ( (HARDWARE_SHOW, 'Hardware Show'), (METAL_SHOW, 'Metal Show'), ) meeting_name = models.CharField( max_length=50, choices=MEETING_NAME_CHOICES, ) date_of_meeting = models.DateField() def __str__(self): return "%s - %s" % (self.meeting_name, self.date_of_meeting) class MeetingAttendance(models.Model): meeting_date = models.ForeignKey('Date', on_delete=models.CASCADE) person = models.ForeignKey('PeopleList', on_delete=models.CASCADE) attended = models.BooleanField() def __str__(self): return "%s - %s" % (self.person, self.meeting_date) </code></pre> <p>My models are a PeopleList (which is people we'd invite to each event). The form for this works great and I can add people to this growing list. The Date model shows Dates that we will have events. The form for this works well since I can continue to add more dates of events. And the MeetingAttendance is the model where I'd like to add people to a date so I can see who went to the event, but when I create a form for it, it isn't coming out how I'd like. It gives me dropdowns since I'm using Foreign Key, but I just want everyone's names (non-editable), the meeting date (non-editable), and then a checkbox to click off if they came or not.</p> <p>What I'm trying to do is be able to open up an event date (and I don't believe I'm routing the date to url correctly, but thats a separate issue), see a list of everyone on our PeopleList and then check-off if they attended to event or not. From there, on the same page (further down) I'd like to show the actual attendance to that specific event (PeopleList who attended that specific date). I kept changing around my detail view, and now it's a bit of a mess.</p> <p><a href="http://i.stack.imgur.com/p7L1x.png" rel="nofollow">Event Detail View</a></p> <pre><code>def meeting_detail(request, pk): attended = MeetingAttendance.objects.filter(meeting_date__pk=pk, attended='True') people = PeopleList.objects.all().order_by('last_name') if request.method == "POST": form = MeetingFormSet(request.POST) if form.is_valid(): formset = form.save(commit=False) formset.save() return redirect('meeting_detail', pk=pk) else: form = MeetingFormSet() context = { 'form': form, 'attended': attended, 'people': people, } return render(request, 'statistics/meeting_detail.html', context) </code></pre> <p>URLs</p> <pre><code>urlpatterns = [ url(r'^$', views.date_list, name='date_list'), url(r'^meeting/(?P&lt;pk&gt;\d+)/$', views.meeting_detail, name='meeting_detail'), url(r'^date/new/$', views.date_new, name='date_new'), </code></pre> <p>Forms:</p> <pre><code>class DateForm(forms.ModelForm): class Meta: model = Date fields = ('meeting_name', 'date_of_meeting',) class MeetingForm(forms.ModelForm): class Meta: model = PeopleList fields = ('first_name', 'last_name', 'phone_number', 'gender',) </code></pre> <p>Any ideas on the easiest way to put this together based on what I currently have?</p> <p>Thank you!</p>
0
2016-08-26T11:52:46Z
39,166,699
<p>Code your form like this</p> <pre><code>#### forms.py from django import form from app.models import PeopleList, Date class CustomForm(forms.Form): person = forms.ModelField(queryset=PeopleList.Objects.all()) date = forms.ModelField(queryset=Date.Objects.all()) #### views.py from app.forms import CustomForm from app.models import MeetingAttendance def savePeopleAndDate(request): form = CustomForm(request.POST or None) if form.is_valid(): people = form.cleaned_data['person'] date = form.cleaned_data['date'] # dumb to database newMeeting = MeetingAttendance(meeting_date=date, person=person) newMeeting.save() return render(request, locals()) </code></pre>
0
2016-08-26T12:45:38Z
[ "python", "django" ]
Django Photologue zip upload keep images names
39,165,686
<p>I'm working on photologue and till now it's perfect. I just want to know how can I keep the images names when uploading zip images.</p> <p>Here is a the code of the save function after the zip file upload. :</p> <pre><code> def save(self, request=None, zip_file=None): if not zip_file: zip_file = self.cleaned_data['zip_file'] zip = zipfile.ZipFile(zip_file) count = 1 current_site = Site.objects.get(id=settings.SITE_ID) if self.cleaned_data['gallery']: logger.debug('Using pre-existing gallery.') gallery = self.cleaned_data['gallery'] else: logger.debug( force_text('Creating new gallery "{0}".').format(self.cleaned_data['title'])) gallery = Gallery.objects.create(title=self.cleaned_data['title'], slug=slugify(self.cleaned_data['title']), description=self.cleaned_data['description'], is_public=self.cleaned_data['is_public']) gallery.sites.add(current_site) for filename in sorted(zip.namelist()): logger.debug('Reading file "{0}".'.format(filename)) if filename.startswith('__') or filename.startswith('.'): logger.debug('Ignoring file "{0}".'.format(filename)) continue if os.path.dirname(filename): logger.warning('Ignoring file "{0}" as it is in a subfolder; all images should be in the top ' 'folder of the zip.'.format(filename)) if request: messages.warning(request, _('Ignoring file "{filename}" as it is in a subfolder; all images should ' 'be in the top folder of the zip.').format(filename=filename), fail_silently=True) continue data = zip.read(filename) if not len(data): logger.debug('File "{0}" is empty.'.format(filename)) continue photo_title_root = self.cleaned_data['title'] if self.cleaned_data['title'] else gallery.title # A photo might already exist with the same slug. So it's somewhat inefficient, # but we loop until we find a slug that's available. while True: photo_title = ' '.join([photo_title_root, str(count)]) slug = slugify(photo_title) if Photo.objects.filter(slug=slug).exists(): count += 1 continue break photo = Photo(title=photo_title, slug=slug, caption=self.cleaned_data['caption'], is_public=self.cleaned_data['is_public']) # Basic check that we have a valid image. try: file = BytesIO(data) opened = Image.open(file) opened.verify() except Exception: # Pillow (or PIL) doesn't recognize it as an image. # If a "bad" file is found we just skip it. # But we do flag this both in the logs and to the user. logger.error('Could not process file "{0}" in the .zip archive.'.format( filename)) if request: messages.warning(request, _('Could not process file "{0}" in the .zip archive.').format( filename), fail_silently=True) continue contentfile = ContentFile(data) photo.image.save(filename, contentfile) photo.save() photo.sites.add(current_site) gallery.photos.add(photo) count += 1 zip.close() if request: messages.success(request, _('The photos have been added to gallery "{0}".').format( gallery.title), fail_silently=True) </code></pre> <p>It's changing the images names to the title. like title_1.jpg title_2.jpg etc ... and I want the name of the initial name of each image inside the zip file<br> Please If you can help me in this </p> <p>Thank you very much </p>
0
2016-08-26T11:53:45Z
39,167,948
<p>I solved it Finally the code became as below if one want's to get benefit from my solution for this problem .</p> <pre><code>def save(self, request=None, zip_file=None): if not zip_file: zip_file = self.cleaned_data['zip_file'] zip = zipfile.ZipFile(zip_file) count = 1 current_site = Site.objects.get(id=settings.SITE_ID) if self.cleaned_data['gallery']: logger.debug('Using pre-existing gallery.') gallery = self.cleaned_data['gallery'] else: logger.debug( force_text('Creating new gallery "{0}".').format(self.cleaned_data['title'])) gallery = Gallery.objects.create(title=self.cleaned_data['title'], slug=slugify(self.cleaned_data['title']), description=self.cleaned_data['description'], is_public=self.cleaned_data['is_public']) gallery.sites.add(current_site) for filename in sorted(zip.namelist()): logger.debug('Reading file "{0}".'.format(filename)) if filename.startswith('__') or filename.startswith('.'): logger.debug('Ignoring file "{0}".'.format(filename)) continue if os.path.dirname(filename): logger.warning('Ignoring file "{0}" as it is in a subfolder; all images should be in the top ' 'folder of the zip.'.format(filename)) if request: messages.warning(request, _('Ignoring file "{filename}" as it is in a subfolder; all images should ' 'be in the top folder of the zip.').format(filename=filename), fail_silently=True) continue data = zip.read(filename) if not len(data): logger.debug('File "{0}" is empty.'.format(filename)) continue photo_title_root = self.cleaned_data['title'] if self.cleaned_data['title'] else gallery.title # A photo might already exist with the same slug. So it's somewhat inefficient, # but we loop until we find a slug that's available. while True: </code></pre> <blockquote> <pre><code> filename = filename[0:-4] photo_title = filename </code></pre> </blockquote> <pre><code> slug = slugify(photo_title) if Photo.objects.filter(slug=slug).exists(): count += 1 continue break photo = Photo(title=photo_title, slug=slug, caption=self.cleaned_data['caption'], is_public=self.cleaned_data['is_public']) # Basic check that we have a valid image. try: file = BytesIO(data) opened = Image.open(file) opened.verify() except Exception: # Pillow (or PIL) doesn't recognize it as an image. # If a "bad" file is found we just skip it. # But we do flag this both in the logs and to the user. logger.error('Could not process file "{0}" in the .zip archive.'.format( filename)) if request: messages.warning(request, _('Could not process file "{0}" in the .zip archive.').format( filename), fail_silently=True) continue contentfile = ContentFile(data) photo.image.save(filename, contentfile) photo.save() photo.sites.add(current_site) gallery.photos.add(photo) count += 1 zip.close() if request: messages.success(request, _('The photos have been added to gallery "{0}".').format( gallery.title), fail_silently=True) </code></pre>
0
2016-08-26T13:50:09Z
[ "python", "django", "photologue" ]
Ball Tracker using OpenCV, Python, Raspberry Pi 3
39,165,715
<p>I have tried to run this script on my Raspberry Pi however I keep encountering an attribute error. <strong>Any help or indication as to what the problem might be would be much appreciated.</strong></p> <h1>Here is the error:</h1> <pre><code>Traceback (most recent call last): File "/home/pi/ball-tracking/ball_tracking.py", line 48, in &lt;module&gt; frame = imutils.resize(frame, width=600) File "/usr/local/lib/python2.7/dist-packages/imutils/convenience.py", line 45, in resize (h, w) = image.shape[:2] AttributeError: 'NoneType' object has no attribute 'shape' </code></pre> <h1>Here is my code:</h1> <pre><code># python ball_tracking.py --video ball_tracking_example.mp4 # python ball_tracking.py # import the necessary packages from collections import deque import numpy as np import argparse import imutils import cv2 # construct the argument parse and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-v", "--video", help="path to the (optional) video file") ap.add_argument("-b", "--buffer", type=int, default=64, help="max buffer size") args = vars(ap.parse_args()) # define the lower and upper boundaries of the "green" # ball in the HSV color space, then initialize the # list of tracked points greenLower = (29, 86, 6) greenUpper = (64, 255, 255) pts = deque(maxlen=args["buffer"]) # if a video path was not supplied, grab the reference # to the webcam if not args.get("video", False): camera = cv2.VideoCapture(0) # otherwise, grab a reference to the video file else: camera = cv2.VideoCapture(args["video"]) # keep looping while True: # grab the current frame (grabbed, frame) = camera.read() # if we are viewing a video and we did not grab a frame, # then we have reached the end of the video if args.get("video") and not grabbed: break # resize the frame, blur it, and convert it to the HSV # color space frame = imutils.resize(frame, width=600) # blurred = cv2.GaussianBlur(frame, (11, 11), 0) hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) # construct a mask for the color "green", then perform # a series of dilations and erosions to remove any small # blobs left in the mask mask = cv2.inRange(hsv, greenLower, greenUpper) mask = cv2.erode(mask, None, iterations=2) mask = cv2.dilate(mask, None, iterations=2) # find contours in the mask and initialize the current # (x, y) center of the ball cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2] center = None # only proceed if at least one contour was found if len(cnts) &gt; 0: # find the largest contour in the mask, then use # it to compute the minimum enclosing circle and # centroid c = max(cnts, key=cv2.contourArea) ((x, y), radius) = cv2.minEnclosingCircle(c) M = cv2.moments(c) center = (int(M["m10"] / M["m00"]), int(M["m01"] / M["m00"])) # only proceed if the radius meets a minimum size if radius &gt; 10: # draw the circle and centroid on the frame, # then update the list of tracked points cv2.circle(frame, (int(x), int(y)), int(radius), (0, 255, 255), 2) cv2.circle(frame, center, 5, (0, 0, 255), -1) # update the points queue pts.appendleft(center) # loop over the set of tracked points for i in xrange(1, len(pts)): # if either of the tracked points are None, ignore # them if pts[i - 1] is None or pts[i] is None: continue # otherwise, compute the thickness of the line and # draw the connecting lines thickness = int(np.sqrt(args["buffer"] / float(i + 1)) * 2.5) cv2.line(frame, pts[i - 1], pts[i], (0, 0, 255), thickness) # show the frame to our screen cv2.imshow("Frame", frame) key = cv2.waitKey(1) &amp; 0xFF # if the 'q' key is pressed, stop the loop if key == ord("q"): break # cleanup the camera and close any open windows camera.release() cv2.destroyAllWindows() </code></pre>
0
2016-08-26T11:55:00Z
39,166,176
<p>It seems that <code>frame</code> was returned as <code>None</code> in this line as if you camera couldn't read an image:</p> <pre><code>(grabbed, frame) = camera.read() </code></pre> <p>Then, when resizing a <code>None</code> object, the program blows up as we described in the error message <code>AttributeError: 'NoneType' object has no attribute 'shape'</code>:</p> <pre><code>frame = imutils.resize(frame, width=600) </code></pre> <p>As discussed in <a href="http://stackoverflow.com/questions/21043394/opencvs-video-capture-not-returning-an-image">this thread</a>, some camera drivers may return <code>False, None</code> in the first frame. A possible workaround would be to verify whether <code>grabbed</code> is <code>False</code> and ignore this frame.</p> <pre><code>while True: grabbed, frame = camera.read() if not grabbed: continue # the rest of the program </code></pre>
1
2016-08-26T12:17:47Z
[ "python", "opencv", "computer-vision", "raspberry-pi3" ]
Ball Tracker using OpenCV, Python, Raspberry Pi 3
39,165,715
<p>I have tried to run this script on my Raspberry Pi however I keep encountering an attribute error. <strong>Any help or indication as to what the problem might be would be much appreciated.</strong></p> <h1>Here is the error:</h1> <pre><code>Traceback (most recent call last): File "/home/pi/ball-tracking/ball_tracking.py", line 48, in &lt;module&gt; frame = imutils.resize(frame, width=600) File "/usr/local/lib/python2.7/dist-packages/imutils/convenience.py", line 45, in resize (h, w) = image.shape[:2] AttributeError: 'NoneType' object has no attribute 'shape' </code></pre> <h1>Here is my code:</h1> <pre><code># python ball_tracking.py --video ball_tracking_example.mp4 # python ball_tracking.py # import the necessary packages from collections import deque import numpy as np import argparse import imutils import cv2 # construct the argument parse and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-v", "--video", help="path to the (optional) video file") ap.add_argument("-b", "--buffer", type=int, default=64, help="max buffer size") args = vars(ap.parse_args()) # define the lower and upper boundaries of the "green" # ball in the HSV color space, then initialize the # list of tracked points greenLower = (29, 86, 6) greenUpper = (64, 255, 255) pts = deque(maxlen=args["buffer"]) # if a video path was not supplied, grab the reference # to the webcam if not args.get("video", False): camera = cv2.VideoCapture(0) # otherwise, grab a reference to the video file else: camera = cv2.VideoCapture(args["video"]) # keep looping while True: # grab the current frame (grabbed, frame) = camera.read() # if we are viewing a video and we did not grab a frame, # then we have reached the end of the video if args.get("video") and not grabbed: break # resize the frame, blur it, and convert it to the HSV # color space frame = imutils.resize(frame, width=600) # blurred = cv2.GaussianBlur(frame, (11, 11), 0) hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) # construct a mask for the color "green", then perform # a series of dilations and erosions to remove any small # blobs left in the mask mask = cv2.inRange(hsv, greenLower, greenUpper) mask = cv2.erode(mask, None, iterations=2) mask = cv2.dilate(mask, None, iterations=2) # find contours in the mask and initialize the current # (x, y) center of the ball cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2] center = None # only proceed if at least one contour was found if len(cnts) &gt; 0: # find the largest contour in the mask, then use # it to compute the minimum enclosing circle and # centroid c = max(cnts, key=cv2.contourArea) ((x, y), radius) = cv2.minEnclosingCircle(c) M = cv2.moments(c) center = (int(M["m10"] / M["m00"]), int(M["m01"] / M["m00"])) # only proceed if the radius meets a minimum size if radius &gt; 10: # draw the circle and centroid on the frame, # then update the list of tracked points cv2.circle(frame, (int(x), int(y)), int(radius), (0, 255, 255), 2) cv2.circle(frame, center, 5, (0, 0, 255), -1) # update the points queue pts.appendleft(center) # loop over the set of tracked points for i in xrange(1, len(pts)): # if either of the tracked points are None, ignore # them if pts[i - 1] is None or pts[i] is None: continue # otherwise, compute the thickness of the line and # draw the connecting lines thickness = int(np.sqrt(args["buffer"] / float(i + 1)) * 2.5) cv2.line(frame, pts[i - 1], pts[i], (0, 0, 255), thickness) # show the frame to our screen cv2.imshow("Frame", frame) key = cv2.waitKey(1) &amp; 0xFF # if the 'q' key is pressed, stop the loop if key == ord("q"): break # cleanup the camera and close any open windows camera.release() cv2.destroyAllWindows() </code></pre>
0
2016-08-26T11:55:00Z
40,133,332
<p>The 'NoneType' error indicated that a frame was not passed to the resize function. When using the cv2.capture method one must ensure that the correct drivers are loaded otherwise you will end up with the same NoneType error.</p> <p>The solution is to manually add the driver to etc/modules or to enter the following command:</p> <pre><code>sudo modprobe bcm2835-v4l2 </code></pre> <p>A simple command that loads the V4L2 drivers.</p>
1
2016-10-19T13:50:34Z
[ "python", "opencv", "computer-vision", "raspberry-pi3" ]
Duplicate column name 'model_id' django mysql error on migrate
39,165,779
<p>I am using Django and MySQL on my VPS. Whenever I run <code>python manage.py migrate</code> I get the following error. But on my development server I use sqlite, and migrate works fine.</p> <pre><code>Running migrations: Rendering model states... DONE Applying bloupergroups.0002_auto_20160826_1138...Traceback (most recent call last): File "manage.py", line 10, in &lt;module&gt; execute_from_command_line(sys.argv) File "/home/ashish/Env/bloup/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line utility.execute() File "/home/ashish/Env/bloup/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 345, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/ashish/Env/bloup/local/lib/python2.7/site-packages/django/core/management/base.py", line 348, in run_from_argv self.execute(*args, **cmd_options) File "/home/ashish/Env/bloup/local/lib/python2.7/site-packages/django/core/management/base.py", line 399, in execute output = self.handle(*args, **options) File "/home/ashish/Env/bloup/local/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 200, in handle executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial) File "/home/ashish/Env/bloup/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 92, in migrate self._migrate_all_forwards(plan, full_plan, fake=fake, fake_initial=fake_initial) File "/home/ashish/Env/bloup/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 121, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/home/ashish/Env/bloup/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 198, in apply_migration state = migration.apply(state, schema_editor) File "/home/ashish/Env/bloup/local/lib/python2.7/site-packages/django/db/migrations/migration.py", line 123, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/home/ashish/Env/bloup/local/lib/python2.7/site-packages/django/db/migrations/operations/fields.py", line 62, in database_forwards field, File "/home/ashish/Env/bloup/local/lib/python2.7/site-packages/django/db/backends/mysql/schema.py", line 50, in add_field super(DatabaseSchemaEditor, self).add_field(model, field) File "/home/ashish/Env/bloup/local/lib/python2.7/site-packages/django/db/backends/base/schema.py", line 396, in add_field self.execute(sql, params) File "/home/ashish/Env/bloup/local/lib/python2.7/site-packages/django/db/backends/base/schema.py", line 110, in execute cursor.execute(sql, params) File "/home/ashish/Env/bloup/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/home/ashish/Env/bloup/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/home/ashish/Env/bloup/local/lib/python2.7/site-packages/django/db/utils.py", line 95, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/home/ashish/Env/bloup/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/home/ashish/Env/bloup/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 112, in execute return self.cursor.execute(query, args) File "/home/ashish/Env/bloup/local/lib/python2.7/site-packages/MySQLdb/cursors.py", line 226, in execute self.errorhandler(self, exc, value) File "/home/ashish/Env/bloup/local/lib/python2.7/site-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler raise errorvalue django.db.utils.OperationalError: (1060, "Duplicate column name 'blouper_id'") </code></pre> <p>I do not understand what the problem is here.</p>
0
2016-08-26T11:58:28Z
39,169,467
<p>Django is probably trying to apply migrations that have already been applied.</p> <p>Try running <code>python manage.py migrate --fake-initial</code></p> <p>From the docs:</p> <blockquote> <p>--fake-initial Allows Django to skip an app’s initial migration if all database tables with the names of all models created by all CreateModel operations in that migration already exist. This option is intended for use when first running migrations against a database that preexisted the use of migrations. This option does not, however, check for matching database schema beyond matching table names and so is only safe to use if you are confident that your existing schema matches what is recorded in your initial migration.</p> </blockquote>
0
2016-08-26T15:10:55Z
[ "python", "mysql", "django", "sqlite", "django-models" ]
How to use `pip` and setup.py to automatically install dependencies that may be private repositories hosted on github
39,165,976
<p>I don't think this is a dupicate, because I tried all links I could find for the past 2 hours and none of the solutions worked. I want the user to be able to clone a repository, <code>cd</code> into the directory, and run <code>$ pip install .</code> (or at least <code>pip install --process-dependency-links .</code>) to install the package, its pypi dependencies <strong>AND</strong> its (latest) <strong>private</strong> github dependencies assuming the user has read permissions for them. (also the devs should be able to run <code>$ pip install -e .</code>)</p> <p>my <code>setup.py</code>:</p> <pre><code>setup ( ... install_requires=[' ... private-pkg ... ], dependency_links=[ 'git+ssh://git@github.com/private-org/private-pkg.git@master#egg=private-pkg'], ) </code></pre> <p>I also tried different variations for dependency_links:</p> <ul> <li><code>https://github.com/private-org/private-pkg/tarball/master#egg=private-pkg</code></li> <li><code>git+https://git@github.com/private-org/private-pkg.git@master#egg=private-pkg</code></li> </ul> <p>I also tried adding a trailing <code>-1.0.0</code> (for version) and it doesn't work but in any case, I'd like the user to be able to install the lastest version</p> <p>Note that I can do:</p> <p><code>pip install "git+https://github.com/private-org/private-pkg"</code> and it works fine, but I can't get <code>pip install .</code> to work no matter what.</p> <p>All these fail with the same error:</p> <p><code>Could not find a version that satisfies the requirement private-pkg (from my-pkg==1.0.0) (form versions: ) No matching distribution found for private-pkg (from my-pkg==1.0.0)</code></p> <p>Running it with <code>pip install -vvv .</code> shows that <code>pip</code> never looks for the git link, but running it with <code>pip install --process-dependency-links -vvv .</code> tries to fetch it but fails for various reasons ("Cannot look at git URL", or "Could not fetch URL"). Note that <code>--process-dependency-links</code> is marked as deprecated.</p>
1
2016-08-26T12:07:44Z
39,494,943
<p>pip expects to have a link to index page (such as PyPI) in <code>dependency_links</code>. Any link to VCS is going to be skipped. This behavior was changed in commit <a href="https://github.com/pypa/pip/commit/26facddaa81be3447b8e06a9886c03b90fd68309" rel="nofollow">26facdd</a>.</p> <p>I recommend to define all external dependencies in <code>requirements.txt</code> file and then run <code>pip install -r requirements.txt</code>. Example of requirements.txt:</p> <pre><code>foo&gt;=1.0 -e git+ssh://git@github.com/private-org/private-pkg.git@master#egg=private-pkg </code></pre> <p>See also <a href="http://stackoverflow.com/questions/16584552/how-to-state-in-requirements-txt-a-direct-github-source">How to state in requirements.txt a direct github source</a></p> <p>There is an article about <a href="https://caremad.io/posts/2013/07/setup-vs-requirement/#a-setuptools-misfeature" rel="nofollow">setup.py vs requirements.txt</a>, which describes this misfeature.</p>
1
2016-09-14T15:59:43Z
[ "python", "pip", "setuptools", "packaging", "setup.py" ]
converting appended images list in Pandas dataframe
39,165,992
<p>I have a list which I created after appending the images from a folder </p> <pre><code>samples=[] for filename in glob.glob(path + '/*.png'): samples.append(misc.imread(filename)) </code></pre> <p>And a sample of the list looks like </p> <pre><code>[array([[ 4, 4, 4, ..., 5, 5, 4], [ 5, 5, 5, ..., 6, 6, 5], [ 5, 5, 5, ..., 6, 6, 4], ..., [12, 12, 11, ..., 12, 12, 7], [12, 11, 11, ..., 13, 12, 7], [11, 11, 10, ..., 12, 12, 7]], dtype=uint8), array([[ 4, 4, 4, ..., 7, 7, 6], [ 5, 5, 5, ..., 6, 6, 4], [ 5, 5, 5, ..., 7, 7, 5]], dtype=uint8)] </code></pre> <p>How it convert the image's dimensions in a Pandas DataFrame. when I tried to do it with </p> <pre><code>df=pd.DataFrame(samples) </code></pre> <p>It gives me an error </p> <pre><code>ValueError: Must pass 2-d input </code></pre> <p>Please Suggest- I will appreciate every help</p>
0
2016-08-26T12:08:49Z
39,166,939
<p>Try converting it into a pandas <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Panel.html" rel="nofollow">panel</a></p> <pre><code>import cv2 img = cv2.imread('path/Picture_1.png') imgPanel = pd.Panel(img) </code></pre> <p>For more info see: <a href="http://pandas-docs.github.io/pandas-docs-travis/dsintro.html#panel" rel="nofollow">Panel- Introduction</a>, <a href="http://pandas-docs.github.io/pandas-docs-travis/whatsnew.html#n-dimensional-panels-experimental" rel="nofollow">n-dimensional Panel (Experimental)</a>, <a href="http://pandas-docs.github.io/pandas-docs-travis/cookbook.html#panels" rel="nofollow">Cookbook- Panel</a>, <a href="http://pandas-docs.github.io/pandas-docs-travis/cookbook.html#panelnd" rel="nofollow">Panel-nd cookbook</a></p>
0
2016-08-26T12:59:11Z
[ "python", "pandas", "dataframe", "scipy" ]
converting appended images list in Pandas dataframe
39,165,992
<p>I have a list which I created after appending the images from a folder </p> <pre><code>samples=[] for filename in glob.glob(path + '/*.png'): samples.append(misc.imread(filename)) </code></pre> <p>And a sample of the list looks like </p> <pre><code>[array([[ 4, 4, 4, ..., 5, 5, 4], [ 5, 5, 5, ..., 6, 6, 5], [ 5, 5, 5, ..., 6, 6, 4], ..., [12, 12, 11, ..., 12, 12, 7], [12, 11, 11, ..., 13, 12, 7], [11, 11, 10, ..., 12, 12, 7]], dtype=uint8), array([[ 4, 4, 4, ..., 7, 7, 6], [ 5, 5, 5, ..., 6, 6, 4], [ 5, 5, 5, ..., 7, 7, 5]], dtype=uint8)] </code></pre> <p>How it convert the image's dimensions in a Pandas DataFrame. when I tried to do it with </p> <pre><code>df=pd.DataFrame(samples) </code></pre> <p>It gives me an error </p> <pre><code>ValueError: Must pass 2-d input </code></pre> <p>Please Suggest- I will appreciate every help</p>
0
2016-08-26T12:08:49Z
40,058,708
<p>Try adding .reshape(-1) while appending an image. </p> <pre><code>for filename in glob.glob(path + '/*.png'): samples.append(misc.imread(filename).reshape(-1)) df = pd.DataFrame.from_records(samples) </code></pre> <p>If you want to 3d version please read <a href="http://stackoverflow.com/questions/6627647/reshaping-a-numpy-array-in-python">Reshaping a numpy array in python</a></p>
0
2016-10-15T11:55:00Z
[ "python", "pandas", "dataframe", "scipy" ]
Can't create an SQL Table in Python using input as name
39,166,102
<p>I have a little issue with my python code. I want to take the input from user and based on that create an SQL table with that name. I take the input in table_name variable and want to do it so:</p> <pre><code>sql = "CREATE TABLE %s" % table_name cur.execute(sql) </code></pre> <p>Let's say I run it with input "books". I get this error:</p> <blockquote> <p>File "XXX", line 55, in FUNCTIONNAME<br> cur.execute(sql)<br> sqlite3.OperationalError: near "books": syntax error</p> </blockquote> <p>Any ideas on what is wrong? I googled it and above code should be OK, but it isn't...</p>
1
2016-08-26T12:13:59Z
39,166,151
<p>That's most probably cause you are not passing the table definition (column names and their type , size). What I see from posted code is that you are passing only table name and so your query becomes below which is totally wrong</p> <pre><code>CREATE TABLE books </code></pre>
4
2016-08-26T12:16:25Z
[ "python", "sql", "sqlite" ]
Connection refused error in python socket (stream)?
39,166,156
<p>My script is launching multiple clients in a machine-1 and tries to connect to a server running on different machines on a specific port. These machines running the server are launched by boto3 and then wait for 5 min for the instances to be in running state. Then a sftp connection is made to transfer files. Then through ssh the server script is executed. Then when multiple clients are launched in machine-1, and it tries to connect to the server, only one connection established and others got connection refused error <code>ConnectionRefusedError</code>. </p> <p>Here is my code:</p> <p>Client:</p> <pre><code>def Client(datas): client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect((datas[0], 81)) datasent =''+datas[1]+'-'+datas[2]+'#' client.send(datasent.encode("UTF-8")) for dataToRun in dataForMP: hp = Process(target=Client, args=(dataToRun,)) hp.start() hp.join() </code></pre> <p>Server:</p> <pre><code>if __name__ == '__main__': sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.setblocking(0) sock.bind(("", 81)) sock.listen(128) </code></pre> <p>I am launching <code>t1.micro</code> instances for server. I have also waited for 10 min before starting the client and server after launching the instances but I'm getting the same error. </p>
0
2016-08-26T12:16:38Z
39,245,447
<p>The issue was regarding the time mismatch between starting the server and client. Actually its takes little while to start the server and in the meantime the client request to connect. So I put a 2 sec delay before starting the client and the issue resolved.</p>
0
2016-08-31T09:14:18Z
[ "python", "sockets", "amazon-web-services", "boto" ]
How to apply a transformation to a certain tonal range in VIPS/Python
39,166,164
<p>I have to apply various transformations to different tonal ranges of 16-bit tiff files in VIPS (and Python). I have managed to do so, but I am new to VIPS and I am not convinced I am doing this in an efficient manner. These images are several hundred megabytes each, and cutting each excess step can save me a few seconds per image. </p> <p>I wonder if there is a more efficient way to achieve the same results I obtain from the code below, for instance using lookup tables (I couldn't really figure out how they work in VIPS). The code separates the shadows in the red channel and passes them through a transformation. </p> <pre><code>im = Vips.Image.new_from_file("test.tiff") # Separate the red channel band = im[0] # Find the tone limit for the bottom 5% lim = band.percent(5) # Create a mask using the tone limit mask = (band &lt;= lim) # Convert the mask to 16 bits mask = mask.cast(band.BandFmt, shift = True) # Run the transformation on the image and keep only the shadow areas new_shadows = (65535 * (shadows / lim * 0.1)) &amp; mask </code></pre> <p>After running more or less similar codes for each tonal range (highlight, shadows, midtones, I add all the resulting images together to reconstruct the original band:</p> <pre><code>new_band = (new_shadows.add(new_highlights).add(new_midtones)).cast(band.BandFmt) </code></pre>
1
2016-08-26T12:17:12Z
39,492,969
<p>I made you a demo program showing how to do something like this with the vips histogram functions:</p> <pre><code>#!/usr/bin/python import sys import gi gi.require_version('Vips', '8.0') from gi.repository import Vips im = Vips.Image.new_from_file(sys.argv[1]) # find the image histogram # # we'll get a uint image, one pixel high and 256 or # 65536 pixels across, it'll have three bands for an RGB image source hist = im.hist_find() # find the normalised cumulative histogram # # for a 16-bit source, we'll have 65535 as the right-most element in each band norm = hist.hist_cum().hist_norm() # search from the left for the first pixel &gt; 5%: the position of this pixel # will give us the pixel value that 5% of pixels fall below # # .profile() gives back a pair of [column-profile, row-profile], we want index 1 # one. .getpoint() reads out a pixel as a Python array, so for an RGB Image # we'll have something like [19.0, 16.0, 15.0] in shadows shadows = (norm &gt; 5.0 / 100.0 * norm.width).profile()[1].getpoint(0, 0) # Now make an identity LUT that matches our original image lut = Vips.Image.identity(bands = im.bands, ushort = im.format == Vips.BandFormat.USHORT) # do something to the shadows ... here we just brighten them a lot lut = (lut &lt; shadows).ifthenelse(lut * 100, lut) # make sure our lut is back in the original format, then map the image through # it im = im.maplut(lut.cast(im.format)) im.write_to_file(sys.argv[2]) </code></pre> <p>It does a single find-histogram operation on the source image, then a single map-histogram operation, so it should be fast.</p> <p>This is just adjusting the shadows, you'll need to extend it slightly to do midtones and highlights as well, but you can do all three modifications from the single initial histogram, so it shouldn't be any slower. </p> <p>Please open an issue on the libvips tracker if you have any more questions:</p> <p><a href="https://github.com/jcupitt/libvips/issues" rel="nofollow">https://github.com/jcupitt/libvips/issues</a></p>
2
2016-09-14T14:26:54Z
[ "python", "image-processing", "vips" ]
Create csv file in python
39,166,256
<p>I created one program in python in which I used collaborative filtering to find Item based CF. My code is,</p> <pre><code># Create a placeholder items for closes neighbours to an item data_neighbours = pd.DataFrame(index=data_ibs.columns,columns=[range(1,13)]) print data_neighbours # Loop through our similarity dataframe and fill in neighbouring item names for i in range(0,len(data_ibs.columns)): ##use sort_values(...) data_neighbours.ix[i,:10] = data_ibs.ix[0:,i].sort_values(ascending=[1, 0])[:10].index data_neighbours.ix[i,:10] = data_ibs.ix[0:,i].sort_values(ascending=[1, 0])[:10].index print data_neighbours.ix[i,:10] Output is in table: user 1 2 3 0 192. c1s1b1p3 c1s1b1p4 c1s1b1p5 1 192. c1s1b1p3 c1s1b1p4 c1s1b1p5 2 192. c1s1b1p3 c1s1b1p4 c1s1b1p5 3 192. c1s1b1p3 c1s1b1p4 c1s1b1p5 4 192. c1s1b1p7 c1s1b1p8 c1s1b1p10 5 192 c1s1b1p5 c1s1b1p6 c1s1b1p7 6 192. c1s1b1p3 c1s1b1p4 c1s1b1p5 7 192. c1s1b1p8 c1s1b1p9 c1s1b1p4 8 192. c1s1b1p6 c1s1b1p10 c1s1b1p5 9 192. c1s1b1p3 c1s1b1p5 c1s1b1p7 10 192. c1s1b1p6 c1s1b1p8 c1s1b1p9 </code></pre> <p>This is table display on cmd prompt I want to save this table in csv file. How I can create csv file to store this table.</p>
0
2016-08-26T12:22:24Z
39,166,327
<p>You should consider to use the <a href="https://docs.python.org/2/library/csv.html" rel="nofollow">csv module</a>. In the documentation there is all the explanations and examples you need to create your csv file.</p>
0
2016-08-26T12:25:52Z
[ "python" ]
Create csv file in python
39,166,256
<p>I created one program in python in which I used collaborative filtering to find Item based CF. My code is,</p> <pre><code># Create a placeholder items for closes neighbours to an item data_neighbours = pd.DataFrame(index=data_ibs.columns,columns=[range(1,13)]) print data_neighbours # Loop through our similarity dataframe and fill in neighbouring item names for i in range(0,len(data_ibs.columns)): ##use sort_values(...) data_neighbours.ix[i,:10] = data_ibs.ix[0:,i].sort_values(ascending=[1, 0])[:10].index data_neighbours.ix[i,:10] = data_ibs.ix[0:,i].sort_values(ascending=[1, 0])[:10].index print data_neighbours.ix[i,:10] Output is in table: user 1 2 3 0 192. c1s1b1p3 c1s1b1p4 c1s1b1p5 1 192. c1s1b1p3 c1s1b1p4 c1s1b1p5 2 192. c1s1b1p3 c1s1b1p4 c1s1b1p5 3 192. c1s1b1p3 c1s1b1p4 c1s1b1p5 4 192. c1s1b1p7 c1s1b1p8 c1s1b1p10 5 192 c1s1b1p5 c1s1b1p6 c1s1b1p7 6 192. c1s1b1p3 c1s1b1p4 c1s1b1p5 7 192. c1s1b1p8 c1s1b1p9 c1s1b1p4 8 192. c1s1b1p6 c1s1b1p10 c1s1b1p5 9 192. c1s1b1p3 c1s1b1p5 c1s1b1p7 10 192. c1s1b1p6 c1s1b1p8 c1s1b1p9 </code></pre> <p>This is table display on cmd prompt I want to save this table in csv file. How I can create csv file to store this table.</p>
0
2016-08-26T12:22:24Z
39,166,477
<pre><code>with open('hi.csv','wb') as ff: sw=csv.writer(ff,delimiter=',',quoting=csv.QUOTE_MINIMAL) for rows in data_neighbours: sw.writerow(rows) </code></pre> <p>data_neighbours must contain lists in row wise....</p>
0
2016-08-26T12:33:24Z
[ "python" ]
Comparing lists containing NaNs
39,166,292
<p>I am trying to compare two different lists to see if they are equal, and was going to remove NaNs, only to discover that my list comparisons still work, despite <code>NaN == NaN -&gt; False</code>. </p> <p>Could someone explain why the following evaluate <code>True</code> or <code>False</code>, as I am finding this behavior unexpected. Thanks,</p> <p>I have read the following which don't seem to resolve the issue:</p> <ul> <li><a href="http://stackoverflow.com/questions/20320022/why-in-numpy-nan-nan-is-false-while-nan-in-nan-is-true">Why in numpy <code>nan == nan</code> is False while nan in [nan] is True?</a></li> <li><a href="http://stackoverflow.com/questions/10034149/why-is-nan-not-equal-to-nan">Why is NaN not equal to NaN? [duplicate]</a></li> </ul> <p>(Python 2.7.3, numpy-1.9.2)</p> <p><strong>I have marked surprising evaluations with a <code>*</code> at the end</strong></p> <pre><code>&gt;&gt;&gt; nan = np.nan &gt;&gt;&gt; [1,2,3]==[3] False &gt;&gt;&gt; [1,2,3]==[1,2,3] True &gt;&gt;&gt; [1,2,nan]==[1,2,nan] True *** &gt;&gt;&gt; nan == nan False &gt;&gt;&gt; [nan] == [nan] True *** &gt;&gt;&gt; [nan, nan] == [nan for i in range(2)] True *** &gt;&gt;&gt; [nan, nan] == [float(nan) for i in range(2)] True *** &gt;&gt;&gt; float(nan) is (float(nan) + 1) False &gt;&gt;&gt; float(nan) is float(nan) True *** </code></pre>
3
2016-08-26T12:24:18Z
39,166,585
<p>To understand what happens here, simply replace <code>nan = np.nan</code> by <code>foo = float('nan')</code>, you will get exactly the same result, why?</p> <pre><code>&gt;&gt;&gt; foo = float('nan') &gt;&gt;&gt; foo is foo # This is obviously True! True &gt;&gt;&gt; foo == foo # This is False per the standard (nan != nan). False &gt;&gt;&gt; bar = float('nan') # foo and bar are two different objects. &gt;&gt;&gt; foo is bar False &gt;&gt;&gt; foo is float(foo) # "Tricky", but float(x) is x if type(x) == float. True </code></pre> <p>Now think that <code>numpy.nan</code> is just a variable name that holds a <code>float('nan')</code>.</p> <p>Now why <code>[nan] == [nan]</code> is simply because <code>list</code> comparison first test identity equality between items before equality for value, think of it as:</p> <pre><code>def equals(l1, l2): for u, v in zip(l1, l2): if u is not v and u != v: return False return True </code></pre>
1
2016-08-26T12:39:29Z
[ "python", "list", "comparison", null ]