title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
How to extract numbers just succeeding a unicode character with regex in Python?
37,918,637
<p>I have the following file name sample:</p> <p>./data/DDT - T = 10 K/DDT - T = 10 K - φ = 1.0/DDT - T = 10 K - φ = 1.0 - DCT 0/DDT - Result - T = 10 K - φ = 1.0 - DCT 10-40 - t = 1000 s.dat</p> <p>And I am trying to extract the value of φ using regex in Python with the code:</p> <pre><code>import numpy as np i...
0
2016-06-20T09:12:47Z
37,922,432
<p>I think you just mix up the byte strings and Unicode strings. You need to make sure you deal with one type of strings when processing text, you cannot mix them up. So, if you need to keep the byte strings, do not use <code>u''</code> prefix from your strings, and keep <code>str('...')</code>:</p> <pre><code>file_na...
1
2016-06-20T12:18:21Z
[ "python", "regex", "unicode" ]
How to extract numbers just succeeding a unicode character with regex in Python?
37,918,637
<p>I have the following file name sample:</p> <p>./data/DDT - T = 10 K/DDT - T = 10 K - φ = 1.0/DDT - T = 10 K - φ = 1.0 - DCT 0/DDT - Result - T = 10 K - φ = 1.0 - DCT 10-40 - t = 1000 s.dat</p> <p>And I am trying to extract the value of φ using regex in Python with the code:</p> <pre><code>import numpy as np i...
0
2016-06-20T09:12:47Z
37,927,564
<p>Just use Unicode strings. Here's a simplified version that works. If you save the source as UTF-8 and declare the source encoding you can use the actual <code>φ</code> character as well, but using Unicode escapes works, too.</p> <pre><code>#encoding:utf8 import re file_names = [u'./data/DDT - T = 10 K/DDT - T =...
1
2016-06-20T16:33:39Z
[ "python", "regex", "unicode" ]
Intersection between two segments algorithm misses out intersections
37,918,677
<p>I am currently looking into making a simple shadow casting algorithm for a small 2D game. As much as possible I would like to give it a try myself before using optimised libraries.</p> <p>I feel like I am almost there but for some reason the method I use to detect the intersection between the ray from my line sourc...
0
2016-06-20T09:14:41Z
37,919,509
<p>Your function is defective - pieces like <code>X1 +=0.1</code> cause weird behavior (it is clear near ends of vertical segments). Use some robust implementation like <a href="http://www.ahristov.com/tutorial/geometry-games/intersection-segments.html" rel="nofollow">this simple one</a><br> (Alexander Hristov. Java bu...
1
2016-06-20T09:56:44Z
[ "python", "algorithm", "python-2.7", "pygame", "shadow" ]
Best practice for parametrizing multiple subfunctions
37,918,722
<p>I often run into a situation where I have a top level function from which I want to be able to modify any of the parameters of multiple subfunctions. I'll express this as the following example:</p> <pre><code>def plot_data_processing(data_param_1=3, data_param_N=4, processing_param_1='a', processing_param_2...
0
2016-06-20T09:16:28Z
37,920,051
<p>Python 3.5 has a new (optional) type hinting system that might do what you want. It's not checked at run-time by the Python interpreter, but does allow you to make statements about the types of arguments and return function values. A separate static analyzer program like <a href="http://mypy-lang.org/" rel="nofollow...
1
2016-06-20T10:22:43Z
[ "python", "functional-programming" ]
Using Django HyperlinkedModelSerializer with prefixed view names
37,918,746
<p>I'm currently trying to use HyperlinkedModelSerializer, but I'm getting the error: </p> <pre><code>Could not resolve URL for hyperlinked relationship using view name "house-detail" </code></pre> <p>That should be "backend:house-detail", all views in my REST api have that "backend:" prefix. How can I have Django RE...
1
2016-06-20T09:17:40Z
37,919,157
<p>To do it manually, do this:</p> <pre><code>class HouseSerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField( view_name='backend:house-detail' ) ... </code></pre> <p>Still not sure how to do it automatically though, so if I ever change the prefix I need...
0
2016-06-20T09:38:07Z
[ "python", "django", "django-rest-framework" ]
Using Django HyperlinkedModelSerializer with prefixed view names
37,918,746
<p>I'm currently trying to use HyperlinkedModelSerializer, but I'm getting the error: </p> <pre><code>Could not resolve URL for hyperlinked relationship using view name "house-detail" </code></pre> <p>That should be "backend:house-detail", all views in my REST api have that "backend:" prefix. How can I have Django RE...
1
2016-06-20T09:17:40Z
37,919,221
<blockquote> <p>Still not sure how to do it automatically though, so if I ever change the prefix I need to change things manually.</p> </blockquote> <p>This is when using base classes and inheritance can help</p> <pre><code>class PrefixedSerializer(serializers.HyperlinkedModelSerializer): prefix = 'backend' ...
1
2016-06-20T09:41:36Z
[ "python", "django", "django-rest-framework" ]
Why is this server program not able to send anything to the client?
37,918,876
<p>I am basically trying to make a chatting app but here I am unable to send anything from the server to the client. How do I correct this? server program:</p> <pre><code>from socket import * host=gethostname() port=7777 s=socket() s.bind((host, port)) s.listen(5) print "Server is Ready!" while True: c, addr= s.ac...
1
2016-06-20T09:24:10Z
37,919,532
<p>You cannot use the connection socket to send or receive objects so the problem is there only....</p> <p>Use - </p> <pre><code>c.sendto("Received", addr) </code></pre> <p>instead of </p> <pre><code>s.sendto("received", addr) </code></pre> <p>Second problem is you are not receiving the messages from the socket.....
0
2016-06-20T09:57:30Z
[ "python", "python-2.7", "sockets", "python-sockets" ]
TypeError: set_name() missing 1 required positional argument: 'name'
37,918,887
<pre><code>class Animal: __name = None __height = 0 __weight = 0 __sound = 0 def __init__(self, name, height, weight, sound): self.__name = name self.__height = height self.__weight = weight self.__sound = sound def set_name(self, name): self.__name = n...
-1
2016-06-20T09:24:50Z
37,919,018
<p>The problem is that you used <code>set..()</code> instead of <code>get_..()</code> at the <code>toString</code> method of the <code>Dog</code> class </p> <pre><code>def toString(self): return '{} is {} cm tall and {} kilograms and says {}. His owner is {}'.format(self.get_name(), ...
0
2016-06-20T09:31:22Z
[ "python", "typeerror" ]
Selenium: How do I get a text within a <td> tag and then click the Javascript link of it's sibling?
37,918,891
<p>I have a list of forms that I need to edit one by one wherein I have to identify the form title first and then click the JavaScript link to open it's editing template.</p> <p>In the sample code below, I need to identify the text <code>Another Custom Form (Mobile)</code> which is the form title and then click the <c...
2
2016-06-20T09:25:00Z
37,920,851
<p>I would approach this by:</p> <ul> <li><ol> <li>creating a class to represent a row in this table, say <strong>"MyRow"</strong>, which has method to interact with each column as a field in the class.</li> </ol></li> <li><ol start="2"> <li>using Selenium to find all of the rows in the table, returning a list of inst...
1
2016-06-20T11:02:10Z
[ "python", "html", "selenium" ]
Selenium: How do I get a text within a <td> tag and then click the Javascript link of it's sibling?
37,918,891
<p>I have a list of forms that I need to edit one by one wherein I have to identify the form title first and then click the JavaScript link to open it's editing template.</p> <p>In the sample code below, I need to identify the text <code>Another Custom Form (Mobile)</code> which is the form title and then click the <c...
2
2016-06-20T09:25:00Z
37,921,232
<p>You can perform click on <code>link</code> with following single <code>xPath</code> where you can provide text <code>Another Custom Form (Mobile)</code> to identify their <code>following-sibling</code> and get that <code>link</code> as as below :-</p> <pre><code>link = browser.find_element_by_xpath("//td[contains(t...
0
2016-06-20T11:20:52Z
[ "python", "html", "selenium" ]
Flask Request showing 400 Bad Request and redirects to '/' instead of '/someURL'
37,918,970
<p>I am creating an app to take info (sort of login) from <strong>index.html</strong> and then redirect to second html page <strong>capture_simple.html</strong>. But on sending post request from the second page the server show Error 400 and later redirects back to '/' ('/' is where the error is shown) instead of remai...
0
2016-06-20T09:29:23Z
37,921,875
<p>So, I am answering my own question. </p> <p>The problem was I had </p> <pre><code>action="." </code></pre> <p>in my form in <strong>capture_simple.html</strong> file, so it was sending the request to the '/' root and creating all trouble.</p> <p>Just drop the action attribute from the form and it works perfectl...
0
2016-06-20T11:52:52Z
[ "python", "html", "http", "flask", "request" ]
DECREF'ing after a call to PyArray_DATA
37,919,094
<p>I'm writing a Python extension in C. My function takes a list of Numpy arrays (that contain integers) as a parameter. I go through the list, get each array, increase the reference, get the C pointers to the array and then decrease the reference.</p> <pre><code>if (!PyArg_ParseTuple(args, "O", &amp;list)) return...
3
2016-06-20T09:35:25Z
37,920,911
<p><code>PyArray_DATA</code> has no effect on the reference count of the array it is applied to. Furthermore, when the list that was passed to your function was created, the reference count of each of the arrays in it was increased by one. So while they don't hurt much, those <code>Py_INCREF</code> and <code>Py_DECRE...
3
2016-06-20T11:05:13Z
[ "python", "c", "numpy" ]
pyqt system tray icon exit when click menu item
37,919,169
<p>I am new to python and pyqt, I learn them today and write a small system tray demon, it run , but when i click "about", and then close the dialog, the app exit. I don't know why</p> <p>Simple code as follow:</p> <pre><code>import sys from PyQt4 import QtGui class SystemTrayIcon(QtGui.QSystemTrayIcon): def __...
0
2016-06-20T09:38:38Z
37,923,510
<p>You can set the application quitOnLastWindowClosed property to False:</p> <pre><code>def main(): app = QtGui.QApplication(sys.argv) app.setQuitOnLastWindowClosed(False) trayIcon = SystemTrayIcon(QtGui.QIcon("trash.svg")) trayIcon.show() sys.exit(app.exec_()) </code></pre>
1
2016-06-20T13:11:36Z
[ "python", "pyqt" ]
Python reading Popen continuously (Windows)
37,919,319
<p>Im trying to <code>stdout.readline</code> and put the results (i.e each line, at the time of printing them to the terminal) on a <code>multiprocessing.Queue</code> for us in another .py file. However, the call:</p> <pre><code>res = subprocess.Popen(command, stdout=subprocess.PIPE, bufsize=1 ) with res.stdout: f...
0
2016-06-20T09:47:38Z
37,924,202
<p>As explained by @eryksun, and confirmed by your comment, the cause of the buffering is the use of <code>printf</code> by the C application.</p> <p>By default, printf buffers its output, but the output is flushed on newline or if a read occurs <strong>when the output is directed to a terminal</strong>. When the outp...
1
2016-06-20T13:45:55Z
[ "python", "windows", "io", "subprocess" ]
Response is blank while downloading a the pdf form amazonaws
37,919,339
<p>I am trying to download the pdf file from this <a href="https://ap-prod-ddc-stack-content.s3.amazonaws.com/devtestbed-prod-01/ABC000128CEC2.pdf?AWSAccessKeyId=AKIAJZ2VLLVH5FAWOGYA&amp;Expires=1466500635&amp;Signature=itUWZwiOiWwH%2BPihTYMjoq1URFw%3D" rel="nofollow">link</a> using python 2.7 requests:</p> <p><a href...
0
2016-06-20T09:48:44Z
37,919,790
<p>All you need to do next is to save the content to file as bytes (using 'wb' flag) and not as string, because the content is byte code.</p> <p><strong>Add this to the end of your code:</strong></p> <pre><code>with open('PATH\downloaded.pdf', 'wb') as file: file.write(response.content) </code></pre> <p><strong>...
2
2016-06-20T10:09:49Z
[ "python", "amazon-web-services", "http-headers", "python-requests", "request-headers" ]
Python data aggregation on X and Y axes
37,919,464
<p>Need some help with data aggregaion in Python.</p> <p>I have a Dataframe with 3 columns and N rows. First two columns contains indices (let it be <code>X</code> and <code>Y</code>), the last one contains values. The task is to calc a <code>sum()</code> of values of third column [corresponding with <code>(x_i,y_j)</...
0
2016-06-20T09:54:42Z
37,919,882
<p>You want to pivot your data. Example:</p> <pre><code>In [5]: data = {'ind1': ['x1','x2','x3','x1','x2','x3'], 'ind2': ['y1','y1','y1','y2','y2','y2'], 'value': ['k1','k2','k3','k4','k5','k6']} In [6]: pd.DataFrame(data=data) Out[6]: ind1 ind2 value 0 x1 y1 k1 1 x2 y1 k2 2 x3 y1 k3 3 x1 ...
2
2016-06-20T10:14:47Z
[ "python", "pandas" ]
Removing characters from a string in pandas
37,919,479
<p>I have a similar question to this one: <a href="http://stackoverflow.com/questions/13682044/pandas-dataframe-remove-unwanted-parts-from-strings-in-a-column">Pandas DataFrame: remove unwanted parts from strings in a column</a>.</p> <p>So I used: </p> <pre><code>temp_dataframe['PPI'] = temp_dataframe['PPI'].map(lamb...
0
2016-06-20T09:55:23Z
37,919,503
<p>use vectorised <code>str.lstrip</code>:</p> <pre><code>temp_dataframe['PPI'] = temp_dataframe['PPI'].str.lstrip('PPI/') </code></pre> <p>it looks like you may have missing values so you should mask those out or replace them:</p> <pre><code>temp_dataframe['PPI'].fillna('', inplace=True) </code></pre> <p>or</p> <...
2
2016-06-20T09:56:34Z
[ "python", "pandas" ]
Removing characters from a string in pandas
37,919,479
<p>I have a similar question to this one: <a href="http://stackoverflow.com/questions/13682044/pandas-dataframe-remove-unwanted-parts-from-strings-in-a-column">Pandas DataFrame: remove unwanted parts from strings in a column</a>.</p> <p>So I used: </p> <pre><code>temp_dataframe['PPI'] = temp_dataframe['PPI'].map(lamb...
0
2016-06-20T09:55:23Z
37,920,391
<p>use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.replace.html" rel="nofollow">replace</a>: </p> <pre><code>temp_dataframe['PPI'].replace('PPI/','',regex=True,inplace=True) </code></pre> <p>or <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.replac...
0
2016-06-20T10:39:33Z
[ "python", "pandas" ]
Converting a hex values to ASCII
37,919,586
<p>What is the most 'Pythonic' way of translating</p> <pre><code>'\xff\xab\x12' </code></pre> <p>into</p> <pre><code>'ffab12' </code></pre> <p>I looked for functions that can do it, but they all want to translate to ASCII (so <code>'\x40'</code> to <code>'a'</code>). I want to have the hexadecimal digits in ASCII.<...
0
2016-06-20T09:59:37Z
37,919,629
<pre><code>original = '\xff\xab\x12' result = original.replace('\\x', '') print result </code></pre> <p>It's <code>\x</code> because it's escaped. <code>a.replace(b,c)</code> just replaces all occurances of <code>b</code> with <code>c</code> in <code>a</code>.</p> <p>What you want is not ascii, because ascii translat...
0
2016-06-20T10:01:27Z
[ "python", "string", "python-2.7" ]
Converting a hex values to ASCII
37,919,586
<p>What is the most 'Pythonic' way of translating</p> <pre><code>'\xff\xab\x12' </code></pre> <p>into</p> <pre><code>'ffab12' </code></pre> <p>I looked for functions that can do it, but they all want to translate to ASCII (so <code>'\x40'</code> to <code>'a'</code>). I want to have the hexadecimal digits in ASCII.<...
0
2016-06-20T09:59:37Z
37,919,880
<p>There's a module called <code>binascii</code> that contains functions for just this:</p> <pre><code>&gt;&gt;&gt; import binascii &gt;&gt;&gt; binascii.hexlify('\xff\xab\x12') 'ffab12' &gt;&gt;&gt; binascii.unhexlify('ffab12') '\xff\xab\x12' </code></pre>
4
2016-06-20T10:14:45Z
[ "python", "string", "python-2.7" ]
Converting streaming data to feature table - analysing streaming data
37,919,725
<p>I am streaming some data from an api regarding users of a SaaS widget, and want to do some analysis based on 'user activity' to find efficiencies in the process. I'm hoping to answer questions such as 'what (groups of) user actions lead to successful completion' etc.</p> <p>Currently, the data is a timestamped log ...
0
2016-06-20T10:06:23Z
37,922,510
<p>I don't fully understand your output. Where goes the timestamp column? How do you choose <code>Cat1</code> and <code>Cat2</code> values?</p> <p>As for the rest you can use <code>get_dummies</code> and <code>groupby</code>:</p> <p>Creating the input dataframe:</p> <pre><code>import io temp = u"""Timestamp User ...
1
2016-06-20T12:23:10Z
[ "python", "pandas" ]
Auto it click exception: access violation reading 0x00000083
37,919,770
<p>My code should open a window from taskbar and then click a control from it. The problem is that after it opens the window I get the error : "exception: access violation reading 0x00000083".I am new to Python (and in programing) and I have no ideea what that means or how to solve it.My code looks like this :</p> <pr...
0
2016-06-20T10:08:37Z
37,983,792
<p>I don't know if that works but change the 2 to 2000. Because in the normal AutoIt version you enter the time in ms not in s. And the minimal wait time is 10ms. Maybe that's what causes the error!</p>
0
2016-06-23T06:27:03Z
[ "python", "exception", "exception-handling", "automation", "autoit" ]
No output from child Python executed with subprocess
37,919,793
<p>This is a simple command that works from command line:</p> <pre><code>&gt; python -c "print('asdasd')" asdasd </code></pre> <p>But it fails to output anything when executed from the script:</p> <pre class="lang-py prettyprint-override"><code>import os import sys import subprocess cmd = [sys.executable] + ['-c', ...
1
2016-06-20T10:09:53Z
37,921,095
<p>First, you don't need those extra double-quotes for <code>'"print(\'asdasd\')"'</code> in your command line arguments. As it is, your code will just execute a python code that do the following: <code>"print(\'asdasd\')"</code>. In other word, it will produce the string: <em>print(\'asdasd\')</em></p> <p>Obviously, ...
1
2016-06-20T11:13:40Z
[ "python", "subprocess" ]
No output from child Python executed with subprocess
37,919,793
<p>This is a simple command that works from command line:</p> <pre><code>&gt; python -c "print('asdasd')" asdasd </code></pre> <p>But it fails to output anything when executed from the script:</p> <pre class="lang-py prettyprint-override"><code>import os import sys import subprocess cmd = [sys.executable] + ['-c', ...
1
2016-06-20T10:09:53Z
37,921,099
<p>Try this:</p> <pre><code>subprocess.Popen(['{} -c "print(\'ECHO\')"'.format(sys.executable)], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate() </code></pre>
0
2016-06-20T11:13:53Z
[ "python", "subprocess" ]
Suppress 'u' in Output - Python
37,919,884
<p>How can i get rid of these <code>u</code> in output?</p> <p>Regex: </p> <p>Tregex1 = <code>"1?\W*([2-9][0-8][0-9])\W*([2-9][0-9]{2})\W*([0-9]{4})(\se?x?t?(\d*))?"</code></p> <p>Code:</p> <pre><code>for a in re.findall(Tregex1,text_value,re.IGNORECASE): print a </code></pre> <p>Output:</p> <pre><code>(u...
0
2016-06-20T10:14:51Z
37,919,997
<p>Your problem is not the <code>u</code>. If you want to format your results in a specific way, you should use the string formatting functions.</p> <pre><code>print '-'.join(a) </code></pre>
1
2016-06-20T10:20:10Z
[ "python", "regex", "encoding" ]
Suppress 'u' in Output - Python
37,919,884
<p>How can i get rid of these <code>u</code> in output?</p> <p>Regex: </p> <p>Tregex1 = <code>"1?\W*([2-9][0-8][0-9])\W*([2-9][0-9]{2})\W*([0-9]{4})(\se?x?t?(\d*))?"</code></p> <p>Code:</p> <pre><code>for a in re.findall(Tregex1,text_value,re.IGNORECASE): print a </code></pre> <p>Output:</p> <pre><code>(u...
0
2016-06-20T10:14:51Z
37,920,035
<p>The u just means it is unicode. You can recode it as you wish. This will work, and also skip the blank values:</p> <pre><code>a = (u'877', u'638', u'7848', u'\n', u'') print "-".join([x.strip() for x in a if x.strip() != u""]) </code></pre> <blockquote> <p>877-638-7848</p> </blockquote>
1
2016-06-20T10:21:42Z
[ "python", "regex", "encoding" ]
Suppress 'u' in Output - Python
37,919,884
<p>How can i get rid of these <code>u</code> in output?</p> <p>Regex: </p> <p>Tregex1 = <code>"1?\W*([2-9][0-8][0-9])\W*([2-9][0-9]{2})\W*([0-9]{4})(\se?x?t?(\d*))?"</code></p> <p>Code:</p> <pre><code>for a in re.findall(Tregex1,text_value,re.IGNORECASE): print a </code></pre> <p>Output:</p> <pre><code>(u...
0
2016-06-20T10:14:51Z
37,920,062
<p>try this:</p> <pre><code>for a in re.findall(Tregex1,text_value,re.IGNORECASE): print '-'.join(a[:3]) </code></pre> <p>the u just tells you that it's a unicode string.</p> <p>the (..., ...,) is the representation of the tuples</p> <p>what '-'.join(...) does is connect the strings of ... with a -</p> <p>a[:3...
2
2016-06-20T10:23:10Z
[ "python", "regex", "encoding" ]
Recreating sentences with numbers
37,919,936
<p>So I have developed a code which lets you recreate a sentence but there is one problem,it cuts out a word! I don't know why so if somebody can correct it that would be brilliant thanks! </p> <pre><code>Sentence = input("Please enter a sentence: ") Sen = Sentence.split() remove=(",") numbers = input("Enter Numbers(...
-1
2016-06-20T10:17:34Z
37,920,088
<p>These lignes are responsible for that behaviour : </p> <pre><code># length = len(numlist) -1 # &lt;==== comment these lines # del numlist[length] # &lt;==== comment these lines </code></pre> <p>Put them in comments, or remove them :</p> <pre><code>Sentence = input("Please enter a sentence: ") Sen = Sentence.spli...
1
2016-06-20T10:24:10Z
[ "python" ]
Updating Context in Odoo 8
37,920,044
<p>I am writing a method that it first will retrieve the current context from the model then using context.update() to add on new values for the context. I also tried to use the current method self.with_context() but still no success since the context values seem frozen and could not be passed in. I read online from s...
2
2016-06-20T10:22:24Z
37,921,991
<p>You already passing new context in return. Just remove self.with_context(context) line. As per below code.</p> <pre><code>def get_print_report(self): domain = [('effective_date', '&gt;=', self.from_date), ('effective_date', '&lt;=', self.to_date), ('employee_id', 'in', self.employee_ids.ids), ...
0
2016-06-20T11:57:53Z
[ "python", "openerp" ]
Python 3.4 Multiprocessing, code does not progress past loop (containing Queue)
37,920,071
<p>I have written a bit of code to test out multiprocessing before I implement in other code. The main code sends a number to the other program (running on another core). That program increments and returns the number. main code increments and returns the value again. All works well, but the loop in the main program, w...
1
2016-06-20T10:23:36Z
37,921,585
<p>After the slave process exits, your master process does one more <code>r.put()</code> and then keeps waiting for <code>q.get()</code> to return. You can solve the problem by providing a timeout value (in seconds) to <code>q.get()</code>:</p> <pre><code>ThisVar = int(q.get(timeout=1)) + 1 </code></pre> <p>Note that...
1
2016-06-20T11:38:04Z
[ "python", "python-3.x", "multiprocessing" ]
Legend related to span
37,920,197
<p>I would like to add a legend which explains what each span represents in the figure and I'm having trouble to find out how to do that, since I'm new to Python/matplotlib.</p> <p>So, I don't want a legend which explains each of the lines in my graphic, but I want to split the graphic using spans in different color a...
3
2016-06-20T10:28:58Z
37,920,769
<p>Since the legend you want does not seem refer to the actual data but some properties in your plot, I'd recommend to use <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.text" rel="nofollow"><code>pylot.text</code> or <code>pyplot.annotate</code></a>. With these commands you can freely position yo...
1
2016-06-20T10:57:50Z
[ "python", "matplotlib" ]
Python - struct.pack vs struck.packinto
37,920,231
<p>I am writing a program where i need to send lots of small chunks of data to a server (mostly integers or strings), so i am using the struct-library. Right now i am using <code>struct.pack</code>, but i am wondering if i should use <code>struct.pack_into</code> instead, as i read it reduces overhead.</p> <p>However...
0
2016-06-20T10:30:55Z
37,920,362
<p>The difference between these methods really revolves around whether you already have an <strong>existing</strong> buffer you wish to write formatted data into (<code>struct.pack_into</code>), or whether you simply want to create a <strong>new</strong> buffer with the formatted data (<code>struct.pack</code>).</p> <...
1
2016-06-20T10:37:04Z
[ "python", "pack" ]
Generate Dynamic HTML page based on clicks in Flask
37,920,427
<p>I have multiple links in table. Each row represents a link. I want to redirect the link into another page for its description. To implement it, I want to use a common template where based on the clicked link, dynamically the HTML page will be filled with the information. The url needs to be dynamic too, appended by ...
-1
2016-06-20T10:40:48Z
37,922,721
<p>you can embed the item identifier in links </p> <pre><code>&lt;a href="/items/item1"&gt;item 1&lt;/a&gt; </code></pre> <p>and in route you can extract the identifier</p> <pre><code>@app.route('/items/&lt;item_identifier&gt;') def show_item_info(item_identifier): print item_identfier # query the db for ite...
1
2016-06-20T12:33:48Z
[ "javascript", "python", "html", "flask" ]
Pandas - Get values within parentheses of a panda dataframe column
37,920,443
<p>My <code>df</code> has 2 columns:</p> <pre><code>Name Attr a(bc) b(aca) (cba) </code></pre> <p>I would like the column <code>Attr</code> to have the values within parentheses of column <code>Name</code></p> <pre><code>Name Attr a(bc) bc b(aca) aca (cba) cba </code></pre> <p>I tried:</p> <pre><code>df...
1
2016-06-20T10:41:31Z
37,920,506
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.extract.html" rel="nofollow"><code>str.extract</code></a>:</p> <pre><code>df['Attr'] = df['Name'].str.extract(r"\(([A-Za-z]+)\)", expand=False) print (df) Name Attr 0 a(bc) bc 1 b(aca) aca 2 (cba) cba </code></pre> <...
1
2016-06-20T10:44:50Z
[ "python", "regex", "pandas", "dataframe", "parentheses" ]
How to identify more than one list item in a for loop
37,920,480
<p>I'm trying to identify keywords in a DataFrame column, then create new binary columns when the keywords are identified. The reproducible example below works when the individual string lists contain just a single keyword to identify; it also highlights at stage 2 where the problem lies. </p> <p>The problem is I want...
1
2016-06-20T10:43:12Z
37,921,310
<p>As written, when you add additional keywords, the length of the resulting pay_col list exceeds the number of rows in your dataframe which is causing the referenced error. </p> <p>Modify this code block:</p> <pre><code>for row in test['comment']: for pay in pay_strings: if pay in row: pay_co...
1
2016-06-20T11:25:07Z
[ "python", "for-loop", "pandas" ]
Sum of Timedeltas column in Pandas Python
37,920,497
<p>A similar question has been asked <a href="http://stackoverflow.com/questions/4049825/how-to-get-the-sum-of-timedelta-in-python">here</a> before</p> <p>But when I tried all the available solutions it was giving me error.</p> <p>Code:</p> <pre><code>print sum(data['Activity_Duration'],datetime.timedelta()) #impo...
1
2016-06-20T10:44:24Z
37,921,025
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.sum.html" rel="nofollow"><code>sum</code></a>:</p> <pre><code>print (df['Activity_Duration'].sum()) </code></pre> <p>Sample:</p> <pre><code>import pandas as pd start = pd.to_datetime('2015-02-24') end = pd.to_datetime('...
1
2016-06-20T11:10:05Z
[ "python", "pandas", "sum", "timedelta" ]
str is not callable or int is not callable
37,920,585
<p>[Solved] I have made a program in Python using classes, but it is continuously saying <code>'str' object is not callable</code>, and if I try commenting lines 7,8 and 16, then it says <code>'int' object is not callable</code>.</p> <pre><code>class Lambo: def __init__(self, color, model_number, average, milage)...
-2
2016-06-20T10:49:07Z
37,920,651
<p>Your methods and attributes have the same names.</p>
1
2016-06-20T10:52:10Z
[ "python" ]
str is not callable or int is not callable
37,920,585
<p>[Solved] I have made a program in Python using classes, but it is continuously saying <code>'str' object is not callable</code>, and if I try commenting lines 7,8 and 16, then it says <code>'int' object is not callable</code>.</p> <pre><code>class Lambo: def __init__(self, color, model_number, average, milage)...
-2
2016-06-20T10:49:07Z
37,920,657
<p>You're using <code>color</code> (etc.) as both the name of a variable (a string) and the name of a method. You can't do that in python. </p> <p>The error <code>str is not callable</code> means that you're putting parentheses after a string variable (hence trying to "call" it like a function). Whenever you see this,...
3
2016-06-20T10:52:17Z
[ "python" ]
str is not callable or int is not callable
37,920,585
<p>[Solved] I have made a program in Python using classes, but it is continuously saying <code>'str' object is not callable</code>, and if I try commenting lines 7,8 and 16, then it says <code>'int' object is not callable</code>.</p> <pre><code>class Lambo: def __init__(self, color, model_number, average, milage)...
-2
2016-06-20T10:49:07Z
37,920,659
<p>Your instance has the following attributes:</p> <pre><code>self.color = color self.model_number = model_number self.average = average self.milage = milage </code></pre> <p>Those <em>mask</em> the methods you defined; methods are just more attributes, but Python looks at the instance first, and only then at the cla...
3
2016-06-20T10:52:22Z
[ "python" ]
Ideal format of "message" to communicate between Java and Python?
37,920,767
<p>I have two processes: a server process, written in Python, and a client written in Java. These two programs will communicate via sockets, and I am about to begin writing the code to handle this.</p> <p>I am currently intending to send messages between the two in a JSON format that will provide data and/or instruct...
0
2016-06-20T10:57:44Z
37,920,999
<p>You can consider using <a href="https://developers.google.com/protocol-buffers/" rel="nofollow">protobuf</a> instead of JSON or even <a href="http://www.grpc.io/faq/" rel="nofollow">gRPC</a>, complete RPC protocol implemented on top of protobuf. The only thing you have to do using protobuf is define messages and ser...
0
2016-06-20T11:09:04Z
[ "java", "python", "sockets" ]
Changing object properties in python multiprocessing
37,920,802
<p>consider the following objects:</p> <pre><code>class Item(object): def __init__(self): self.c = 0 def increase(self): S.increase(self) class S(object): @staticmethod def increase(item): item.c += 1 </code></pre> <p>This mirrors the situation I am currently in, S is some lib...
0
2016-06-20T10:59:38Z
37,928,705
<p>You're expecting your mutator, the static method <code>increase</code> in class <code>S</code> (called from the non-static <code>increase</code> in class <code>item</code>) to adjust each <code>i.c</code> field—and it does. The problem is not with the static method, but rather with the internal design of <code>mu...
1
2016-06-20T17:44:47Z
[ "python", "multiprocessing", "static-methods" ]
Pandas python, what is the workbook encoding type?
37,920,809
<p>I am new to python and also to the pandas library in Python. The documentation is not well described and they didn't explain it well. I want to save the dataframe as an excel format and <strong>in the memory</strong> and I have found the following explanation: <a href="http://pandas.pydata.org/pandas-docs/stable/io....
3
2016-06-20T10:59:55Z
37,921,817
<p>For the explanation i paste the example from your link here again:</p> <pre><code># Safe import for either Python 2.x or 3.x try: from io import BytesIO except ImportError: from cStringIO import StringIO as BytesIO bio = BytesIO() # By setting the 'engine' in the ExcelWriter constructor. writer = ExcelWri...
2
2016-06-20T11:50:31Z
[ "python", "pandas", "mandrill" ]
How accuracy calculated for train data is used for evaluating test data in tensorflow
37,920,949
<p>In tensorflow the model is created with training data but i want to know how is the test data are evaluated with accuracy calculated with training data.</p> <pre><code> correct_prediction = tf.equal(tf.argmax(pred, 1),tf.argmax(y_train, 1)) # Calculate accuracy accuracy = tf.reduce_mean(tf.cast(corre...
0
2016-06-20T11:06:43Z
37,927,433
<p>In TensorFlow you create a graph, where data flows between nodes, from inputs to outputs.</p> <p>Let's take a simple example, MNIST. Here are the <strong>TensorFlow nodes</strong>:</p> <ul> <li>inputs: <ul> <li>batch of 28x28 images: <code>images</code> of shape <code>[batch_size, 28, 28, 1]</code></li> <li>label...
1
2016-06-20T16:25:40Z
[ "python", "tensorflow" ]
Create nested list of tuple elements based on the string integer number as index
37,921,184
<p>Let’s say I have a tuple, which contains lists, where its first element is always a string-number, e.g.</p> <pre><code>asdf = (['0', ...], ['1', ...], ['2', ...], ['3.0', ...], ['3.1', ...], ['3.2', ...], ['4', ...] , ['5.0', ...], ['5.1', ...]) </code></pre> <p>Baiscally, I want to have a list, which contains a...
1
2016-06-20T11:18:15Z
37,921,339
<p>Use <a href="https://docs.python.org/2/library/itertools.html#itertools.groupby" rel="nofollow"><code>itertools.groupby</code></a>,</p> <pre><code>import operator import itertools tuples = (['0', ], ['1', ], ['2', ], ['3.0', ], ['3.1', ], ['3.2', ], ['4', ] , ['5.0', ], ['5.1', ]) l = map(operator.itemgetter(0), ...
3
2016-06-20T11:26:09Z
[ "python", "tuples", "sublist" ]
Create nested list of tuple elements based on the string integer number as index
37,921,184
<p>Let’s say I have a tuple, which contains lists, where its first element is always a string-number, e.g.</p> <pre><code>asdf = (['0', ...], ['1', ...], ['2', ...], ['3.0', ...], ['3.1', ...], ['3.2', ...], ['4', ...] , ['5.0', ...], ['5.1', ...]) </code></pre> <p>Baiscally, I want to have a list, which contains a...
1
2016-06-20T11:18:15Z
37,925,083
<p>You can also do it without using <code>itertools.groupby()</code>. You can use a sorting method/defaultdict approach like this:</p> <pre><code>from collections import defaultdict asdf = (['0', ], ['1', ], ['2', ], ['3.0', ], ['3.1', ], ['3.2', ], ['4', ] , ['5.0', ], ['5.1', ]) all_items = [x[0] for x in asdf] d...
0
2016-06-20T14:27:50Z
[ "python", "tuples", "sublist" ]
Calculating cosine similarity across column in pandas
37,921,237
<p>I am new to pandas and i have these 2 series.</p> <p><code>train['description_1']</code> and <code>train['description_2']</code> are series. They each contain a vector for each row. </p> <pre><code>from scipy.spatial.distance import cosine item3 = pd.concat([train['description_1'], train['description_2']], axis = ...
1
2016-06-20T11:21:12Z
37,921,330
<p>You need:</p> <pre><code>import pandas as pd from scipy.spatial.distance import cosine df = pd.DataFrame({'description_1':[0.1,0.32,0.3], 'description_2':[0.4,0.5,0.6]}) print (df) description_1 description_2 0 0.10 0.4 1 0.32 0.5 2 0.30 ...
2
2016-06-20T11:25:55Z
[ "python", "numpy", "pandas" ]
Python PIL/Image make 3x3 Grid from sequence Images
37,921,295
<p>I'm trying to make a 3x3 Grid by sequence images but can't seem to get it right. The images are in folder, named from 0 - 8 (total 9 images), the output of the final one image grid of 3x3 should as follow</p> <pre><code>image0 image1 image2 image3 image4 image5 image6 image7 image8 </code></pre> <p>I was trying t...
0
2016-06-20T11:24:05Z
37,921,514
<p>Here's an example how this can be done (consider image is one of your images):</p> <pre><code> img_w, img_h = image.size background = Image.new('RGBA',(1300, 1300), (255, 255, 255, 255)) bg_w, bg_h = background.size offset = (10,(((bg_h - img_h)) / 2)-370) background.paste(image1,offset) </code><...
2
2016-06-20T11:34:33Z
[ "python", "image", "python-imaging-library", "pillow" ]
PySide Widget for 3dsMax and Modo
37,921,360
<p>I'm trying to create a simple QT app using PySide and Python that I want it to run as a 3dsMax script, a Modo script and a stand-alone app if needed. So, I've saved the following files in my D:\PyTest. It's just a QLabel for this test.</p> <p>When I run it (<em>TestWidget.py</em>) as a stand-alone it works fine. Wh...
1
2016-06-20T11:27:10Z
37,943,028
<p>Ok, with a little help from The Foundry I have a working version. They gave me this very useful link <a href="http://sdk.luxology.com/wiki/CustomView" rel="nofollow">http://sdk.luxology.com/wiki/CustomView</a></p> <p><em>3dsMax.py</em></p> <pre><code>from PySide import QtGui import MaxPlus import sys ui_dir = r'D:...
1
2016-06-21T11:21:06Z
[ "python", "qt", "pyside", "3dsmax", "cross-application" ]
Comparison of two documents in python
37,921,521
<p>Given two documents, I wish to calculate the similarity between them. I have measures to find out the cosine distance, N-Gram and tf-idf using this: <a href="http://stackoverflow.com/questions/2380394/simple-implementation-of-n-gram-tf-idf-and-cosine-similarity-in-python">This is a previously asked question</a></p> ...
-1
2016-06-20T11:35:07Z
37,921,834
<p>If you're focused into using these functions described by you, it should be easy to implement by reading <a href="https://github.com/nltk/nltk/wiki" rel="nofollow">nltk wiki</a>, but I don't know if this is the best way to compare the simmilarity between them.</p> <p>As stated in the <a href="http://docs.python.org...
1
2016-06-20T11:51:01Z
[ "python", "tf-idf", "n-gram", "word2vec", "cosine-similarity" ]
easy install can not install library package
37,921,650
<p>I used <code>easy_install</code>to install <code>pydelicious</code> library but it report an error:</p> <pre><code>&gt;easy_install pydelicious-0.6-py2.6.egg Searching for pydelicious-0.6-py2.6.egg Reading https://pypi.python.org/simple/pydelicious-0.6-py2.6.egg/ Couldn't find index page for 'pydelicious-0.6-py2.6....
0
2016-06-20T11:42:13Z
37,921,899
<p>Are you looking for <code>easy_install -f /path/to/pydelicious-0.6-py2.6.egg</code>?</p>
1
2016-06-20T11:53:38Z
[ "python", "easy-install" ]
easy install can not install library package
37,921,650
<p>I used <code>easy_install</code>to install <code>pydelicious</code> library but it report an error:</p> <pre><code>&gt;easy_install pydelicious-0.6-py2.6.egg Searching for pydelicious-0.6-py2.6.egg Reading https://pypi.python.org/simple/pydelicious-0.6-py2.6.egg/ Couldn't find index page for 'pydelicious-0.6-py2.6....
0
2016-06-20T11:42:13Z
37,921,962
<p>I think easy_install search in internet your pack. You must unzip and use setup.py in downloaded file</p>
0
2016-06-20T11:56:28Z
[ "python", "easy-install" ]
How to delete columns with at least 20% missing values
37,921,703
<p>Is there an efficient way to delete columns that have at least 20% missing values?</p> <p>Suppose my dataframe is like:</p> <pre><code> A B C D 0 sg hh 1 7 1 gf 9 2 hh 10 3 dd 8 4 6 5 y ...
0
2016-06-20T11:44:47Z
37,921,823
<p>You can use <code>boolean indexing</code> on the <code>columns</code> where the count of <code>notnull</code> values is larger then <code>80%</code>:</p> <pre><code>df.loc[:, pd.notnull(df).sum()&gt;len(df)*.8] </code></pre> <p>This is useful for many cases, e.g., dropping the columns where the number of values la...
4
2016-06-20T11:50:48Z
[ "python", "pandas", "machine-learning" ]
How to delete columns with at least 20% missing values
37,921,703
<p>Is there an efficient way to delete columns that have at least 20% missing values?</p> <p>Suppose my dataframe is like:</p> <pre><code> A B C D 0 sg hh 1 7 1 gf 9 2 hh 10 3 dd 8 4 6 5 y ...
0
2016-06-20T11:44:47Z
37,921,915
<p>You can call <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.dropna.html#pandas.DataFrame.dropna" rel="nofollow"><code>dropna</code></a> and pass a <code>thresh</code> value to drop the columns that don't meet your threshold criteria:</p> <pre><code>In [10]: frac = len(df) * 0.8 ...
1
2016-06-20T11:54:12Z
[ "python", "pandas", "machine-learning" ]
How to replace first and last 4 bytes in binary file in python
37,921,802
<p>This should be easy!</p> <p>I have a binary file. and I need to read the first 4 bytes from the file and replace the value there. for example: if the first 4 bytes is 00000000 so I want to replace them with 11111111. </p> <p>Also I need to read the last 4 bytes of the file and replace the value there. please not...
-3
2016-06-20T11:50:03Z
37,921,969
<p>this code should work in python 2.7:</p> <pre><code>with open(filepath, 'r+b') as f: data = f.read(4) f.seek(0) if len(somestring) != 4: raise ValueError f.write(somestring) f.seek(os.path.getsize(filepath)-4) enddata = f.read(4) f.seek(os.path.getsize(filepath)-4) if len(end...
1
2016-06-20T11:56:46Z
[ "python", "file", "binary" ]
Solution to Euler Project Task 5: Why does it work?
37,921,904
<p>After some trial and error I have found a solution which works very quickly for the <a href="https://projecteuler.net/problem=5" rel="nofollow">Project Euler Problem 5</a>. (I have found another way which correctly solved the example case (numbers 1-10) but took an eternity to solve the actual Problem.) Here it goes...
0
2016-06-20T11:53:47Z
37,922,417
<p>Well this isn't really a coding issue but a mathematical issue. If you look at all the numbers from 1-20 as the prime sthat make them you'll get the following: 1, 2,3,2^2,5,2^3,7,2^3....2^2*5. the interesting part here is that once you multiply by the highest exponent of every single factor in these numbers you wil...
2
2016-06-20T12:17:44Z
[ "python", "optimization" ]
Soft delete django database objects
37,922,029
<p>Suppose that I have django models such A ->B ->C ->D in the default database.</p> <p>C is a foreign key in D,similarly B in C and C in A.</p> <p>On the deletion of the object A,the default behaviour of Django is that all the objects related to A directly or indirectly will get deleted automatically(On delete casca...
1
2016-06-20T11:59:31Z
37,922,348
<p>Just override <code>delete</code> method of model <code>A</code> and check relation before delete. If it isn't empty - move object to another table/DB. </p>
0
2016-06-20T12:14:27Z
[ "python", "django", "web", "django-rest-framework" ]
Soft delete django database objects
37,922,029
<p>Suppose that I have django models such A ->B ->C ->D in the default database.</p> <p>C is a foreign key in D,similarly B in C and C in A.</p> <p>On the deletion of the object A,the default behaviour of Django is that all the objects related to A directly or indirectly will get deleted automatically(On delete casca...
1
2016-06-20T11:59:31Z
37,958,391
<p>I have implemented this thing using a deleted flag on each model of my database instead of moving things to separate database as follows:</p> <pre><code>deleted = models.BooleanField(default=False) </code></pre> <p>And defined a soft_del function for each model as follows:</p> <pre><code>def soft_del(self): ...
0
2016-06-22T04:09:06Z
[ "python", "django", "web", "django-rest-framework" ]
Soft delete django database objects
37,922,029
<p>Suppose that I have django models such A ->B ->C ->D in the default database.</p> <p>C is a foreign key in D,similarly B in C and C in A.</p> <p>On the deletion of the object A,the default behaviour of Django is that all the objects related to A directly or indirectly will get deleted automatically(On delete casca...
1
2016-06-20T11:59:31Z
39,655,206
<p>There is a library that matches django's default delete behavior on soft deletes. (ie uses the Cascade, do nothing, etc options from the model specification). </p> <p><a href="https://github.com/upgrad/django-deletes" rel="nofollow">https://github.com/upgrad/django-deletes</a></p> <p>PS: The library is still in be...
0
2016-09-23T07:35:23Z
[ "python", "django", "web", "django-rest-framework" ]
python Reading file containing \x0a as \n not as \\x0a in python
37,922,260
<p>I have xml file which contains hex characters \x0a. I want to convert them into proper unicode characters like \n in python.</p> <p>Whenever i try to read the files it escapes the backslash characters.</p> <p>For example i my file contents are</p> <pre><code>get EtqLt5fwmRBE\x0a </code></pre> <p>Then after readi...
-1
2016-06-20T12:10:11Z
37,922,552
<p>You can run your text through the <code>string_escape</code> (Python 2 only, produces a bytestring) or <code>unicode_escape</code> (Python 2 and 3, produces a unicode string) codecs.</p> <p>How you apply these depends on your Python version (2 or 3) and if the input is a byte string (<code>str</code> in Python 2, <...
4
2016-06-20T12:25:29Z
[ "python", "unicode", "python-unicode" ]
Django - MultiChoiceField to_field_name and selected
37,922,287
<p>I am currently using a MultiChoiceField to represent the corresponding ManyToManyField of my field. It works fine.</p> <p>I updated my form to use the attribute to_field_name in the form field to change the field used for the values of the inputs and it works fine too.</p> <p>My issue is that Django, to choose the...
0
2016-06-20T12:11:28Z
38,096,575
<p>Well, I managed to achieve what I wanted. As suggested by @Alasdair, I created an intermediary model.</p> <pre><code>class Model1(models.Model): name = models.Charfield(...) muscles = models.ManyToManyField(Model2, blank=True, null=True,) class Model2(models.Model): name = models.CharField(...) field1 = mo...
0
2016-06-29T10:11:21Z
[ "python", "django", "forms", "field" ]
Django - MultiChoiceField to_field_name and selected
37,922,287
<p>I am currently using a MultiChoiceField to represent the corresponding ManyToManyField of my field. It works fine.</p> <p>I updated my form to use the attribute to_field_name in the form field to change the field used for the values of the inputs and it works fine too.</p> <p>My issue is that Django, to choose the...
0
2016-06-20T12:11:28Z
38,348,686
<p>It looks as if you might have hit <a href="https://code.djangoproject.com/ticket/17657#comment:13" rel="nofollow">this bug</a>, which is fixed in Django 1.10.</p>
0
2016-07-13T10:10:46Z
[ "python", "django", "forms", "field" ]
Referencing a dataframe object's index and column?
37,922,332
<p>I have the following dataframe. I want to create a new dataframe based on the column and index of elements, but I am unable to reference to their index name.</p> <pre><code> AAA BBB CCC DDD A NaN NaN NaN NaN B NaN NaN NaN NaN C NaN NaN NaN NaN D NaN NaN NaN NaN </code></pre> <p>Code:</p> <pre...
1
2016-06-20T12:13:24Z
37,922,406
<p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.ix.html" rel="nofollow"><code>ix</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.fillna.html" rel="nofollow"><code>fillna</code></a>:</p> <pre><code>df_tmp.ix['B', 'AAA...
2
2016-06-20T12:17:18Z
[ "python", "numpy", "pandas", "dataframe" ]
byte array numpy Python 2 vs Python 3
37,922,357
<p>I need to generate tuples of this form : (string, string) or (string, int).</p> <p>I have the following code which seems to work fine in Python 2 but not returning the desired result in Python 3 (tested on Python 3.5) :</p> <pre><code>import string import numpy as np global_tab = [] global_nb_loop = 0 def nu...
2
2016-06-20T12:14:43Z
37,922,564
<p>Replace <code>global_tab</code> with:</p> <pre><code>global_tab = [(''.join(u), str(v)) for u, v in zip(np.random.choice(list(string.ascii_letters), (N, 15)), np.random.randint(0, 100, N) )] </code></pre> <p><code>ascii_letters</code> are of type string so you may not need to call <code>encode('utf-8')</code>:</p>...
1
2016-06-20T12:26:06Z
[ "python", "python-3.x", "numpy", "numpy-random" ]
byte array numpy Python 2 vs Python 3
37,922,357
<p>I need to generate tuples of this form : (string, string) or (string, int).</p> <p>I have the following code which seems to work fine in Python 2 but not returning the desired result in Python 3 (tested on Python 3.5) :</p> <pre><code>import string import numpy as np global_tab = [] global_nb_loop = 0 def nu...
2
2016-06-20T12:14:43Z
37,922,811
<h1>Why</h1> <p>In python 2 <code>string.ascii_letters</code> is a byte-string to begin with. The "magic" of python 2 first decodes it with default encoding when you call the method <code>.encode('utf-8')</code> and then re-encodes as requested. The result of encoding is <code>bytes</code> in both python 2 and 3.</p> ...
2
2016-06-20T12:39:14Z
[ "python", "python-3.x", "numpy", "numpy-random" ]
I am trying to write data into file
37,922,410
<p>When I run then i get error.why print man gave error and also os.getwd() also give error.But when i comment that then there is no error.code works according to expectation </p> <pre><code>from __future__ import print_function; import os man=[] other = [] print os.getcwd() try: data = ...
-1
2016-06-20T12:17:31Z
37,922,462
<p>You should call <code>print</code> as function, because you import <code>print_function</code>:</p> <pre><code>from __future__ import print_function print("Hello World") </code></pre>
1
2016-06-20T12:20:22Z
[ "python", "file", "save" ]
I am trying to write data into file
37,922,410
<p>When I run then i get error.why print man gave error and also os.getwd() also give error.But when i comment that then there is no error.code works according to expectation </p> <pre><code>from __future__ import print_function; import os man=[] other = [] print os.getcwd() try: data = ...
-1
2016-06-20T12:17:31Z
37,923,120
<p>As far as I see the following. 1) In the first line there is a ';' that could be removed. 2) the second line 'import...' and the rest to the bottom have tabs that should be removed. These lines should be in the same col that line 1 ('from ...') 3) when you use 'print' (as other people are saying) you should use '(' ...
1
2016-06-20T12:53:25Z
[ "python", "file", "save" ]
No such file or directory attach_file in django email
37,922,557
<p>attach_file is not picking the absolute url although file exist. its able to pic internal url and send file but not the absolute url</p> <pre><code>email.attach_file("http://devuserapi.doctorinsta.com/static/pdfs/Imran_1066.pdf",mimetype="application/pdf") </code></pre> <p>this file opens when i copy paste the url...
1
2016-06-20T12:25:40Z
37,922,647
<p><code>attach_file</code> takes a file from your filesystem, not a URL, so you have to use a local path to it</p> <p>See <a href="https://docs.djangoproject.com/en/1.9/topics/email/" rel="nofollow">https://docs.djangoproject.com/en/1.9/topics/email/</a></p> <p>One, untested, possibility is to use the <code>attach</...
1
2016-06-20T12:30:21Z
[ "python", "django", "email", "pdf" ]
Pandas index iat
37,922,653
<p>I use pandas indexing iat but i found error</p> <blockquote> <p>TypeError: <strong>call</strong>() takes from 1 to 2 positional arguments but 3 were given. </p> </blockquote> <p>My code is:</p> <pre><code>df['xyz'] = df.index ,date_format = "%m/%d/%Y" ,x=len(df.index),start = df.iat(1,2) ,end = df.iat(x,2),df.d...
-3
2016-06-20T12:30:39Z
37,922,683
<p>I think you need add <code>[]</code>, not <code>()</code> to <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.iat.html" rel="nofollow"><code>iat</code></a>:</p> <pre><code>df.iat[1,2] </code></pre> <p>Also change <code>[1,2]</code> to <code>[1,1]</code>, because there are only 2 col...
0
2016-06-20T12:32:03Z
[ "python", "datetime", "pandas", "dataframe" ]
Converting / parsing column strings to datetime values - pandas
37,922,792
<p>I have a csv output of thermal simulations, which I would like to perform data analysis on, using pandas.</p> <p>Having imported the csv into a pandas dataframe, I would like to manipulate the timestamp and import it as such.</p> <p>The starting format is the following (starts with a space, has US data format and ...
2
2016-06-20T12:38:18Z
37,922,917
<p>You should specify your format to <code>to_datetime</code> function, because it isn't default format:</p> <pre><code>pd.to_datetime(x, format='%Y/%m/%d_%H:%M') </code></pre>
2
2016-06-20T12:43:52Z
[ "python", "string", "datetime", "pandas" ]
Assert that one run is significantly faster than one other
37,922,994
<p>I need to make a functionnal test that assert that one run is <strong>significantly</strong> faster than one other.</p> <p>Here is the code I have written so far:</p> <pre><code>def test_run5(self): cmd_line = ["python", self.__right_def_file_only_files] start = time.clock() with self.assertRaises(Syst...
1
2016-06-20T12:47:36Z
37,962,382
<p>I found out an equation named <a href="https://en.wikipedia.org/wiki/Michaelis%E2%80%93Menten_kinetics" rel="nofollow"><code>Michaelis-Menten kinetics</code></a> which fit with my needs. Here is the function which should do the trick</p> <pre><code>def get_best_factor(full_exec_time, rule_count, maximum_ratio=1): ...
1
2016-06-22T08:20:09Z
[ "python", "unit-testing", "testing", "time" ]
Draw Longest Line in Contours OPENCV
37,923,008
<p>I am using OpenCV and Python. I am trying to draw the longest line inside a contours. </p> <p>I have a contour named <code>cnt</code>. The image is binary, the inside of the contours is white and the outside is black. I would like to draw the longest line inside the white contours. I found how to draw lines using <...
0
2016-06-20T12:48:06Z
38,264,117
<p>The below method using to draw the number of number of lines from the image and get the degree of max value try this. its working fine </p> <pre><code> Mat Compute_skewAngle (Mat&amp; src,Mat&amp; src_gray,int drawLine) { int thresh = 100; RNG rng(12345); // 1. Load Gray Scae Image // 2. Get Size of Image cv:...
0
2016-07-08T10:11:54Z
[ "python", "image", "python-2.7", "opencv", "opencv3.0" ]
Python API streaming examples for RabbitMQ on Flink
37,923,045
<p>Considering using Flink in place of Spark. Firstly cannot seem to find any examples that use the Python API in a streaming mode. I.e. going here, I don't see any: <a href="https://ci.apache.org/projects/flink/flink-docs-master/apis/streaming/" rel="nofollow">https://ci.apache.org/projects/flink/flink-docs-master/api...
1
2016-06-20T12:50:29Z
37,927,238
<p>Flink has no Streaming Python API.</p>
1
2016-06-20T16:14:59Z
[ "python", "apache-flink" ]
How to avoid the following discrepancy in my chatting app between client and server?
37,923,191
<p>As in my chatting app here, when client sends a message sends a message to server it becomes necessary for server to send a reply before client can send a message again. How to avoid this?</p> <p><strong>Server program:</strong></p> <pre><code>from socket import * import threading host=gethostname() port=7776 s=so...
1
2016-06-20T12:56:42Z
37,923,616
<p>I am pretty sure you were meant to make the central server receive messages from clients, and send them to all other clients, was it not? What you implemented isn't exactly that - instead, the server process just prints all messages that arrive from the clients.</p> <p>Anyways, based on the way you implemented it, ...
0
2016-06-20T13:17:00Z
[ "python", "multithreading", "python-2.7", "sockets", "python-sockets" ]
Why does unittest.mock fail when the production class constructor takes extra arguments?
37,923,265
<p>I have run into a problem which I think might be a bug with the libraries I am using. However, I am fairly new to python, unittest, and unittest.mock libraries so this may just be a hole in my understanding.</p> <p>While adding tests to some production code I have run into an error, I have produced a minimal sample...
4
2016-06-20T12:59:59Z
37,924,643
<p>Interestingly, the way you chose to perform the assert has masked your issue.</p> <p>Try, instead of this:</p> <pre><code>mockSUT.assert_has_calls(calls=[mock.call.notOkFunc()]) </code></pre> <p>to do this:</p> <pre><code>mockSUT.assert_has_calls(calls=[mock.call.notOkFunc()], any_order=True) </code></pre> <p>Y...
3
2016-06-20T14:07:09Z
[ "python", "python-unittest", "python-unittest.mock" ]
Why does unittest.mock fail when the production class constructor takes extra arguments?
37,923,265
<p>I have run into a problem which I think might be a bug with the libraries I am using. However, I am fairly new to python, unittest, and unittest.mock libraries so this may just be a hole in my understanding.</p> <p>While adding tests to some production code I have run into an error, I have produced a minimal sample...
4
2016-06-20T12:59:59Z
37,935,053
<p>I don't think I can explain definitively why this is the case, I still suspect a bug in the Mock library, since the issue only occurs for a test case with no arguments on the called function. Thanks to advance512 for pointing out that the real error was hidden!</p> <p>However to work around this issue, without havi...
2
2016-06-21T03:25:10Z
[ "python", "python-unittest", "python-unittest.mock" ]
Extracting data from .nc file by latitude and longitude in python
37,923,403
<p>I have gridded datasets in .nc format. I want to extract data on the basis of latitude and longitude. Latitude and longitude of my datasets are shown below:</p> <pre><code>import netCDF4 from netCDF4 import Dataset f= Dataset('data.nc') f.variables['lat'][:] array([ 31.5, 30.5, 29.5, 28.5, 27.5, 26.5, 25.5, ...
1
2016-06-20T13:06:29Z
37,950,799
<p>This code will certainly not work:</p> <pre><code>f.variables['temp'][:,29.5,65.5] </code></pre> <p>since you can't (shouldn't) index with floats in <code>numpy</code> or <code>netcdf4</code>.</p> <p>If you want to index by value, I'd suggest checking out <a href="http://xarray.pydata.org/en/stable/" rel="nofollo...
2
2016-06-21T17:23:28Z
[ "python", "numpy", "gdal", "netcdf" ]
Extracting data from .nc file by latitude and longitude in python
37,923,403
<p>I have gridded datasets in .nc format. I want to extract data on the basis of latitude and longitude. Latitude and longitude of my datasets are shown below:</p> <pre><code>import netCDF4 from netCDF4 import Dataset f= Dataset('data.nc') f.variables['lat'][:] array([ 31.5, 30.5, 29.5, 28.5, 27.5, 26.5, 25.5, ...
1
2016-06-20T13:06:29Z
37,969,232
<p>Below is correct if the 'temp' variable is dimensioned by lat,lon. Some NetCDF variables are dimensioned by lon,lat</p> <pre><code>f.variables['temp'][:,2,5] </code></pre> <p>You can check the dimensions of the 'temp' variable.</p> <pre><code>print f.variables['temp'].dimensions </code></pre> <p>Code to search f...
1
2016-06-22T13:16:39Z
[ "python", "numpy", "gdal", "netcdf" ]
unable to import tweetTokenizer
37,923,506
<p>I tried to import TweetTokenizer but it didn't happen</p> <p>I tried installing nltk.download(), but the list of packages didn't included any Tokenizer package. </p> <p>I followed <a href="http://www.nltk.org/api/nltk.tokenize.html" rel="nofollow">this</a> which didn't help</p> <pre><code>&gt;&gt;&gt; from nltk.t...
-2
2016-06-20T13:11:23Z
37,925,217
<p>Try updating your nltk model, and that should work fine</p>
1
2016-06-20T14:34:49Z
[ "python", "tokenize", "tweets" ]
Django REST Framework DateTimeField format showing Python Time
37,923,682
<p>Given some model</p> <pre><code>class Loan(models.Model): time_of_loan = models.DateTimeField() username = models.CharField() </code></pre> <p>I have attempted to use the <code>ModelSerializer</code> from Django's REST Framework to serialize the <code>Loan</code>. </p> <pre><code>class LoanSerializer(seri...
2
2016-06-20T13:20:26Z
38,039,225
<p>After so much finding, I finally got the answer.</p> <pre><code>from rest_framework.renderers import JSONRenderer serializer = LoanSerializer(loan_obj) serializer.data json = JSONRenderer().render(serializer.data) </code></pre>
0
2016-06-26T13:58:03Z
[ "python", "json", "django", "datetime", "django-rest-framework" ]
Some Rich Text Formatting (HTML) Not Displaying in Microsoft Access 2010
37,923,718
<p>I'm using a python script to parse a mass of text and import it into a Microsoft Access 2010 database. I'm inserting certain portions of the original text into a Rich Text section of a table. Adding <code>&lt;Br&gt;</code> statements creates the intended effect of starting a new line. This are implemented in python...
1
2016-06-20T13:22:18Z
37,928,104
<p>Strings are immutable in Python, so the <code>.replace</code> method does not perform the replacement <em>in situ</em>, it simply returns a new string with the replacement(s) applied. So, for example, this code does not change the value of the string named <code>thing</code>:</p> <pre class="lang-python prettypri...
1
2016-06-20T17:06:08Z
[ "python", "html", "ms-access", "ms-office" ]
Extracting facebook groups data with No admin rights
37,923,720
<p>I need to extract some data from a facebook group for my research. I tried certain approach and tools but nothing works out the way I wanted. I want to extract things like comment, no. of likes per post, post content, date of post etc.I am looking for a R or python script that can automate this process. I followed m...
0
2016-06-20T13:22:21Z
37,927,150
<p>I found <a href="http://analyticsastra.com/complete-guide-facebook-data-mining-using-r/" rel="nofollow">this</a> blog post about <code>Rfacebook</code> helpful. Note that if you don't have admin rights for the group then you're probably out of luck unless you just want to access your own data.</p>
0
2016-06-20T16:09:43Z
[ "python", "python-3.x" ]
ViewDoesNotExist at /
37,923,723
<p>I receive the following error:</p> <pre><code>ViewDoesNotExist at / '&lt;HttpResponse status_code=200, "text/html; charset=utf-8"&gt;' is not a callable or a dot-notation path Request Method: GET Request URL: http://0.0.0.0:8000/ Django Version: 1.9.7 Exception Type: ViewDoesNotExist Exception Value: '&lt;Ht...
0
2016-06-20T13:22:25Z
37,923,765
<p>Replace: </p> <pre><code>url(r'^$', views.hello_world()), </code></pre> <p>with:</p> <pre><code>url(r'^$', views.hello_world), </code></pre> <p>i.e., don't call the function, just pass the callable to the url configuration.</p>
5
2016-06-20T13:24:42Z
[ "python", "django", "python-3.x" ]
ViewDoesNotExist at /
37,923,723
<p>I receive the following error:</p> <pre><code>ViewDoesNotExist at / '&lt;HttpResponse status_code=200, "text/html; charset=utf-8"&gt;' is not a callable or a dot-notation path Request Method: GET Request URL: http://0.0.0.0:8000/ Django Version: 1.9.7 Exception Type: ViewDoesNotExist Exception Value: '&lt;Ht...
0
2016-06-20T13:22:25Z
37,923,805
<p>In your <code>urlpatterns</code> you supply the functions that django should call. This means that you need to supply just the function and not call them. Simply remove the <code>()</code> at the end and it should work:</p> <pre><code>urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', views.hello_...
3
2016-06-20T13:26:29Z
[ "python", "django", "python-3.x" ]
I need to get info on one line cleaned up in Python
37,923,727
<p>OK, I have been able to web scrape the info i need from a website, clean it up and format it the way I want. The problem is I need the description and price on one line. I have been able to do it but with indented spaces. I can't figure out how to clean it up all on one line. </p> <p>Any help is appreciated</p> ...
-2
2016-06-20T13:22:34Z
37,925,316
<p>The text values of the scraped <code>g_data</code> and <code>p_data</code> have a lot of whitespace on the sides. You need to remove them to print each item in one line. Like:</p> <pre><code>&gt;&gt;&gt; for g,p in zip(g_data, p_data): ... print g.text.strip().replace('\n',' '), p.text.strip() ... Samsung - RF2...
1
2016-06-20T14:39:54Z
[ "python", "beautifulsoup", "python-requests" ]
Parallel programming on Binary tree
37,923,795
<p>I'm quite new to python and parallel programming. I have a binary tree that looks like this: <a href="http://i.stack.imgur.com/2UJTf.gif" rel="nofollow"><img src="http://i.stack.imgur.com/2UJTf.gif" alt="binary tree"></a></p> <p>My task is to square each node and replace the value in the node, but the children node...
0
2016-06-20T13:25:57Z
37,925,325
<p>I assume that by parallel you simply mean that all the nodes of a depth level must be computed before a lower depth level, i.e. that you don't care about multiple threads.</p> <p>The standard way to perform an operation on the nodes of a binary tree is to use a recursive function. However, in this case, you'll have...
0
2016-06-20T14:40:15Z
[ "python", "algorithm", "parallel-processing", "binary-tree", "python-multiprocessing" ]
Parallel programming on Binary tree
37,923,795
<p>I'm quite new to python and parallel programming. I have a binary tree that looks like this: <a href="http://i.stack.imgur.com/2UJTf.gif" rel="nofollow"><img src="http://i.stack.imgur.com/2UJTf.gif" alt="binary tree"></a></p> <p>My task is to square each node and replace the value in the node, but the children node...
0
2016-06-20T13:25:57Z
37,933,106
<p>Here is the solution that squares each level before its parent levels. It first finds the levels, and then starts from the lowest level to square each level:</p> <pre><code>from Queue import Queue class Node: def __init__(self, value): self.v = value self.l = None self.r = None def...
2
2016-06-20T22:57:55Z
[ "python", "algorithm", "parallel-processing", "binary-tree", "python-multiprocessing" ]
Google Container Engine stdout Logs Not Showing Up
37,923,927
<p>My stdout logs are not showing up in Google Logs Viewer, or when using <code>kubectl logs &lt;pod&gt;</code>. The cluster has Cloud Logging enabled and fluentd containers are running on each node.</p> <p>Example Python code:</p> <pre><code>logger = logging.getLogger() logger.setLevel(logging.INFO) handler = loggin...
0
2016-06-20T13:32:39Z
37,934,693
<p>If the logs aren't showing up when you run <code>kubectl logs pod</code>, then the problem is almost certainly that the logs from your application aren't going to stdout or stderr, so that's what you should focus on.</p> <p>What happens if you <code>docker run</code> your application locally? Does <code>docker logs...
0
2016-06-21T02:35:43Z
[ "python", "docker", "kubernetes", "google-container-engine", "google-cloud-logging" ]
Google Container Engine stdout Logs Not Showing Up
37,923,927
<p>My stdout logs are not showing up in Google Logs Viewer, or when using <code>kubectl logs &lt;pod&gt;</code>. The cluster has Cloud Logging enabled and fluentd containers are running on each node.</p> <p>Example Python code:</p> <pre><code>logger = logging.getLogger() logger.setLevel(logging.INFO) handler = loggin...
0
2016-06-20T13:32:39Z
37,956,227
<p>The logs are definitely going to stdout, they just aren't showing up when running <code>kubectl logs &lt;pod_name&gt;</code>. Nor are they showing up in Google Logs Viewer.</p> <p>This is because logs sent to stdout will only be captured if they're coming from the process that's the entry point of the Docker contai...
1
2016-06-21T23:32:49Z
[ "python", "docker", "kubernetes", "google-container-engine", "google-cloud-logging" ]
Memory address of a lambda function
37,923,933
<p>I noticed this behavior in Python 2 and 3:</p> <pre><code>&gt;&gt;&gt; id(lambda: 1) == id(lambda: 2) True </code></pre> <p>They share the same hash as well.</p> <pre><code>&gt;&gt;&gt; hash(lambda: 1) == hash(lambda: 2) True </code></pre> <p>I expected to have two <strong>different</strong> <code>id</code>s and...
3
2016-06-20T13:32:49Z
37,924,027
<p>This has nothing to do with scope, or lambdas, or closures. It is simply that Python manages memory with reference counting, and those lambdas are never assigned to any references, so Python immediately deletes them and reuses the memory location for the next object.</p>
4
2016-06-20T13:37:46Z
[ "python", "lambda", "closures" ]
Creating a "slice notation" style list from a set of numbers in Python
37,924,055
<p>Say I have a set of ~100,000 different numbers. Some are sequential, some are not.</p> <p>To demonstrate the problem, a small subset of these numbers might be:</p> <blockquote> <p>(a) {1,2,3,4,5,6,7,8,9,11,13,15,45,46,47,3467}</p> </blockquote> <p>An efficient way of writing this subset is as follows:</p> <blo...
1
2016-06-20T13:39:07Z
37,925,112
<p>Disclaimer: I misread the question and thought you wanted to go from the slice notation to the set version, <strong>this doesn't actually answer your question</strong> but I figured it was worth leaving posted.</p> <p>First off note that if you are using python 3.5+ <a href="https://www.python.org/dev/peps/pep-3132...
1
2016-06-20T14:29:23Z
[ "python", "list", "set", "subset", "slice" ]
Creating a "slice notation" style list from a set of numbers in Python
37,924,055
<p>Say I have a set of ~100,000 different numbers. Some are sequential, some are not.</p> <p>To demonstrate the problem, a small subset of these numbers might be:</p> <blockquote> <p>(a) {1,2,3,4,5,6,7,8,9,11,13,15,45,46,47,3467}</p> </blockquote> <p>An efficient way of writing this subset is as follows:</p> <blo...
1
2016-06-20T13:39:07Z
37,926,224
<p>I think I got it but the following code was not very thoroughly tested and may contain bugs.</p> <p>Basically <code>get_partial_slices</code> will try to create <code>partial_slice</code> objects, when the next number in the (sorted) set does not <code>.fit()</code> into the slice it is <code>.end()</code>ed and th...
1
2016-06-20T15:24:06Z
[ "python", "list", "set", "subset", "slice" ]
Creating a "slice notation" style list from a set of numbers in Python
37,924,055
<p>Say I have a set of ~100,000 different numbers. Some are sequential, some are not.</p> <p>To demonstrate the problem, a small subset of these numbers might be:</p> <blockquote> <p>(a) {1,2,3,4,5,6,7,8,9,11,13,15,45,46,47,3467}</p> </blockquote> <p>An efficient way of writing this subset is as follows:</p> <blo...
1
2016-06-20T13:39:07Z
37,927,530
<p>The simplest way is to use numpy's <code>r_[]</code> syntax. So for your example, it would just be:</p> <pre><code>&gt;&gt;&gt; from numpy import r_ &gt;&gt;&gt; &gt;&gt;&gt; a = r_[1:10, 11:17:2, 45:48, 3467] </code></pre> <p>Keep in mind that python slices don't include the last number, and the x:y:1 is implied...
1
2016-06-20T16:31:28Z
[ "python", "list", "set", "subset", "slice" ]
Looping through and concatenating log files
37,924,122
<p>So I have a small python script that will ask the user for a username then it will rip their logs for a certain twitch.tv channel from overrustlelogs.net</p> <p>At the moment I just have 2 lists, one for months one for the year because the log URL takes the format of </p> <blockquote> <p><a href="http://overrust...
0
2016-06-20T13:42:19Z
37,924,680
<p>Here's a simple script that will help you.</p> <ol> <li><p>It creates a list with days between certain dates using <code>datetime.timedelta()</code>.</p></li> <li><p>Then it format these days using only month name and year (<code>%B-%Y</code>)</p></li> <li><p>And finally remove duplicates by using an <code>if not i...
0
2016-06-20T14:08:39Z
[ "python", "python-2.7", "loops", "datetime" ]
Looping through and concatenating log files
37,924,122
<p>So I have a small python script that will ask the user for a username then it will rip their logs for a certain twitch.tv channel from overrustlelogs.net</p> <p>At the moment I just have 2 lists, one for months one for the year because the log URL takes the format of </p> <blockquote> <p><a href="http://overrust...
0
2016-06-20T13:42:19Z
37,927,768
<p>Apart from <code>datetime</code> module, you can also take a look at <code>calendar</code> module. However, it does not have a built-in to iterate through months.</p> <pre><code>import calendar from collections import namedtuple MonthWithYear = namedtuple('MonthWithYear', ['month', 'year']) def months_between(sin...
0
2016-06-20T16:46:04Z
[ "python", "python-2.7", "loops", "datetime" ]
plot_trisurf unwanted triangle
37,924,126
<p>I am working with python and I am using matplotlib to create 3D graph however the <code>plot_trisurf</code> method keeps triangles on one edge of the graph and it is really annoying. I have looked for solution but did not succeed to solve the problem. Here is the code:</p> <pre><code>variableToDisplay='U' fig = pl...
1
2016-06-20T13:42:27Z
37,946,128
<p>I finally find a way. Here is the code and the graph obtained:</p> <pre><code>from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm from matplotlib.ticker import LinearLocator, FormatStrFormatter import matplotlib.pyplot as plt import numpy as np import matplotlib.tri as tri from matplotlib.ticker impor...
0
2016-06-21T13:41:29Z
[ "python", "matplotlib" ]
PIL: add a text at the bottom middle of image
37,924,130
<p>I've width and height of the image.</p> <pre><code>img = Image.open(img_src) width, height = img.size font = ImageFont.truetype("MuseoSansCyrl_0.otf", 100) text_w, text_h = draw.textsize(title, font) </code></pre> <p>I'm trying to find a generic way to add a text to image at the bottom middle.</p> <p>Here is the...
1
2016-06-20T13:42:36Z
37,924,566
<p>You had already placed a call to <code>draw.textsize</code>, which returns you the Width and Height the final text will have - from that point, you just thave to calculate the top-left corner where to render your text like this:</p> <p>Top will be your image_height - text_height, left will be your image_width/2 - ...
1
2016-06-20T14:03:40Z
[ "python", "image", "image-processing", "fonts", "python-imaging-library" ]
PIL: add a text at the bottom middle of image
37,924,130
<p>I've width and height of the image.</p> <pre><code>img = Image.open(img_src) width, height = img.size font = ImageFont.truetype("MuseoSansCyrl_0.otf", 100) text_w, text_h = draw.textsize(title, font) </code></pre> <p>I'm trying to find a generic way to add a text to image at the bottom middle.</p> <p>Here is the...
1
2016-06-20T13:42:36Z
37,924,637
<p>The names you have for the needed variables — <code>REQ_WIDTH</code> and <code>REQ_HEIGHT</code> — are a little misleading because they're not a width and height.</p> <p>You just need to do a little math:</p> <pre><code> X_POS = h - text_h Y_POS = w//2 - text_w//2 # or (w - text_w) // 2 draw.text(...
2
2016-06-20T14:06:45Z
[ "python", "image", "image-processing", "fonts", "python-imaging-library" ]
How to convert negative longitude to a positive in python?
37,924,192
<p>I am reading in a text file and extracting values to display the longitude but from the text file, it is a negative value and need for it to be positive.</p> <p>A sample of the text file that I have, in the format of (DDDMMSS.SS), named coordinates.txt:</p> <pre><code>Longitude : -0780417.04 </code></pre> <p>Basi...
0
2016-06-20T13:45:43Z
37,924,318
<pre><code>x = line.split(':')[1].strip() first = int(x[1:4]) + 359 second = int(x[4:6]) + 59 third = float(x[6:10]) + 60.0 print(first, second, third) </code></pre>
0
2016-06-20T13:52:00Z
[ "python", "python-2.7" ]
How to convert negative longitude to a positive in python?
37,924,192
<p>I am reading in a text file and extracting values to display the longitude but from the text file, it is a negative value and need for it to be positive.</p> <p>A sample of the text file that I have, in the format of (DDDMMSS.SS), named coordinates.txt:</p> <pre><code>Longitude : -0780417.04 </code></pre> <p>Basi...
0
2016-06-20T13:45:43Z
37,924,355
<p>First, pull the value into a variable. Leave it as a string:</p> <pre><code>key,value = line.split(':') </code></pre> <p>Next, perform your check. I don't know how you handle positive longitudes. I'm assuming you ignore them:</p> <pre><code>if key == 'Longitude' and value.strip().startswith('-'): </code></pre> <...
1
2016-06-20T13:54:06Z
[ "python", "python-2.7" ]
Passing Parameters to SQLDF in Python
37,924,195
<p>I'm trying to pass parameters through sqldf in python:</p> <pre><code>id = '001F5' q = """select * from df where id= %id; """ test = sqldf(q, globals()) </code></pre> <p>I've tried many things e.g. +id, "+id;"" and %id etc and nothing works, is it possible to do this at all?</p> <p>Many Thanks</p>
0
2016-06-20T13:45:46Z
37,924,900
<p>Try:</p> <pre><code>id = "'001F5'" q = "select * from df where id=" + id + ";" test = sqldf(q, globals()) </code></pre> <p>Or you can try:</p> <pre><code>id = "'001F5'" q = "select * from df where id={0};".format(id) test = sqldf(q, globals()) </code></pre>
1
2016-06-20T14:20:13Z
[ "python", "parameters", "sqldf" ]