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 |
|---|---|---|---|---|---|---|---|---|---|
New numpy array from attribute of objects in another numpy array | 37,714,320 | <p>Is there a way to do an element-wise attribute extraction from a numpy array? For example, say I have:</p>
<pre><code>import numpy as np
class foo():
def __init__(self, value):
self.bar = value
obj_array = np.empty((2, 2), dtype='object')
for i in range(obj_array.shape[0]):
for j in range(obj_arra... | 0 | 2016-06-08T23:01:33Z | 37,714,694 | <p>I think the fastest way will be to combine Python's <code>operator.attrgetter</code> with numpy's <code>np.frompyfunction</code> - the first gives a fast, native code inlined, way to retrieve an object's attribute. The second, transforms an ordinary Python function into a Numpy's broadcast function, which can proce... | 1 | 2016-06-08T23:41:23Z | [
"python",
"numpy"
] |
Numpy einsum broadcasting | 37,714,462 | <p>Can someone please explain how broadcasting (ellipsis) works in the numpy.einsum() function?</p>
<p>Some examples to show how and when it can be used would be greatly appreciated.</p>
<p>I've checked the following official documentation page but there are only 2 examples and I can't seem to understand how to inter... | 2 | 2016-06-08T23:15:48Z | 37,714,579 | <p>The ellipses are a shorthand roughly standing for "all the remaining axes not explicitly mentioned". For example, suppose you had an array of shape (2,3,4,5,6,6):</p>
<pre><code>import numpy as np
arr = np.random.random((2,3,4,5,6,6))
</code></pre>
<p>and you wish to take a trace along its last two axes:</p>
<pre... | 4 | 2016-06-08T23:28:51Z | [
"python",
"numpy",
"numpy-einsum"
] |
Wand + ImageMagick + Anaconda: "'wand' has no attribute 'image'" | 37,714,467 | <p>I'm having issues using these three together. I believe wand is not recognizing the ImageMagick libraries but I'm not sure.</p>
<p>Environment:
Python 3.5.1 :: Anaconda 4.0.0 (64-bit)
Windows 7</p>
<p>Set up instructions I took:</p>
<ol>
<li>Installed ImageMagick-6.9.4-Q8 (x64) with the "C/C++ development
headers... | 1 | 2016-06-08T23:16:04Z | 37,724,640 | <p>Try this</p>
<pre class="lang-py prettyprint-override"><code>from wand.image import Image
with Image(filename=source_file, resolution=(RESOLUTION, RESOLUTION)) as img:
pass
</code></pre>
<blockquote>
<p>Is there something I'm missing? Why is wand not working correctly?</p>
</blockquote>
<p>I believe it is ... | 1 | 2016-06-09T11:25:41Z | [
"python",
"windows",
"imagemagick",
"anaconda",
"wand"
] |
python - iteration by date and time - half hour | 37,714,602 | <p>I think about how to iterate by data and time in following way: </p>
<pre><code>2016-06-10,00:00
2016-06-10,01:30
2016-06-10,02:00
2016-06-10,02:30
....
</code></pre>
<p>Can somebody help me ?</p>
| 2 | 2016-06-08T23:30:46Z | 37,715,379 | <pre><code>import datetime
from datetime import timedelta
format = "%Y-%m-%d,%H:%M"
start = datetime.datetime(2016, 6, 10, 0, 0)
minutes = 0
for i in range(6):
print (start + timedelta(minutes=minutes)).strftime(format)
minutes += 30
</code></pre>
<p>Output:</p>
<pre><code>$ python timespan.py
2016-06-1... | 3 | 2016-06-09T01:11:18Z | [
"python"
] |
python - iteration by date and time - half hour | 37,714,602 | <p>I think about how to iterate by data and time in following way: </p>
<pre><code>2016-06-10,00:00
2016-06-10,01:30
2016-06-10,02:00
2016-06-10,02:30
....
</code></pre>
<p>Can somebody help me ?</p>
| 2 | 2016-06-08T23:30:46Z | 37,715,533 | <p>Use <code>timedelta</code> to generate a range of <code>datetime</code> objects:</p>
<pre><code>from datetime import timedelta, datetime
start_date = datetime(2016, 6, 9, 5, 0, 0)
for td in (start_date + timedelta(minutes=30*it) for it in xrange(10)):
print td.strftime("%Y-%m-%d,%H:%M")
</code></pre>
<p>Outpu... | 2 | 2016-06-09T01:33:17Z | [
"python"
] |
Can a set() be shared between Python processes? | 37,714,680 | <p>I am using multiprocessing in Python 2.7 to process a very large set of data. As each process runs, it adds integers to a shared mp.Manager.Queue(), but only if some other process hasn't already added the same integer. Since you can't do an "in"-style membership test for Queues, the way I'm doing it is to check each... | 1 | 2016-06-08T23:39:28Z | 37,714,759 | <p>An obvious tweak is to use an <code>mp.Manager.dict()</code> instead of the set, and use arbitrary values (say, set <code>the_dict[result_int] = 1</code> to indicate membership in the set). BTW, this is how "everyone" implemented sets before Python added the <code>set</code> type, and even now dicts and sets are im... | 7 | 2016-06-08T23:49:33Z | [
"python",
"set",
"multiprocessing"
] |
simplify code using a list in python | 37,714,768 | <p>I have a line of python code that basically asigns a integer to a string (one letter). Since I use if statements, it need a lot of code lines... Is there a way I could simplify my code using a list so that it doesn't take up 63 lines of code? Here's my code:</p>
<pre><code>if character in " ":
character = 0
el... | 3 | 2016-06-08T23:50:36Z | 37,714,792 | <p>Use a <em>dict</em> with <em>str.lower</em>:</p>
<pre><code>d = {" ":0, "a": 1, "b": 2, ......,"'":30}
character = d.get(character.lower(), 0)
</code></pre>
<p>If <em>character</em> is not in the dict the default value will be <code>0</code>although I don't see the logic of setting a space to 0 and also having th... | 1 | 2016-06-08T23:54:21Z | [
"python"
] |
simplify code using a list in python | 37,714,768 | <p>I have a line of python code that basically asigns a integer to a string (one letter). Since I use if statements, it need a lot of code lines... Is there a way I could simplify my code using a list so that it doesn't take up 63 lines of code? Here's my code:</p>
<pre><code>if character in " ":
character = 0
el... | 3 | 2016-06-08T23:50:36Z | 37,714,817 | <p>There's no reason to code all those letters a-z by hand...
If it's alpha, subtract 97 from the ord, otherwise <code>.get()</code> from the dict with a default of 0 if its not in the dict</p>
<pre><code>specialChars = {" " : 0, "." : 27, "," : 28, "?" : 29, "'" : 30}
char = "'"
if char.isalpha():
print(ord(char.... | 1 | 2016-06-08T23:56:27Z | [
"python"
] |
simplify code using a list in python | 37,714,768 | <p>I have a line of python code that basically asigns a integer to a string (one letter). Since I use if statements, it need a lot of code lines... Is there a way I could simplify my code using a list so that it doesn't take up 63 lines of code? Here's my code:</p>
<pre><code>if character in " ":
character = 0
el... | 3 | 2016-06-08T23:50:36Z | 37,714,818 | <p>Put all of the characters into one big string where the characters' positions in that string are the values you want to assign. You can handle upper and lowercase letters by converting the input to lowercase first.</p>
<pre><code>value = " abcdefghijklmnopqrstuvwxyz.,?'".find(character.lower())
</code></pre>
| 3 | 2016-06-08T23:56:29Z | [
"python"
] |
simplify code using a list in python | 37,714,768 | <p>I have a line of python code that basically asigns a integer to a string (one letter). Since I use if statements, it need a lot of code lines... Is there a way I could simplify my code using a list so that it doesn't take up 63 lines of code? Here's my code:</p>
<pre><code>if character in " ":
character = 0
el... | 3 | 2016-06-08T23:50:36Z | 37,714,823 | <p>Here's the basic idea:</p>
<pre><code>character = ord(character.lower()) - ord('a') + 1 if character != ' ' else 0
</code></pre>
<p>You can adapt it to your particular requirements on the input. Since you didn't specify the acceptable domain of input values, I'm assuming that input is limited to what's in your exa... | 0 | 2016-06-08T23:57:34Z | [
"python"
] |
simplify code using a list in python | 37,714,768 | <p>I have a line of python code that basically asigns a integer to a string (one letter). Since I use if statements, it need a lot of code lines... Is there a way I could simplify my code using a list so that it doesn't take up 63 lines of code? Here's my code:</p>
<pre><code>if character in " ":
character = 0
el... | 3 | 2016-06-08T23:50:36Z | 37,714,889 | <p>I would use a <code>dict</code> like so:</p>
<pre><code>In [0]: import string
In [1]: keys = list(" ") + list(string.ascii_lowercase)
In [2]: dict = {}
In [3]: for v, k in enumerate(keys): dict[k] = v
In [4]: def getCharVal(character): return dict.get(character.lower(), -1)
In [5]: getCharVal("B")
Out[5]: 2
</... | 0 | 2016-06-09T00:05:33Z | [
"python"
] |
simplify code using a list in python | 37,714,768 | <p>I have a line of python code that basically asigns a integer to a string (one letter). Since I use if statements, it need a lot of code lines... Is there a way I could simplify my code using a list so that it doesn't take up 63 lines of code? Here's my code:</p>
<pre><code>if character in " ":
character = 0
el... | 3 | 2016-06-08T23:50:36Z | 37,716,628 | <p>You can Simply set range by setting ASCII value using ord() function and then find index using index() function.</p>
<pre><code>TestCase='T'
# Make all Input to lowercase.
TestCase=TestCase.lower()
#calculate ASCII value of all lower character String
RangeVariable=range(ord('a'),ord('z'))
#Now Returning requi... | 0 | 2016-06-09T04:07:46Z | [
"python"
] |
combining specific values in python list | 37,714,773 | <p>Here is my list </p>
<pre><code>['INQ/DATA', 'ENTRY', '1', 'MONETARY', '0', 'TRAN', 'GRID', '0', 'BCR', '0', 'ENVIRONMENT', 'TBL', '0', 'PRODUCT', 'FILE', '0', 'STOP/HOLD', '1', 'QUERY', '0', 'LOOKUP', 'FILE', '0', 'REPORT', 'FILE', '0']
</code></pre>
<p>I want the answer set like below...</p>
<pre><code>['INQ/DA... | -1 | 2016-06-08T23:51:34Z | 37,714,882 | <p>Merge the list items into a string literal using <code>.join</code> then <code>split</code> the string with <code>re</code> into a list of items using the numbers. </p>
<p>Build the final list by using a list comprehension on the splitted items to <code>strip</code> and <code>filter</code> whitespace characters: </... | 0 | 2016-06-09T00:05:00Z | [
"python",
"python-2.7"
] |
combining specific values in python list | 37,714,773 | <p>Here is my list </p>
<pre><code>['INQ/DATA', 'ENTRY', '1', 'MONETARY', '0', 'TRAN', 'GRID', '0', 'BCR', '0', 'ENVIRONMENT', 'TBL', '0', 'PRODUCT', 'FILE', '0', 'STOP/HOLD', '1', 'QUERY', '0', 'LOOKUP', 'FILE', '0', 'REPORT', 'FILE', '0']
</code></pre>
<p>I want the answer set like below...</p>
<pre><code>['INQ/DA... | -1 | 2016-06-08T23:51:34Z | 37,715,000 | <p>Let <a href="https://docs.python.org/2/library/itertools.html#itertools.groupby" rel="nofollow"><em>itertools.groupby</em></a> do it for you, passing <code>str.isdigit</code> as the key:</p>
<pre><code>l = ['INQ/DATA', 'ENTRY', '1', 'MONETARY', '0', 'TRAN', 'GRID', '0', 'BCR', '0', 'ENVIRONMENT', 'TBL', '0', 'PROD... | 0 | 2016-06-09T00:18:23Z | [
"python",
"python-2.7"
] |
How to add an attribute to a tag found using xpath in lxml in Python? | 37,714,813 | <p>I have the following xml - </p>
<pre><code><draw:image></draw:image>
</code></pre>
<p>I want to add multiple xlink attributes to it and make it -</p>
<pre><code><draw:image xlink:href="image" xlink:show="embed"></draw:image>
</code></pre>
<p>I tried using the following code but got the er... | 1 | 2016-06-08T23:56:07Z | 37,715,285 | <p>This is a working example:</p>
<pre><code>from lxml import etree as et
xml = et.parse("your.xml")
root = xml.getroot()
d = root.nsmap
for node in root.xpath("//draw:image", namespaces=d):
node.attrib["{http://www.w3.org/1999/xlink}href"] = "value"
node.attrib["{http://www.w3.org/1999/xlink}show"] = "embed... | 1 | 2016-06-09T00:58:02Z | [
"python",
"xml",
"xpath",
"lxml"
] |
Operate on every list item *except* matching item in pandas series | 37,714,845 | <p>I'm trying to write a function to calculate an odds ratio given a string that matches one index in a pandas series associated with a mean value. I want to find the value that matches the string, perform a calculation on that. And then take the average of every value in the pandas series that DOES NOT match the strin... | 0 | 2016-06-09T00:00:24Z | 37,715,153 | <p>try:</p>
<pre><code>def ratio(m, series):
Numerator = [series.Value.loc[series.index == motif].mean()] for motif in series.index
Denominator = [series.Value.loc[series.index != motif].mean()] for motif in series.index
ratio = numerator/denominator
return ratio
</code></pre>
| 0 | 2016-06-09T00:39:01Z | [
"python",
"pandas",
"filtering"
] |
What am I doing wrong with my code? | 37,714,914 | <p>When trying to run this code with Cloud 9 IDE online it wont run and produces the error code seen in the terminal. What do I need to do. It mentioned something about changing the host name? But I'm not sure how to do that. </p>
<p><a href="http://i.stack.imgur.com/4Qe5b.png" rel="nofollow">The Image Of The Code</a>... | -2 | 2016-06-09T00:07:35Z | 37,715,051 | <p>I'm seeing two things going on. One probably doesn't matter yet.</p>
<p>The immediate problem is that there's something wrong with the bash script kicking the run off. I couldn't say too much more without seeing it. But it's throwing errors around variable set or export.</p>
<p>In the code itself, I don't see a de... | 0 | 2016-06-09T00:24:06Z | [
"python",
"chromebook"
] |
Merging 2 Python callables into a single callable | 37,714,922 | <p>I have 2 Python callable objects (i.e. 2 function pointers). What's the cleanest way for me to merge these 2 into another callable?</p>
<p>Example:</p>
<pre><code>a = lambda: 1
b = lambda: 2
</code></pre>
<p>I want to merge these 2 into <code>c</code> where <code>c()</code> will call both <code>a()</code> and <co... | 0 | 2016-06-09T00:08:02Z | 37,714,950 | <p>Just put both of them in a tuple:</p>
<pre><code>a = lambda: 1
b = lambda: 2
c = lambda: (a(), b())
</code></pre>
<hr>
<pre><code>>>> c()
(1, 2)
>>>
</code></pre>
| 0 | 2016-06-09T00:12:24Z | [
"python"
] |
Most pythonic way to recursively apply a function to string values | 37,714,933 | <p><strong>Question:</strong>
I was wondering the most pythonic way to recursively apply a function to string values in an object without knowing it's schema in advance? Preferably in a generic enough manner to make it a reusable component for other types of operations.</p>
<p><strong>Context:</strong>
I am processin... | 3 | 2016-06-09T00:10:03Z | 37,715,008 | <p>My suggestion is to cut down on some redundant code:</p>
<pre><code>def strip(obj):
return obj.strip()
def recurse_into(obj, baseaction, basetype=str):
if isinstance(obj, basetype):
return baseaction(obj)
elif isinstance(obj, list):
return [recurse_into(o, baseaction, basetype) for o in... | 0 | 2016-06-09T00:19:35Z | [
"python",
"recursion"
] |
Most pythonic way to recursively apply a function to string values | 37,714,933 | <p><strong>Question:</strong>
I was wondering the most pythonic way to recursively apply a function to string values in an object without knowing it's schema in advance? Preferably in a generic enough manner to make it a reusable component for other types of operations.</p>
<p><strong>Context:</strong>
I am processin... | 3 | 2016-06-09T00:10:03Z | 37,715,472 | <p>The same approach "reversed" would be to split cases in separate functions and map them out. It's less metamagical, but might look more readable.</p>
<pre><code>def strip_obj(obj):
return obj.strip()
def strip_tuple(tuple):
return tuple(recurse(obj) for obj in tupl)
...
def recurse(root):
actions = {bas... | 0 | 2016-06-09T01:24:43Z | [
"python",
"recursion"
] |
Parse doubly delimited file with Python | 37,714,966 | <p>I am parsing comma-delimited files with Python where some of the text fields are double-delimited with quotes because the text contains non-delimiting commas. For example, given this line of input:</p>
<pre><code>field_1,field_2,...,"this,field,contains,non-delimiting,commas",...,field_n
</code></pre>
<p>I need t... | -1 | 2016-06-09T00:14:37Z | 37,715,106 | <p>You can use a fairly simple <a href="http://stackoverflow.com/questions/1756096/understanding-generators-in-python">generator</a> to accomplish this.</p>
<pre><code>def tokenize(input):
outstr = ""
stringmode = False
for char in input:
if char == "," and not stringmode:
yield outstr... | 0 | 2016-06-09T00:32:17Z | [
"python",
"python-2.7",
"parsing"
] |
Parse doubly delimited file with Python | 37,714,966 | <p>I am parsing comma-delimited files with Python where some of the text fields are double-delimited with quotes because the text contains non-delimiting commas. For example, given this line of input:</p>
<pre><code>field_1,field_2,...,"this,field,contains,non-delimiting,commas",...,field_n
</code></pre>
<p>I need t... | -1 | 2016-06-09T00:14:37Z | 37,715,231 | <p>This is something that is directly handled by <a href="https://docs.python.org/2/library/csv.html" rel="nofollow">the <code>csv</code> module</a> using <a href="https://docs.python.org/2/library/csv.html#csv.QUOTE_MINIMAL" rel="nofollow"><code>csv.QUOTE_MINIMAL</code></a> for <code>quoting</code> (comes as part of t... | 3 | 2016-06-09T00:50:06Z | [
"python",
"python-2.7",
"parsing"
] |
Correlation Matrix: Extract Variables with High R Values | 37,715,050 | <p>How can I get an output that would list only the variables whose absolute value correlation is greater than .7?</p>
<p>I would like output similar to this:</p>
<pre><code>four: one, three
one: three
</code></pre>
<p>Thanks for your time!</p>
<p>Code</p>
<pre><code>import pandas as pd
x={'one':[1,2,3,4],'two':[... | 0 | 2016-06-09T00:24:03Z | 37,715,896 | <p>If all you want is to print it out, this will work:</p>
<pre><code>col_names = y.corr().columns.values
for col, row in (y.corr().abs() > 0.7).iteritems():
print(col, col_names[row.values])
</code></pre>
<p>Note that this works but it might be slow because the <code>iteritems</code> method converts each row... | 0 | 2016-06-09T02:29:22Z | [
"python",
"matrix",
"correlation"
] |
Where do you need to use lit() in Pyspark SQL? | 37,715,060 | <p>I'm trying to make sense of where you need to use a <code>lit</code> value, which is defined as a <code>literal column</code> in the documentation.</p>
<p>Take for example this <code>udf</code>, which returns the index of a SQL column array:</p>
<pre><code>def find_index(column, index):
return column[index]
</... | 0 | 2016-06-09T00:24:52Z | 37,723,432 | <p>To keep it simple you need a <code>Column</code> (can be a one created using <code>lit</code> but it is not the only option) when JVM counterpart expects a column and there is no internal conversion in a Python wrapper or you wan to call a <code>Column</code> specific method. </p>
<p>In the first case the only stri... | 1 | 2016-06-09T10:30:43Z | [
"python",
"apache-spark",
"pyspark"
] |
Reverse geocode, reading .CSV file and TypeError: a float is required | 37,715,222 | <p>Fixed: Added float() to coordinates1 and coordinates2:</p>
<pre><code>my_location = gmaps.reverse_geocode(float(coordinates1), float(coordinates2))
</code></pre>
<p>I'm trying to convert lat long coordinates to addresses. I have a .CSV file with the coordinates, and I don't know if my code can read it, or if it's ... | 0 | 2016-06-09T00:49:02Z | 37,715,347 | <p>As <em>PM 2Ring</em> pointed out, you need to convert the coordinates from strings into floating point numbers. Replace:</p>
<pre><code>coordinates1 = row[0]
coordinates2 = row[1]
</code></pre>
<p>with:</p>
<pre><code>coordinates1, coordinates2 = [float(c) for c in row]
</code></pre>
| 1 | 2016-06-09T01:07:09Z | [
"python",
"csv"
] |
pandas groupby-apply behavior, returning a Series (inconsistent output type) | 37,715,246 | <p>I'm curious about the behavior of pandas groupby-apply when the apply function returns a series.</p>
<p>When the series are of different lengths, it returns a multi-indexed series.</p>
<pre><code>In [1]: import pandas as pd
In [2]: df1=pd.DataFrame({'state':list("AABBB"),
...: 'city':list("vwxy... | 0 | 2016-06-09T00:52:35Z | 37,717,138 | <p>In essence, a dataframe consists of equal-length series (technically a dictionary container of series objects). As stated in the panadas <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html" rel="nofollow">split-apply-combine</a> docs, running a <em>groupby()</em> refers to one or more of the following<... | 1 | 2016-06-09T04:58:15Z | [
"python",
"pandas"
] |
Opening up a batch of tabs at once in Selenium | 37,715,263 | <p>Though this is probably not the intended use for Selenium, I want to open up a few (typically 2-5) tabs at the same time after I have logged in.</p>
<p>Here is what I've tried:</p>
<pre><code>for estimate in estimates:
browser.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 't')
browser.g... | 0 | 2016-06-09T00:54:35Z | 37,716,307 | <p>I was unable to find a better solution, so I have resorted to a method that is inadvisable under normal circumstances:</p>
<pre><code>browser.set_page_load_timeout(0)
for estimate in estimates:
browser.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 't')
try:
browser.get('https://www.examp... | 0 | 2016-06-09T03:31:35Z | [
"python",
"selenium",
"selenium-webdriver"
] |
gdal_calc amin fails when passing more than 23 input files | 37,715,316 | <p>I've written an R function that calls <code>gdal_calc.py</code> to calculate the pixel-wise minimum value across a <code>RasterStack</code> (series of input raster files). I've done this because it's much faster than <code>raster::min</code> for large rasters. The function works well for up to 23 files, but throws a... | 9 | 2016-06-09T01:03:11Z | 37,912,771 | <p>The issue you were running into was that the <code>X</code> variable from the <code>calc</code> input was colliding with the variable created by a loop in the <code>doit</code> function:</p>
<pre><code>for X in range(0,nXBlocks):
</code></pre>
<p>It appears this has already been fixed by the gdal developers (in no... | 2 | 2016-06-19T23:11:28Z | [
"python",
"numpy",
"raster",
"gdal"
] |
I can't extract text from powerpoint 2003 file by olefile | 37,715,355 | <p>I can't extract text from Powerpoint 2003 ppt. After the following code, python shell will be 'not responding' or hang up. </p>
<p><code>
import olefile
ole = olefile.OleFileIO('mypowerpoint.ppt')
text = ole.openstream('PowerPoint Document')
read = text.read()
print(read)
</code></p>
| 0 | 2016-06-09T01:07:52Z | 37,752,961 | <p>I think this is because the stream "PowerPoint Document" contains mostly binary data. So you would need to process it to extract the text before printing it.</p>
<p>Alternatively, you may use print(repr(read)) to see what it contains.</p>
| 0 | 2016-06-10T16:21:16Z | [
"python",
"text",
"extract"
] |
Django Rest Framework ModelSerializer save error | 37,715,373 | <p>I want to add an extra key-value pair from the data that I passed to the serializer however this error occurs:</p>
<pre><code>ValueError: Cannot assign "1": "ExamLog.student" must be a "Students" instance.
</code></pre>
<p>serializers.py</p>
<pre><code>class ExamSubmitSerializer(serializers.ModelSerializer):
... | 0 | 2016-06-09T01:10:20Z | 37,718,202 | <pre><code>def to_internal_value(self, data):
x = get_score(data['exam']) # This will result to 1, I have no errors with this one
data['score'] = x
data = super(ExamSubmitSerializer, self).to_internal_value(data)
return data
</code></pre>
<p>Calling super on the method before returning the data will ... | 2 | 2016-06-09T06:18:50Z | [
"python",
"django",
"django-rest-framework"
] |
What built-in function is called when entering object in interactive Python shell? | 37,715,461 | <p>It's nice to be able to enter an object in the shell, and get something back, e.g.,</p>
<pre><code>>>>foo
I am foo
</code></pre>
<p>Usually, using <code>print(foo)</code> in a module script will yield the same result, as in the case above (I'm using Python 3.5). But often, with instances of complex class... | 2 | 2016-06-09T01:22:17Z | 37,715,486 | <p>In the REPL, it's <code>__repr__()</code> that's used to give you the representation of an object whereas <code>print</code> gives you the result of the <code>__str__()</code> function, as per the following transcript:</p>
<pre><code>pax> python
Python 2.7.9 (default, Jun 1 2016, 16:07:34)
[GCC 4.9.2] on linux... | 2 | 2016-06-09T01:26:57Z | [
"python"
] |
What built-in function is called when entering object in interactive Python shell? | 37,715,461 | <p>It's nice to be able to enter an object in the shell, and get something back, e.g.,</p>
<pre><code>>>>foo
I am foo
</code></pre>
<p>Usually, using <code>print(foo)</code> in a module script will yield the same result, as in the case above (I'm using Python 3.5). But often, with instances of complex class... | 2 | 2016-06-09T01:22:17Z | 37,715,489 | <p><code>__repr__()</code> is the method called in this situation. It returns the "official" (canonical) representation of the object, as opposed to <code>__str__</code> which is typically less structured.</p>
<ul>
<li><a href="https://docs.python.org/3/reference/datamodel.html#object.__repr__" rel="nofollow">Official... | 1 | 2016-06-09T01:27:21Z | [
"python"
] |
What built-in function is called when entering object in interactive Python shell? | 37,715,461 | <p>It's nice to be able to enter an object in the shell, and get something back, e.g.,</p>
<pre><code>>>>foo
I am foo
</code></pre>
<p>Usually, using <code>print(foo)</code> in a module script will yield the same result, as in the case above (I'm using Python 3.5). But often, with instances of complex class... | 2 | 2016-06-09T01:22:17Z | 37,715,492 | <p>Compare <code>repr</code> vs <code>str</code>:</p>
<pre><code>>>> class A: pass
...
>>> A
<class __main__.A at 0x101c609a8>
>>> A()
<__main__.A instance at 0x101cea488>
>>> print A
__main__.A
>>> repr(A)
'<class __main__.A at 0x101c609a8>'
>>>... | 1 | 2016-06-09T01:27:50Z | [
"python"
] |
What built-in function is called when entering object in interactive Python shell? | 37,715,461 | <p>It's nice to be able to enter an object in the shell, and get something back, e.g.,</p>
<pre><code>>>>foo
I am foo
</code></pre>
<p>Usually, using <code>print(foo)</code> in a module script will yield the same result, as in the case above (I'm using Python 3.5). But often, with instances of complex class... | 2 | 2016-06-09T01:22:17Z | 37,715,516 | <p><code>print</code> implicitly applies <code>str()</code> to each printed item to obtain a string, while the shell implicitly applies <code>repr()</code> to obtain a string. So it's the difference (if any) between an object's <code>__str__()</code> and <code>__repr__()</code> methods </p>
<pre><code>>>> cl... | 5 | 2016-06-09T01:31:04Z | [
"python"
] |
python dictionary, assigning lists | 37,715,488 | <p>Hello all i have an assignment for my computer science class where i have to emulate a different version of Conway game of life: <a href="https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life" rel="nofollow">https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life</a></p>
<p>( in short, the user enters with a set of c... | 0 | 2016-06-09T01:27:02Z | 37,715,641 | <p>You might use this approach to get input </p>
<pre><code>m=5
n=5
#Generate m*n board with all cells Dead
board=[["Dead" for x in range(m)] for y in range(n)]
#Input list with alive cells
alivelist=[[0,0],[2,3],[4,4]]
print board
# [['Dead', 'Dead', 'Dead', 'Dead', 'Dead'],
# ['Dead', 'Dead', 'Dead', 'Dead', 'D... | 0 | 2016-06-09T01:49:36Z | [
"python",
"dictionary"
] |
Flask to Dygraph - how to pass data? | 37,715,505 | <p>If I have a simple Python time data series like this:</p>
<pre><code>graphdata = []
graphdata.append( [(datetime.date(2008, 5, 7)),75])
graphdata.append([(datetime.date(2008, 5, 8)), 85])
graphdata.append([(datetime.date(2008, 5, 10)), 60])
</code></pre>
<p>How can I pass the data to a Flask page running Dygraph?<... | 2 | 2016-06-09T01:29:20Z | 39,422,375 | <p>No need to pass the data as a list containing <code>datetime</code> objects. Dygraphs reads CSV format with ease. So just pass the data as one long CSV <code>string</code>. For your case, first formulate that string containing your data:</p>
<pre><code>graphdata = ''
graphdata = graphdata + '2008-05-07, 75\n'
graph... | 0 | 2016-09-10T03:54:18Z | [
"javascript",
"python",
"flask",
"dygraphs"
] |
What is the Django equivalence for Flask's UserMixin? | 37,715,517 | <p>In Flask there is the <code>flask.ext.login.UserMixin</code> from the <code>flask-login</code> module. </p>
<p>I've tried to looked for the Django equivalence and the closest thing to the Flask's <code>UserMixin</code> is the <code>django.contrib.auth.models.User</code> from
<a href="https://docs.djangoproject.com... | 1 | 2016-06-09T01:31:06Z | 37,715,552 | <p>Indeed. It's a model that stores information about a logged in User. Same thing.</p>
<p>You can either extend the model or replace it entirely.</p>
<blockquote>
<p>There are two ways to extend the default User model without substituting your own model. If the changes you need are purely behavioral, and donât r... | 1 | 2016-06-09T01:35:31Z | [
"python",
"django",
"flask",
"mixins",
"pybossa"
] |
Convert data from one format to another | 37,715,917 | <p>I have data in this format:</p>
<pre><code>{'a':['b','c','d'],'bla':['djjd','cop']}
</code></pre>
<p>And I want to convert the above into this format:</p>
<pre><code>('a',('b','c','d')),('bla',('djjd','cop'))
</code></pre>
<p>What can be done in Python to achieve the above?</p>
| -1 | 2016-06-09T02:32:24Z | 37,715,941 | <p>You can use simple <a href="https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions" rel="nofollow">list comprehension</a> that turns key value pairs from dictionary to tuples:</p>
<pre><code>>>> d = {'a':['b','c','d'],'bla':['djjd','cop']}
>>> [(k, tuple(v)) for k, v in d.items... | 0 | 2016-06-09T02:35:39Z | [
"python",
"list",
"hashmap"
] |
Convert data from one format to another | 37,715,917 | <p>I have data in this format:</p>
<pre><code>{'a':['b','c','d'],'bla':['djjd','cop']}
</code></pre>
<p>And I want to convert the above into this format:</p>
<pre><code>('a',('b','c','d')),('bla',('djjd','cop'))
</code></pre>
<p>What can be done in Python to achieve the above?</p>
| -1 | 2016-06-09T02:32:24Z | 37,715,950 | <p>Suppose your data is in variable <code>d</code>. Then:</p>
<pre><code>converted = [(key, tuple(d[key])) for key in sorted(d)]
</code></pre>
| 1 | 2016-06-09T02:37:37Z | [
"python",
"list",
"hashmap"
] |
How to create a list of random objects? | 37,715,971 | <pre><code>class HandOfCards:
def __init__ (self, numCardsInHand):
self.list = []
all_rank = random.randint(1, 13)
random_suit = ['d', 'c', 'h', 's']
all_suit = random.choice(random_suit)
for count in range(numCardsInHand):
self.list.append(Card(all_rank, all_... | 2 | 2016-06-09T02:41:14Z | 37,716,016 | <p>You need to make the calls to the <code>random</code> module within your loop:</p>
<pre><code> for count in range(numCardsInHand):
all_rank = random.randint(1, 13)
random_suit = ['d', 'c', 'h', 's']
all_suit = random.choice(random_suit)
self.list.append(Card(all_rank, all_suit))
<... | 2 | 2016-06-09T02:47:25Z | [
"python",
"oop",
"python-3.x"
] |
How to create a list of random objects? | 37,715,971 | <pre><code>class HandOfCards:
def __init__ (self, numCardsInHand):
self.list = []
all_rank = random.randint(1, 13)
random_suit = ['d', 'c', 'h', 's']
all_suit = random.choice(random_suit)
for count in range(numCardsInHand):
self.list.append(Card(all_rank, all_... | 2 | 2016-06-09T02:41:14Z | 37,716,017 | <p>The <code>random</code> module only assigns the value to the variable and the variables is fixed to it. It does not reassign everytime you call the variable (that would be weird). In other words, you should call the function again everytime you want a new value. In your case,</p>
<pre><code>for count in range(numCa... | 2 | 2016-06-09T02:47:33Z | [
"python",
"oop",
"python-3.x"
] |
How to create a list of random objects? | 37,715,971 | <pre><code>class HandOfCards:
def __init__ (self, numCardsInHand):
self.list = []
all_rank = random.randint(1, 13)
random_suit = ['d', 'c', 'h', 's']
all_suit = random.choice(random_suit)
for count in range(numCardsInHand):
self.list.append(Card(all_rank, all_... | 2 | 2016-06-09T02:41:14Z | 37,716,055 | <p><code>all_rank</code> is not a function that generates a random rank; it <em>is</em> a single, randomly chosen rank, as the result of a single call to <code>random.choice</code>. (Likewise for <code>all_suit</code>.)</p>
<p>However, even if you called <code>random.choice</code> and <code>random.randint</code> each ... | 2 | 2016-06-09T02:54:04Z | [
"python",
"oop",
"python-3.x"
] |
Automatically changing Django model field on update for one field and freezing one-time write-only for another? | 37,716,134 | <p><strong>Is there a <code>onupdate</code> parameter for Django's model fields?</strong></p>
<p>For example, in Flask with SQLAlchemy, it's possible to do something like the following with the <code>onupdate=...</code> parameter for the database schema's <code>db.Column()</code>:</p>
<pre><code>import datetime
from... | 0 | 2016-06-09T03:05:32Z | 37,717,191 | <p>In django you have the <code>auto_now_add</code> and <code>auto_now</code> optional arguments for <code>models.DateTimeField</code></p>
<pre class="lang-py prettyprint-override"><code>class User(models.Model):
id = models.IntegerField()
created_on = models.DateTimeField(auto_now_add=True)
updated_on = m... | 1 | 2016-06-09T05:02:00Z | [
"python",
"django",
"flask",
"sql-update",
"schema"
] |
Python How to store decoded unicode string from email in list and then use later? | 37,716,174 | <p>I have been working on parsing emails with Python. Learning how to handle character encoding has been challenging. I am using the native email libraries to create a msg object.</p>
<p>I first take the important header values and store as variables. No problem here as far as I can tell. This is an example of getting... | 0 | 2016-06-09T03:12:28Z | 37,716,398 | <p>When you write to the file, use the following:</p>
<pre><code>f = open(emailPartsFile,'wb')
</code></pre>
<p>....</p>
<pre><code>f.write(str(<YOUR_DICT>).encode('utf8'))
</code></pre>
<p>When you open your file, it should have the Chinese characters. </p>
| 0 | 2016-06-09T03:45:04Z | [
"python",
"email",
"unicode",
"encoding"
] |
What's the difference between STATIC_URL and STATIC_ROOT in Django? | 37,716,200 | <p>I'm somewhat confused as to what the difference is between STATIC_URL and STATIC_ROOT in Django's <code>'staticfiles'</code> app.</p>
<p>I believe I understand what the <code>STATIC_ROOT</code> is: it's essentially the location on the server where the staticfiles' <code>collectstatic</code> command will place the s... | 2 | 2016-06-09T03:16:17Z | 37,717,024 | <p>Like you mentioned, it is pretty clear from the documentation:</p>
<blockquote>
<p><strong>STATIC_ROOT:</strong></p>
<p>The absolute path to the directory where <code>collectstatic</code> will collect static files for deployment.</p>
<p><strong>STATIC_URL</strong></p>
<p>default: None</p>
<p>U... | 1 | 2016-06-09T04:47:39Z | [
"python",
"django",
"django-staticfiles"
] |
What's the difference between STATIC_URL and STATIC_ROOT in Django? | 37,716,200 | <p>I'm somewhat confused as to what the difference is between STATIC_URL and STATIC_ROOT in Django's <code>'staticfiles'</code> app.</p>
<p>I believe I understand what the <code>STATIC_ROOT</code> is: it's essentially the location on the server where the staticfiles' <code>collectstatic</code> command will place the s... | 2 | 2016-06-09T03:16:17Z | 37,717,112 | <p>STATIC_URL is simply the prefix or url that its prepended to your static files and is used by the <code>static</code> method in Django templates mostly. <a href="https://docs.djangoproject.com/en/1.9/ref/settings/#std:setting-STATIC_URL" rel="nofollow">https://docs.djangoproject.com/en/1.9/ref/settings/#std:setting-... | 0 | 2016-06-09T04:56:25Z | [
"python",
"django",
"django-staticfiles"
] |
What's the difference between STATIC_URL and STATIC_ROOT in Django? | 37,716,200 | <p>I'm somewhat confused as to what the difference is between STATIC_URL and STATIC_ROOT in Django's <code>'staticfiles'</code> app.</p>
<p>I believe I understand what the <code>STATIC_ROOT</code> is: it's essentially the location on the server where the staticfiles' <code>collectstatic</code> command will place the s... | 2 | 2016-06-09T03:16:17Z | 37,717,144 | <p><code>STATIC_ROOT</code> is where all your assets will be collected by the <code>collectstatic</code> command. The contents of this directly contain all static assets from all applications listed in <code>INSTALLED_APPS</code> (from their own <code>static</code> folders) and any file locations mentioned in <a href="... | 0 | 2016-06-09T04:58:31Z | [
"python",
"django",
"django-staticfiles"
] |
In odoo how can I match content of the email body to the description field in leads | 37,716,233 | <p>In auto lead through incoming email I have added the code shown below that how to add body of email into description but I am getting as html format
Can anybody know how to add content of the email body same as into description field.</p>
<pre class="lang-py prettyprint-override"><code>def message_new(self, cr, uid... | 0 | 2016-06-09T03:22:04Z | 37,722,742 | <p>Try out:</p>
<pre class="lang-py prettyprint-override"><code>from openerp.tools import html2plaintext
# ...
if 'description' in fields and not data.get('description'):
data['description'] = html2plaintext(msg.get('body')) if msg.get('body') else ''
# ...
</code></pre>
| 1 | 2016-06-09T10:00:29Z | [
"python",
"openerp",
"odoo-8",
"openerp-8"
] |
Determine Active NIC address using python console commands | 37,716,294 | <p>I am trying to find an active NIC, an active NIC is one where the command wil return UP for me.</p>
<p>In my command:</p>
<pre><code># cat /sys/class/net/eth0/operstate
</code></pre>
<p>I am returned a value of UP</p>
<p>In another command, I type:</p>
<pre><code># cat /sys/class/net/eth1/operstate
</code></pre... | 0 | 2016-06-09T03:29:36Z | 37,716,354 | <p>x is a variable containing the value: 1 or 2 or 3 or 4.
The code-snippet you've treats x as a string.
Also, the code-snippet tries to enclose single quotes within single quotes generating the error.</p>
<p>Modify as below and it should work.</p>
<p>Also, there's a syntax error in the above code - you're missing a ... | 0 | 2016-06-09T03:39:31Z | [
"python",
"console",
"command",
"line",
"nic"
] |
Python: AttributeError: 'NoneType' object has no attribute 'rfind' | 37,716,326 | <p>I am trying to determine the file extension using os.path.splitext</p>
<p>here is my code:</p>
<pre><code>for emailid in msgs:
typ, s = mail.fetch(emailid, "(RFC822)")
m = email.message_from_string(s[0][1])
result = re.findall(pattern,str)
if result:
for part in m.walk():
f... | 1 | 2016-06-09T03:34:28Z | 37,716,381 | <p>In <code>extension = os.path.splitext(fileName)</code>, you're using the variable <code>fileName</code>, instead of <code>filename</code>. Python is case-sensitive, so these are different variables. Evidently, <code>fileName</code> is elsewhere set to None, and changing that instance to <code>filename</code> should ... | 2 | 2016-06-09T03:43:05Z | [
"python",
"file-extension"
] |
Puking blood: how to make a scrapy, python, and postrgres ecosystem inside Windows 7 that can deal with unicode | 37,716,376 | <p>Would <em>really</em> appreciate if anyone can help me either fix the problems I describe below, or (worst case) suggest an alternative environment that would work (although I'm loathe to upgrade to Windows 10)</p>
<hr>
<p>I am scraping mostly-english webpages from a Japanese website. A few required fields have ka... | 1 | 2016-06-09T03:42:36Z | 37,717,517 | <p>From your error message, <code>cp437</code> is the US Windows console default encoding. You could try temporarily switching your system locale to "Japanese(Japan)" so you could print Kanji to the console. Go to Control Panel, Region and Language, Administrative tab and click "Change system locale...". After reboo... | 1 | 2016-06-09T05:29:09Z | [
"python",
"postgresql",
"unicode",
"windows-7",
"scrapy"
] |
Python Struct format error | 37,716,415 | <p>So I am looking at code that I wrote perhaps as much as 4 years ago, and I know it ran correctly at the time. But now I am trying to run it, on a different computer than when I wrote it years ago and I am getting an error now. (Tried it today on both Windows 10 and Ubuntu)</p>
<p>I am using Python 2.7, as I was the... | 1 | 2016-06-09T03:47:22Z | 37,716,519 | <p>The <em>standard</em> size of <code>L</code> is 4 bytes, but that is only used if you are explicit about the endianness to use by beginning the format string with <code>></code>, <code><</code>, <code>!</code>, or <code>=</code>. Otherwise, the platform-dependent native size for your machine is used. (In this ... | 3 | 2016-06-09T03:56:03Z | [
"python",
"struct"
] |
How can I get a specific interface of an Acad object with comtypes (Python) | 37,716,619 | <p>I am writing a Python3 program to work with AutoCAD.
I use pyautocad and comtypes.</p>
<p>I can take any object on the drawing and get its best interface.
For example, I can explode some block reference and work with new objects the AutoCAD creates:</p>
<pre><code>for NewItem in BlockReference.Explode():
# NewIt... | 1 | 2016-06-09T04:06:35Z | 37,757,971 | <p>This was only tested with python 2.7:</p>
<pre><code>from pyautocad import Autocad, APoint
from comtypes.client import GetBestInterface
from comtypes.gen.AutoCAD import IAcadEntity, IAcadObject
# Get acad application
acad = Autocad(create_if_not_exists=True)
# Create a new document
doc1 = GetBestInterface(acad.App... | 0 | 2016-06-10T22:27:40Z | [
"python",
"com",
"autocad"
] |
Mysql query killed automatically in python | 37,716,627 | <p>I am using MobaExterm to run my python script.
The script is fetching records from 3 tables. I can see the output of my query in MySQL Workbench but when the same query runs in my script, i get output as <strong>"Killed"</strong></p>
<p>What is the reason. My query seems correct.</p>
<pre><code>select tsp.data_ip... | 0 | 2016-06-09T04:07:39Z | 37,742,459 | <p>The reason why this happens in python script is because of too many records.
The record exceeds the time to wait of the script while its running and kills it.</p>
<p>As seen in the select query, it is querying three tables at the same time with where clause mentioning multiple conditions in 'and', 'or'.</p>
<p><st... | 0 | 2016-06-10T07:33:35Z | [
"python",
"mysql"
] |
How to hstack several sparse matrices (feature matrices)? | 37,716,699 | <p>I have 3 sparse matrices:</p>
<pre><code>In [39]:
mat1
Out[39]:
(1, 878049)
<1x878049 sparse matrix of type '<type 'numpy.int64'>'
with 878048 stored elements in Compressed Sparse Row format>
In [37]:
mat2
Out[37]:
(1, 878049)
<1x878049 sparse matrix of type '<type 'numpy.int64'>'
... | 2 | 2016-06-09T04:14:18Z | 37,717,576 | <p>Use the <code>sparse</code> versions of <code>vstack</code>. As general rule you need to use sparse functions and methods, not the <code>numpy</code> ones with similar name. <code>sparse</code> matrices are not subclasses of <code>numpy</code> <code>ndarray</code>.</p>
<p>But, your 3 three matrices do not look sp... | 2 | 2016-06-09T05:33:24Z | [
"python",
"numpy",
"machine-learning",
"scipy",
"scikit-learn"
] |
grep a string after pattern match in python | 37,716,749 | <p>I want to extract the testbed name from a file. This is the line where the name is present, How could I do it in Python?</p>
<pre><code>Status: aaa (image='some_image_name' on testbed='test_bed_name' archiving)
</code></pre>
<p>I was thinking of splitting the string taking the index, but this line may not be the s... | 0 | 2016-06-09T04:19:50Z | 37,716,797 | <p>With a lookbehind.</p>
<pre><code>>>> re.search("(?<=testbed=')([^']+)'", "Status: aaa (image='some_image_name' on testbed='test_bed_name' archiving)").groups()
('test_bed_name',)
</code></pre>
| 2 | 2016-06-09T04:23:58Z | [
"python"
] |
grep a string after pattern match in python | 37,716,749 | <p>I want to extract the testbed name from a file. This is the line where the name is present, How could I do it in Python?</p>
<pre><code>Status: aaa (image='some_image_name' on testbed='test_bed_name' archiving)
</code></pre>
<p>I was thinking of splitting the string taking the index, but this line may not be the s... | 0 | 2016-06-09T04:19:50Z | 37,716,810 | <p>If the format is always like that, you could simply slice your way to the right place:</p>
<pre><code>>>> s.split('=')[-1].split(' ')[0][1:-1]
test_bed_name
</code></pre>
<p>Or, you can use regular expressions:</p>
<pre><code>>>> re.findall(r"(?:.*?)testbed='(.*?)'(?:.*?)", s)
test_bed_name
</co... | 0 | 2016-06-09T04:26:04Z | [
"python"
] |
Django No Profile Authentication | 37,716,808 | <p>I want to make a django site which has no profile authentication or signing in. Anonymous users will be able to make a form that will be potentially open to anyone else on the site.</p>
<p>I'd like to do two things:</p>
<ol>
<li><p>Somehow limit access to this form to certain people, without on site profiles. Ma... | 0 | 2016-06-09T04:25:50Z | 37,717,213 | <p>There is no best practice nor a plugin for this use case. It is a common-or-garden, simple use case which should not demand that much of code and logic that you look for some plugin or best practice. Just draw the picture you imagine, sit and write your code. if you have any exact problems in your code, then ask a q... | 0 | 2016-06-09T05:03:35Z | [
"python",
"django",
"one-time-password"
] |
Django No Profile Authentication | 37,716,808 | <p>I want to make a django site which has no profile authentication or signing in. Anonymous users will be able to make a form that will be potentially open to anyone else on the site.</p>
<p>I'd like to do two things:</p>
<ol>
<li><p>Somehow limit access to this form to certain people, without on site profiles. Ma... | 0 | 2016-06-09T04:25:50Z | 37,718,590 | <p>Given the specific site you're trying to recreate has an <a href="https://onetimesecret.com/docs/api/secrets" rel="nofollow">api</a>, it would appear that the details aren't matched against the user, but the post itself. so simply make a model that has the two things that it requires</p>
<blockquote>
<p>Query Par... | 0 | 2016-06-09T06:42:05Z | [
"python",
"django",
"one-time-password"
] |
Im having trouble figuring out why my paddles and ball images wont show up on pygame | 37,716,809 | <h1> starting all modules and window</h1>
<pre><code> import pygame, sys, time, random from pygame.locals import *
pygame.init()
bg = pygame.image.load("./soccerfield.png")
mainClock = pygame.time.Clock()
WINDOWWIDTH = 800
WINDOWHEIGHT = 600
SIZESIDE... | -1 | 2016-06-09T04:26:02Z | 37,764,856 | <p>Why are you loading the images in this code here:</p>
<pre><code>Paddle1.draw()
Paddle1.pygame.image.load("./soccerplayer1")
windowSurface.blit(Paddle1)
</code></pre>
<p>You should set the paddle image during class instantiation. Also you are trying to blit the class not the image, hence why it isn't showing up. ... | 0 | 2016-06-11T14:27:20Z | [
"python",
"pygame",
"pong"
] |
Why does uWSGI fail to start in Docker? | 37,716,826 | <p>I am relatively new to using uWSGI to serve Python applications and I am attempting to start a uWSGI process in emperor mode with a vassal, but every time I try to start uWSGI inside of Docker with the following command (as <code>root</code>):</p>
<pre><code># /usr/local/bin/uwsgi --ini /etc/uwsgi/emperor.ini
</cod... | 1 | 2016-06-09T04:27:43Z | 37,767,666 | <blockquote>
<p><strong>tl;dr</strong> don't use <code>UWSGI_VERSION</code> as an environment variable, apparently it forces uWSGI to only print the version number instead of start?</p>
</blockquote>
<p>I believe I solved my own issue!</p>
<p>After experimenting with other uWSGI images on Docker's hub, I found that... | 1 | 2016-06-11T19:18:19Z | [
"python",
"docker",
"uwsgi",
"supervisord"
] |
Python : How to connect socket on different network | 37,716,891 | <p><strong>I have begun learning Socket Programming and Issue I faced is. I am unable to connect Sockets when On two different network ( To be specific : I am using Web-host and Cgi programming to create python socket Server and my goal is to connect to that socket using desktop client python application )</strong></p>... | 0 | 2016-06-09T04:34:58Z | 37,716,948 | <p>Python 2 and 3 handle sockets differently! See here <a href="http://stackoverflow.com/questions/29513683/difference-between-python3-and-python2-socket-send-data">this question</a> for example. What you could do as a quick workaround is to change your client start line to <code>"#!/usr/bin/env python2.7"</code> to fo... | 0 | 2016-06-09T04:40:38Z | [
"python",
"sockets",
"networking",
"server",
"client"
] |
More efficient way to search large XML file in Python | 37,716,938 | <p>So I have 2 XML file (A and B) with around 90k record on each file.</p>
<p>Format of the files are as follows:</p>
<pre><code><trips>
<trip id="" speed=""/>
.
.
.
.
</trips>
</code></pre>
<p>I need to compare the speed attribute from bo... | 0 | 2016-06-09T04:39:22Z | 37,717,008 | <p>Cast both the trees into dicts, then compare them:</p>
<pre><code>trips_a = {}
for trip in A.getElementByTagName('trip'):
trips_a[trip.attributes['id']] = trip.attributes['id'].value
for trip in B.getElementByTagName('trip'):
trip_value_from_B = trip.attributes['id'].value
trip_value_from_A = trips_a[tr... | 1 | 2016-06-09T04:46:00Z | [
"python",
"xml",
"performance"
] |
Conform long lines to fit PEP 8 | 37,716,955 | <p>I have a question about styling in PEP 8 (or cutting the number of characters in each line to be smaller).</p>
<p>Consider that I have a <code>book</code> with a bunch of different attributes and I want to concatenate them into some String.</p>
<pre><code>books = [book_1, book_2, book_3]
for b in books:
print("T... | 2 | 2016-06-09T04:40:56Z | 37,717,001 | <p>Enter a new line like so. see also: <a href="http://stackoverflow.com/questions/4172448/is-it-possible-to-break-a-long-line-to-multiple-lines-in-python">Is it possible to break a long line to multiple lines in Python</a></p>
<pre><code>books = [book_1, book_2, book_3]
for b in books:
print("Thank you for using ou... | 1 | 2016-06-09T04:45:11Z | [
"python",
"pep8"
] |
Conform long lines to fit PEP 8 | 37,716,955 | <p>I have a question about styling in PEP 8 (or cutting the number of characters in each line to be smaller).</p>
<p>Consider that I have a <code>book</code> with a bunch of different attributes and I want to concatenate them into some String.</p>
<pre><code>books = [book_1, book_2, book_3]
for b in books:
print("T... | 2 | 2016-06-09T04:40:56Z | 37,717,216 | <p>You can move your string outside the loop, and then format it before printing, like this:</p>
<pre><code>message = 'Thank you for using our Library! You have decided to borrow {0.title} \
on {0.start_date}. Please remember to return the book in \
{0.lend_duration} calendar days on {0.return_da... | 4 | 2016-06-09T05:03:52Z | [
"python",
"pep8"
] |
Conform long lines to fit PEP 8 | 37,716,955 | <p>I have a question about styling in PEP 8 (or cutting the number of characters in each line to be smaller).</p>
<p>Consider that I have a <code>book</code> with a bunch of different attributes and I want to concatenate them into some String.</p>
<pre><code>books = [book_1, book_2, book_3]
for b in books:
print("T... | 2 | 2016-06-09T04:40:56Z | 37,717,278 | <p>Try this approach:</p>
<pre><code>print(("Thank you for using our Library! You have decided to borrow {} "
+ "on {}. Please remember to return the book in {} calendar days"
+ "on {}").format(book.title, book.start_date, book.lend_duration,
book.return_date)
</code></pre>
<p... | 0 | 2016-06-09T05:09:06Z | [
"python",
"pep8"
] |
Conform long lines to fit PEP 8 | 37,716,955 | <p>I have a question about styling in PEP 8 (or cutting the number of characters in each line to be smaller).</p>
<p>Consider that I have a <code>book</code> with a bunch of different attributes and I want to concatenate them into some String.</p>
<pre><code>books = [book_1, book_2, book_3]
for b in books:
print("T... | 2 | 2016-06-09T04:40:56Z | 37,733,532 | <p>As it's not mentioned in any other answer, you can use parenenthesis <em>without</em> using <code>+</code> or <code>\</code>:</p>
<pre><code>>>> ("hello"
" world")
'hello world'
</code></pre>
<p>Combined with <a href="http://stackoverflow.com/a/37717216/1240268">Burhan's answer</a> that gives you:</p... | 1 | 2016-06-09T18:24:36Z | [
"python",
"pep8"
] |
How to print multiplication table using nested for loops | 37,717,127 | <p>I need some help printing multiplication table using nested for loop. My code right now is:</p>
<pre><code>for x in range(1,10):
print(" ", x, end = '')
print()
for row in range(1, 10):
for col in range(1, 10):
num = row * col
if num < 10:
empty = " "
else:
... | 1 | 2016-06-09T04:57:34Z | 37,717,344 | <p>One of the simplest methods would be to start counting from 0 instead of 1:</p>
<pre><code>for row in range(0, 10):
for col in range(0, 10):
num = row * col
if num < 10:
empty = " "
else:
if num < 100:
empty = " "
if col == 0:
... | 2 | 2016-06-09T05:15:29Z | [
"python",
"for-loop",
"printing"
] |
How to print multiplication table using nested for loops | 37,717,127 | <p>I need some help printing multiplication table using nested for loop. My code right now is:</p>
<pre><code>for x in range(1,10):
print(" ", x, end = '')
print()
for row in range(1, 10):
for col in range(1, 10):
num = row * col
if num < 10:
empty = " "
else:
... | 1 | 2016-06-09T04:57:34Z | 37,717,398 | <p>Try this:</p>
<pre><code>header = '\t{}'.format('\t'.join(map(str, range(1, 10))))
rows = []
for i in range(1, 10):
row = '\t'.join(map(str, (i*q for q in range(1, 10))))
rows.append('{}\t{}'.format(i, row))
print(header+'\n' + '\n'.join(rows))
</code></pre>
<p>Which will give you:</p>
<pre><code>>>&g... | 2 | 2016-06-09T05:19:59Z | [
"python",
"for-loop",
"printing"
] |
Python Pandas: cannot do slice indexing | 37,717,137 | <p>I am trying to work with a pandas multiindex dataframe that looks like this:</p>
<pre><code> end ref|alt
chrom start
chr1 3000714 3000715 T|G
3001065 3001066 G|T
3001110 3001111 G|C
3001131 3001132 G|A
</code></pre>
<p>I want to be able to do this: </p>
<pr... | 2 | 2016-06-09T04:58:11Z | 37,717,252 | <p>I think you need add <code>,:</code> to the end - it means you need slicing rows, but need all columns:</p>
<pre><code>print (df.loc[('chr1', slice(3000714, 3001110)),:])
end ref|alt
chrom start
chr1 3000714 3000715 T|G
3001065 3001066 G|T
3001110 300111... | 3 | 2016-06-09T05:06:59Z | [
"python",
"pandas",
"dataframe",
"multi-index"
] |
How can I merge texts inside my JSON files | 37,717,258 | <p>The thing I have is like this:</p>
<pre><code> {
"locale": "WORLD",
"articles": [
{
"url": "Second url"
},
{
"url": "Second url"
}
]
}
</code></pre>
<p>and another file containing this:</p>
<pre><code>{
"locale": "WORLD",
"articles": [
{
"url": "First u... | 0 | 2016-06-09T05:07:29Z | 37,717,403 | <p>I suggest, you simply deserialize-transform-serialize as transformation scenario.</p>
<p>A non-compacting merge (leaving redundant dicts/objects the kind <code>{"url": "whatever"}</code> being elemtn of "articles" key list as is:</p>
<pre><code>#! /usr/bin/env python
from __future__ import print_function
import js... | 0 | 2016-06-09T05:20:21Z | [
"python",
"json"
] |
How to filter twitter with blank between characters? | 37,717,271 | <p>based on twitter streaming api <a href="https://dev.twitter.com/streaming/overview/request-parameters#track" rel="nofollow">track</a> and tweepy, I'd like to filter twitter posts contains
"A B" with code below:</p>
<pre><code>twitter_stream.filter(track=['A B'])
</code></pre>
<p>But the result are not expected:<... | 2 | 2016-06-09T05:08:38Z | 37,737,432 | <p>Encode space to '%20'.</p>
<pre><code>twitter_stream.filter(track=['A%20B'])
</code></pre>
| 0 | 2016-06-09T22:50:16Z | [
"python",
"nlp",
"web-crawler",
"tweepy",
"twitter-streaming-api"
] |
Print custom string with character and character count without using python built-in methods | 37,717,279 | <p>I would like to tweak my string to print the character and the character count without using python built-in methods. </p>
<pre><code>>>> string = 'aaaabbbddd'
</code></pre>
<p>I am looking for this output:</p>
<pre><code>a4b3d3
</code></pre>
| -1 | 2016-06-09T05:09:06Z | 37,717,361 | <p>This might look like a bit long but i hope this will solve your problem</p>
<pre><code>string='aaaabbbddd'
elems=set(string)
result=''
for ele in elems:
result = result+ele+str(string.count(ele))
</code></pre>
<p>Hope it helps. Happy Coding :) </p>
| 1 | 2016-06-09T05:16:55Z | [
"python",
"string"
] |
Print custom string with character and character count without using python built-in methods | 37,717,279 | <p>I would like to tweak my string to print the character and the character count without using python built-in methods. </p>
<pre><code>>>> string = 'aaaabbbddd'
</code></pre>
<p>I am looking for this output:</p>
<pre><code>a4b3d3
</code></pre>
| -1 | 2016-06-09T05:09:06Z | 37,717,613 | <p>Here is a way to do it with no built in methods!</p>
<pre><code>def count_modify(string):
d = {}
for i in string:
if i in d:
d[i] += 1
else:
d[i] = 1
return ''.join(str(x)+str(d[x]) for x in d)
</code></pre>
<p>Alternatively you could decide to not use the <code>... | 2 | 2016-06-09T05:35:28Z | [
"python",
"string"
] |
Get binary data with psycopg2 | 37,717,280 | <p>I have a column containing binary data. If I do <code>fetchone()</code> it is not giving me any data, instead I do <code>fetchall()</code> then get the result below. How can O get that binary data into a variable and then convert it into a base64 encoded string?</p>
<pre><code>con = psycopg2.connect(config.DB_CONNE... | 1 | 2016-06-09T05:09:09Z | 37,717,506 | <p>You need to read the buffer:</p>
<pre><code>import base64
# your code here
data = base64.encode(curo[0].read())
</code></pre>
| 0 | 2016-06-09T05:27:47Z | [
"python",
"postgresql",
"psycopg2"
] |
Get binary data with psycopg2 | 37,717,280 | <p>I have a column containing binary data. If I do <code>fetchone()</code> it is not giving me any data, instead I do <code>fetchall()</code> then get the result below. How can O get that binary data into a variable and then convert it into a base64 encoded string?</p>
<pre><code>con = psycopg2.connect(config.DB_CONNE... | 1 | 2016-06-09T05:09:09Z | 37,722,774 | <p><code>psycopg2</code> returns the binary data (probably stored in a <code>bytea</code> column in your table) in a <code>buffer</code> object in Python 2, or in a <a href="https://docs.python.org/3/library/stdtypes.html#memory-views" rel="nofollow"><code>memoryview</code></a> in Python 3.</p>
<p>Both <code>buffer</c... | 1 | 2016-06-09T10:01:38Z | [
"python",
"postgresql",
"psycopg2"
] |
How to make a list accept /n so that when writen to a file so that not everyting is on the same line? | 37,717,563 | <p>So this is my code for a random serial number generator and i can't figure out how to make each serial number appear on a different line at the moment they have only got spaces between them how do i make them appear on a new line?</p>
<pre><code>#!/usr/bin/python
import random, hashlib, os
from sys import exit
from... | 1 | 2016-06-09T05:32:43Z | 37,717,713 | <p><code>'\n'</code> is used to create a space in between two lines and <code>'\r'</code> is used to emulate a enter or return keypress. it can be appended, joined, etc... to any string in the following ways. <code>my_str+='\n'</code>, <code>'\n'.join(my_list)</code>, ''.join(str(x)+'\n' for x in my_list)` and more. wh... | 0 | 2016-06-09T05:42:24Z | [
"python",
"string",
"join"
] |
How to make a list accept /n so that when writen to a file so that not everyting is on the same line? | 37,717,563 | <p>So this is my code for a random serial number generator and i can't figure out how to make each serial number appear on a different line at the moment they have only got spaces between them how do i make them appear on a new line?</p>
<pre><code>#!/usr/bin/python
import random, hashlib, os
from sys import exit
from... | 1 | 2016-06-09T05:32:43Z | 37,717,717 | <p>Replace </p>
<pre><code>gencodelist.append(' ')
</code></pre>
<p>with</p>
<pre><code>gencodelist.append('\n')
</code></pre>
<p>It is working after this code change.</p>
| 1 | 2016-06-09T05:42:34Z | [
"python",
"string",
"join"
] |
How to neatly create association matrix based on cluster result in python? | 37,718,084 | <p>Say for five patterns, using clustering method, they are assigned three classes with label <code>[1,1,2,1,3]</code>, now I want to generate an 5*5 association matrix based on that, where in the matrix <code>1</code> means they are in same cluster and 0 means they are in different clusters.</p>
<p>Is there any neat ... | -1 | 2016-06-09T06:11:06Z | 37,718,201 | <p>If I understood correctly the desired output you can generate the matrix with list comprehension:</p>
<pre><code>>>> import pprint
>>> l = [1,1,2,1,3]
>>> res = [[int(x == y) for y in l] for x in l]
>>> pprint.pprint(res)
[[1, 1, 0, 1, 0],
[1, 1, 0, 1, 0],
[0, 0, 1, 0, 0],
[1,... | 0 | 2016-06-09T06:18:48Z | [
"python",
"cluster-analysis"
] |
How to neatly create association matrix based on cluster result in python? | 37,718,084 | <p>Say for five patterns, using clustering method, they are assigned three classes with label <code>[1,1,2,1,3]</code>, now I want to generate an 5*5 association matrix based on that, where in the matrix <code>1</code> means they are in same cluster and 0 means they are in different clusters.</p>
<p>Is there any neat ... | -1 | 2016-06-09T06:11:06Z | 37,983,419 | <p>You don't need a <em>library</em> to do this.</p>
<p>This is elementary math/logic and can neatly expressed in e.g. <code>numpy</code>.</p>
<p>Use the label vector, repeat it to square form and it's transpose <code>rep == rep.transpose()</code> is your association matrix.</p>
<p>Doing this in numpy will be more e... | 0 | 2016-06-23T06:00:01Z | [
"python",
"cluster-analysis"
] |
Removing Non English Sub headings and Paragraphs | 37,718,110 | <p>Hi I have a script which is able to remove subheadings and paragraphs but I am not able to remove paragraphs with non english subheadings and words.</p>
<p>For example, <strong>(Original Text)</strong>:</p>
<pre><code>=== Personal finance ===
Protection against unforeseen personal events, as well as events in the ... | -1 | 2016-06-09T06:13:09Z | 37,719,514 | <p>If you only want to detect if a string contains non english characters, thats easy: just try to decode it as <code>ascii</code>: if it fails, it contains character with code above 127:</p>
<pre><code>try:
utxt = txt.decode('ascii')
except:
# txt contains non "english" characters
...
</code></pre>
<p... | 1 | 2016-06-09T07:30:16Z | [
"python",
"python-2.7",
"wikipedia",
"wikipedia-api",
"non-english"
] |
Why the program only can run once.(PYTHON) | 37,718,172 | <pre><code>import gi
gi.require_version('Gst', '1.0')
from gi.repository import GObject #,Gtk
from gi.repository import Gst as gst
import datetime
def take_photo():
GObject.threads_init()
gst.init(None)
pipeline = gst.Pipeline()
video_source = gst.ElementFactory.make('v4l2src', 'video_source')
... | -3 | 2016-06-09T06:16:34Z | 37,724,621 | <p>What about implementing it as class, so do a proper initializationof gstreamer stuff.. and in take_photo you just play the pipe and stop it afterwards.. in should be reusable then (from gstreamer point of view.. pipe can go to NULL and PLAYING over and over):</p>
<pre><code>class TakePhoto:
def __init__(self)... | 0 | 2016-06-09T11:24:44Z | [
"python",
"python-2.7",
"gstreamer"
] |
web scraping: How to identify records in the database but removed on the Web | 37,718,176 | <p>Currently I'm using <code>Scrapy</code> to extract price from an online store. Say my first run extracted 100 products. After that, the store removed one product and added 2 new products. I'm wondering how to catch the removed product by comparing the new 101 products online and the old 100 products in my database?<... | 0 | 2016-06-09T06:16:59Z | 37,738,560 | <p>I think I figured out how to do this, so I will post it here if someone comes across this in the future.</p>
<p>The solution is to make a custom <a href="http://doc.scrapy.org/en/latest/topics/extensions.html" rel="nofollow">extension</a>,</p>
<pre><code>def __init__(self):
scraped_item_list = []
def from_cra... | 0 | 2016-06-10T01:17:38Z | [
"python",
"scrapy"
] |
groupby - python pandas dataframe | 37,718,183 | <p>I have a dataframe with columns <code>date</code>,<code>name</code>,<code>id</code> (data is redundant).<br>
Now i want to obtain the frequency of combination (<code>date</code>,<code>name</code>,<code>id</code>)
For that am applying <code>groupby</code> on my dataframe: </p>
<pre><code>df.groupby(['date','uname'... | 2 | 2016-06-09T06:17:33Z | 37,718,192 | <p>You need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html" rel="nofollow"><code>reset_index</code></a>:</p>
<pre><code>df.groupby(['date','uname','id']).size().reset_index()
date uname id size
0 2016-02-11 a@abc.com 111 1
1 20... | 2 | 2016-06-09T06:18:14Z | [
"python",
"pandas",
"dataframe",
"group-by",
"multi-index"
] |
Python Twisted frameowrk transport.write to a c# socket BeginReceive reading length based message framing value | 37,718,216 | <p>I'm using length based message framing with python twisted framework with a C# client running BeginRecieve async reads and I'm having trouble grabbing the value of the length of the message.</p>
<p>This is the twisted python code</p>
<blockquote>
<p>self.transport.write(pack(self.structFormat, len(string)) + str... | 0 | 2016-06-09T06:19:21Z | 37,736,839 | <p>Sorry the question was badly asked. I did find the solution though.</p>
<blockquote>
<p>int netmsg_size = BitConverter.ToInt32(state.buffer, 0);</p>
<p>int msg_size = IPAddress.NetworkToHostOrder(netmsg_size);</p>
</blockquote>
<p>This converts the network integer back into a regular integer.</p>
| 0 | 2016-06-09T21:56:42Z | [
"c#",
"python",
"sockets",
"twisted",
"beginreceive"
] |
PyQt5 draggable frameless window | 37,718,329 | <p>I found an example to set borders on a frameless window, however it's not draggable. How can I make a frameless window draggable? Especially if I can see an example it'll be awesome. Here is my example code(normally the code is longer, that's why there are much libraries just don't mind them);</p>
<pre><code>from ... | 1 | 2016-06-09T06:26:16Z | 37,718,648 | <p>You need to handle the mouse events yourself.</p>
<ul>
<li>We will need to add an event on <code>mousePressEvent</code>, which will keep the place where we last clicked on the window</li>
<li>Then, we will add a <code>mouseMoveEvent</code>, which will calculate the distance between the last clicked point and the cu... | 1 | 2016-06-09T06:46:12Z | [
"python",
"windows",
"python-3.4",
"pyqt5",
"qmainwindow"
] |
Plotting decision boundary for High Dimension Data | 37,718,347 | <p>I am building a model for binary classification problem where each of my data points is of <strong>300 dimensions</strong> (I am using 300 features). I am using a <em>PassiveAggressiveClassifier</em> from <em>sklearn</em>. The model is performing really well. </p>
<p><strong>I wish to plot the decision boundary of... | 2 | 2016-06-09T06:27:11Z | 37,917,341 | <p>One way is to impose a Voronoi tesselation on your 2D plot, i.e. color it based on proximity to the 2D data points (different colors for each predicted class label). See recent paper by <a href="http://dare.uva.nl/document/2/164710" rel="nofollow">Migut et al., 2015</a>.</p>
<p>This is a lot easier than it sounds u... | 1 | 2016-06-20T08:02:30Z | [
"python",
"plot",
"machine-learning",
"scikit-learn",
"data-science"
] |
Deleting xml tags with particular Element name using xml.dom in python | 37,718,441 | <p>How can we delete tags with particular Element name in an xml code using <code>xml.dom</code> (not <code>lxml.etree</code>) in python. </p>
<p>e.g. if we have the following xml code:</p>
<pre><code><?xml version="1.0"?>
<catalog>
<book id="bk101">
<author>Gambardella, Matthew</auth... | 0 | 2016-06-09T06:32:41Z | 37,718,916 | <p>Select all the elements by <code>title</code> tag and remove them using <code>removeChild</code></p>
<p><b>Update:</b></p>
<pre><code>from xml.dom import minidom
xmldoc = minidom.parse("book_xml.xml")
nodes = xmldoc.getElementsByTagName("title")
for node in nodes:
parent = node.parentNode
parent.removeCh... | 0 | 2016-06-09T07:00:06Z | [
"python",
"xml",
"dom"
] |
sys.argv arguments with spaces | 37,718,580 | <p>I'm trying to input folder names as sys.argv arguments, but am having problem with folder names that have spaces, which become multiple variables. </p>
<p>For example, from the command line below, "Folder Name" becomes two variables. </p>
<pre><code>Program.py D:\Users\Erick\Desktop\Folder Name
</code></pre>
<p>... | 0 | 2016-06-09T06:41:23Z | 37,718,627 | <p>Space is the delimiter for command line arguments. You'll be better off not using spaces in your directory and file names if possible. For entering an argument which has space in it you'll have to enclose it in quotes <code>"folder with space"</code>. </p>
<p><code>Program.py "D:\Users\Erick\Desktop\Folder Name"</... | 5 | 2016-06-09T06:44:57Z | [
"python"
] |
Create Scrapy never ending spider | 37,718,593 | <p>I've created a scrapy library <a href="https://github.com/rdcprojects/scrapy-mq-redis" rel="nofollow">scrapy-mq-redis</a> and want to make the spiders never ending. I've used spider_idle signal handler to stop it from closing (picked it from upstream library).</p>
<p>Is there a way to access scheduler in this funct... | 1 | 2016-06-09T06:42:17Z | 37,741,914 | <p>I found out that the scheduler is available in spider as below:</p>
<p><code>self.crawler.engine.slot.scheduler.next_request()</code></p>
<p>I added listener in spider as below:</p>
<p><code>self.crawler.signals.connect(self.spider_idle, signal=signals.spider_idle)</code></p>
<p>And the callback is as below:</p>... | 0 | 2016-06-10T07:03:14Z | [
"python",
"scrapy",
"pika"
] |
How to move a zip file to a folder | 37,718,688 | <p>I have a large no. of zip file whose name is only numerical. Now each zip file contains a folder having the same name as the zip file( ie if the name of the zip file is say 1234.zip then the name of the folder will also be 1234). Also this folder contains a text file say atextfile.txt, which contains integer specif... | 1 | 2016-06-09T06:48:19Z | 37,718,848 | <blockquote>
<p>Try with <a href="https://docs.python.org/2/library/subprocess.html" rel="nofollow">subprocess</a> and ROBOCOPY:</p>
</blockquote>
<pre><code>import glob
import os
import zipfile
import subprocess
for zip_name in glob.glob('[0-9]*.zip'):
z = zipfile.ZipFile(zip_name)
# To remove '.zip' from ... | 0 | 2016-06-09T06:56:59Z | [
"python",
"zip"
] |
How to move a zip file to a folder | 37,718,688 | <p>I have a large no. of zip file whose name is only numerical. Now each zip file contains a folder having the same name as the zip file( ie if the name of the zip file is say 1234.zip then the name of the folder will also be 1234). Also this folder contains a text file say atextfile.txt, which contains integer specif... | 1 | 2016-06-09T06:48:19Z | 37,719,104 | <p>The following works for me, there seemed to be a problem with the way you were getting the year.</p>
<pre><code>import glob
import os
import zipfile
import shutil
for zip_name in glob.glob('[0-9]*.zip'):
z = zipfile.ZipFile(zip_name)
subdir = os.path.splitext(zip_name)[0]
with z.open('{}/atextfile.txt... | 0 | 2016-06-09T07:10:38Z | [
"python",
"zip"
] |
How to get the angle(theta) value using the HoguhLineP? | 37,718,813 | <p>I have a sample code which will detect lines. I need to detect lines with a degree angle. But this code detects all the lines in the image. </p>
<pre><code>import cv2
import numpy as np
img = cv2.imread('myhouse.png')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray,50,150,apertureSize = 3)
minLi... | 1 | 2016-06-09T06:55:30Z | 37,718,927 | <p>Please refer the Documentation of
<a href="http://docs.opencv.org/3.0-beta/doc/py_tutorials/py_imgproc/py_houghlines/py_houghlines.html" rel="nofollow">Hough Line Transform</a>. </p>
<p>In my point of view, you cannot get the degree in HoughLinesP. You can get from HoughLines.</p>
| 0 | 2016-06-09T07:00:27Z | [
"python",
"opencv",
"image-processing",
"hough-transform"
] |
Variable Explorer in Jupyter Notebook | 37,718,907 | <p>Is there a variable explorer in Jupyter (IPython) like in Spyder? It is very uncomfortable having to print the list of variables all the time each time I run through the test code.</p>
<p>Has this feature been implemented yet? If so, you to enable it?</p>
| 2 | 2016-06-09T06:59:38Z | 37,719,560 | <p>This might help you, though it's not exactly what Spyder offers and is much simpler:</p>
<p>To get a list of all currently defined variables, run <strong>who</strong> :</p>
<pre><code>In [1]: foo = 'bar'
In [2]: who
foo
</code></pre>
<p>For more detail, run <strong>whos</strong>:</p>
<pre><code>In [3]: whos
Var... | 2 | 2016-06-09T07:32:10Z | [
"python",
"jupyter-notebook",
"facilities"
] |
how to plot the tensorflow neural network object | 37,718,934 | <p>I tried example code of tensorflow spiral dataset and constructed the neural network. I wanted to visualize the graphical structure of the network.
PFB the code i tried.</p>
<pre><code>with tf.Graph().as_default():
net = tflearn.input_data([None, 2])
net = tflearn.fully_connected(net,6,
act... | 1 | 2016-06-09T07:00:54Z | 37,726,760 | <p>To visualize a graph, you should use TensorBoard. Here is a <a href="https://www.tensorflow.org/versions/r0.9/how_tos/summaries_and_tensorboard/index.html" rel="nofollow">tutorial</a> for how to use it.</p>
<p>You can add at the end of your code a summary writer, which will write an event file (containing the visua... | 1 | 2016-06-09T13:01:32Z | [
"python",
"tensorflow"
] |
Why is my list not saving correctly (python) | 37,718,963 | <p>When I print each item separately (see comment below), they come out correctly. However, when I try to populate the list with the dictionaries, it comes out empty! Can anyone figure out why?</p>
<pre><code>def getAnnualSnow(allData):
annualSnow = []
year = allData[0]['year']
totalSnow = 0
for month... | 0 | 2016-06-09T07:02:49Z | 37,719,159 | <p>maybe don't return if list is empty ?
I only changed the last else.</p>
<pre><code> if year <= 2012:
if monthData['year'] == year:
totalSnow = totalSnow + monthData['snow']
else:
totalAnnSnow = {'year':year, 'totalsnow':round(totalSnow,1)}
#print(totalAnnSno... | 0 | 2016-06-09T07:13:01Z | [
"python",
"list"
] |
Why is my list not saving correctly (python) | 37,718,963 | <p>When I print each item separately (see comment below), they come out correctly. However, when I try to populate the list with the dictionaries, it comes out empty! Can anyone figure out why?</p>
<pre><code>def getAnnualSnow(allData):
annualSnow = []
year = allData[0]['year']
totalSnow = 0
for month... | 0 | 2016-06-09T07:02:49Z | 37,719,272 | <p>Okay. So I think what's causing your confusion is that the function doesn't return anything (None?). Look at the modified else part below, I've only added a return statement. </p>
<pre><code>def getAnnualSnow(allData):
annualSnow = []
year = allData[0]['year']
totalSnow = 0
for monthData in allData... | 0 | 2016-06-09T07:18:53Z | [
"python",
"list"
] |
pip upgrade not happening in python 2.7 | 37,719,204 | <p>I am in confusion. I have looked in other posts in regard to this problem. In terminal of conda env., when I ran </p>
<pre><code>conda list
</code></pre>
<p>all the packages are displayed with versions. pip version is 8.0.2</p>
<p>When I tried </p>
<pre><code> python -m pip install --upgrade pip
</code></pre>
<... | 1 | 2016-06-09T07:15:36Z | 37,719,464 | <p>Upgrade pip:</p>
<pre><code>pip install --upgrade pip
</code></pre>
<p>Upgrade all packages with pip:</p>
<pre><code>import pip
from subprocess import call
for dist in pip.get_installed_distributions():
call("pip install --upgrade " + dist.project_name, shell=True)
</code></pre>
| 0 | 2016-06-09T07:27:58Z | [
"python",
"pip",
"anaconda"
] |
change image features programmically | 37,719,261 | <p>This is for a hobby project of mine.</p>
<p>It's a real world like political game. In it there is a lot of characters like politicians, military officers, religious figures etc. All these characters features are to be generated dynamically and stored in as game progresses. This includes, characters name, age, c... | 0 | 2016-06-09T07:18:33Z | 37,719,963 | <p>I wonder what your expectations are. </p>
<pre class="lang-py prettyprint-override"><code>from dynamicPeopleVectorCreater.magic import *
</code></pre>
<p>if you are talking about a character creator, then you have to do it on your own. And i am absolutely sure it is hard work, even business company may spent a lot... | 1 | 2016-06-09T07:53:49Z | [
"javascript",
"python",
"angularjs",
"image",
"image-processing"
] |
Singleton/Borg pattern based on different parameters passed while creating the object | 37,719,280 | <p>I am using borg pattern to share state amongst the objects:</p>
<pre><code>class Borg:
__shared_state = {}
def __init__(self):
self.__dict__ = self.__shared_state
</code></pre>
<p>Now lets assume that I want to create context based objects of the Borg class, based on parameters I pass while creati... | 1 | 2016-06-09T07:19:18Z | 37,719,460 | <p>No, what you use is what I'd use; use a dictionary for the shared states.</p>
<p>You can simplify it <em>slightly</em> by using the return value of <code>dict.setdefault()</code> rather than ignore it:</p>
<pre><code>def __init__(self, *args, **kwargs):
context_key = hash('{0}{1}'.format(cPickle.dumps(args),cP... | 2 | 2016-06-09T07:27:47Z | [
"python",
"python-2.7"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.