title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Python Tkinter While Thread
39,689,940
<p>Well i am a bit of newb at python, and i am getting hard to make a thread in Tkinter , as you all know using while in Tkinter makes it Not Responding and the script still running.</p> <pre><code> def scheduler(): def wait(): schedule.run_pending() time.sleep(1) return Hours = Schedu...
1
2016-09-25T17:52:11Z
39,719,410
<h3>When to use the after method; faking while without threading</h3> <p>As mentioned in a comment, In far most cases, you do not need threading to run a "fake" while loop. You can use the <code>after()</code> method to schedule your actions, using <code>tkinter</code>'s <code>mainloop</code> as a "coat rack" to sche...
1
2016-09-27T08:09:19Z
[ "python", "multithreading", "tkinter", "python-multithreading", "schedule" ]
asynchronous subprocess Popen python 3.5
39,689,975
<p>I am trying to asynchronously run the Popen command from subprocess, so that I can run other stuff in the background.</p> <pre><code>import subprocess import requests import asyncio import asyncio.subprocess async def x(message): if len(message.content.split()) &gt; 1: #output = asyncio...
-1
2016-09-25T17:55:15Z
39,746,135
<p>Tested with python 3.5. Just ask if you have questions.</p> <pre><code>import threading import time import subprocess import shlex from sys import stdout # Only data wihtin a class are actually shared by the threads. # Let's use a class as communicator (there could be problems if you have more than # a single thr...
0
2016-09-28T11:27:54Z
[ "python", "asynchronous", "subprocess", "python-3.5" ]
asynchronous subprocess Popen python 3.5
39,689,975
<p>I am trying to asynchronously run the Popen command from subprocess, so that I can run other stuff in the background.</p> <pre><code>import subprocess import requests import asyncio import asyncio.subprocess async def x(message): if len(message.content.split()) &gt; 1: #output = asyncio...
-1
2016-09-25T17:55:15Z
39,746,464
<p>This one is much simpler, I found it after the other reply that could, anyway, be interesting... so I left it.</p> <pre><code>import time import subprocess import shlex from sys import stdout command = 'time sleep 5' # Here I used the 'time' only to have some output def x(command): cmd = shlex.split(command)...
0
2016-09-28T11:42:29Z
[ "python", "asynchronous", "subprocess", "python-3.5" ]
asynchronous subprocess Popen python 3.5
39,689,975
<p>I am trying to asynchronously run the Popen command from subprocess, so that I can run other stuff in the background.</p> <pre><code>import subprocess import requests import asyncio import asyncio.subprocess async def x(message): if len(message.content.split()) &gt; 1: #output = asyncio...
-1
2016-09-25T17:55:15Z
39,754,330
<p>I eventually found the answer to my question, which utilizes async. <a href="http://pastebin.com/Zj8SK1CG" rel="nofollow">http://pastebin.com/Zj8SK1CG</a></p>
0
2016-09-28T17:43:53Z
[ "python", "asynchronous", "subprocess", "python-3.5" ]
My HyperlinkedImage subclass of reportlab Image class is not working
39,689,977
<p>I'm trying to export a PDF with hyperlinked images for a report. I have images throughout my report, and wanted to add a hyperlink to that picture added in the PDF to open up the jpg in the folder where I grabbed the image. I found great solutions from @Meilo <a href="http://stackoverflow.com/questions/19596300/repo...
0
2016-09-25T17:55:18Z
39,727,013
<p>The answer is actually proposed in @Dennis Golomazov's post on the second answer for the modified HyperlinkedImage subclass <a href="http://stackoverflow.com/questions/19596300/reportlab-image-link/39134216#39134216">ReportLab Image Link</a>. I knew something wasn't working with the hAlign parameter, and @Dennis Gol...
0
2016-09-27T14:13:02Z
[ "python", "image", "hyperlink", "reportlab" ]
relation "hello_greeting" does not exist
39,690,005
<p>I'm trying the python tutorial on Heroku app (<a href="https://devcenter.heroku.com/articles/getting-started-with-python#introduction" rel="nofollow">https://devcenter.heroku.com/articles/getting-started-with-python#introduction</a>) and I got that error when I appended \db on the main app but it works with the loca...
1
2016-09-25T17:58:15Z
39,690,175
<p>Sorry, my mistake. I was not able to migrate thus the issue was solved using</p> <pre><code>heroku run python manage.py migrate </code></pre>
0
2016-09-25T18:13:46Z
[ "python", "heroku" ]
PyQt QPushButton signal handling
39,690,243
<p>I have a <code>repeat</code> python function and a <em>test.ui</em> which has only one push-button. My doubt is how to loop the same function exactly once for every time the button is clicked. Because for me whenever I perform:</p> <pre><code>self.pushButton.clicked.connect(self.repeat) </code></pre> <p>it loops m...
0
2016-09-25T18:21:33Z
39,703,796
<p>Loooking at your code, you have established the connection multiple times. You should establish it with <code>self.pushButton.clicked.connect(self.repeat)</code> only in your <code>__init__</code> but not in <code>repeat()</code> function. In other words, delete the second occurrence (i.e. in <code>repeat()</code>) ...
1
2016-09-26T13:09:51Z
[ "python", "pyqt4", "signals-slots", "qpushbutton" ]
Django rest framework one to one relation Create serializer
39,690,267
<p>I'm a beginner to the Django Rest Frame work. I want to create a custom user but I have a problem from a long period i try to find a solution through many forums but unfortunately i didn't succeed. hope you help me </p> <p>models.py</p> <pre><code>class Account(models.Model): user=models.OneToOneField(User,o...
1
2016-09-25T18:23:13Z
39,691,374
<p>Your problem is here:</p> <pre><code> user_data = validated_data.pop('user') account = Account.objects.create(**validated_data) User.objects.create(account=account, **user_data) </code></pre> <p>You're trying to create an Account before creating a User, which won't work because an Account requires a value ...
1
2016-09-25T20:14:13Z
[ "python", "django", "rest", "django-rest-framework" ]
How to split string with different phones using re?
39,690,301
<p>For example there are such phones:</p> <pre><code>phones = '+35(123) 456 78 90 (123) 555 55 55 (908)985 88 89 (593)592 56 95' </code></pre> <p>I need to get:</p> <pre><code>phones_list = ['+35(123) 456 78 90', '(123) 555 55 55', '(908)985 88 89', (593)592 56 95] </code></pre> <p>Trying to solve using <code>re...
2
2016-09-25T18:26:25Z
39,690,425
<p>This approach uses the <code>+</code> or <code>(</code> to signal the beginning of a phone number. It does not require multiple-spaces:</p> <pre><code>&gt;&gt;&gt; phones = '+35(123) 456 78 90 (123) 555 55 55 (908)985 88 89 (593)592 56 95' &gt;&gt;&gt; re.split(r' +(?=[(+])', phones) ['+35(123) 456 78 90', '(12...
5
2016-09-25T18:38:10Z
[ "python", "regex", "python-3.x" ]
PHP openssl AES in Python
39,690,400
<p>I am working on a project where PHP is used for decrypt AES-256-CBC messages</p> <pre><code>&lt;?php class CryptService{ private static $encryptMethod = 'AES-256-CBC'; private $key; private $iv; public function __construct(){ $this-&gt;key = hash('sha256', 'c7b35827805788e77e41c50df4444149...
0
2016-09-25T18:35:01Z
39,690,864
<p><a href="http://php.net/manual/en/function.hash.php" rel="nofollow">PHP's <code>hash</code></a> outputs a Hex-encoded string by default, but Python's <code>.digest()</code> returns <code>bytes</code>. You probably wanted to use <code>.hexdigest()</code>:</p> <pre><code>def __init__(self, key, iv): self.key = ha...
1
2016-09-25T19:20:49Z
[ "php", "python", "encryption", "aes", "pycrypto" ]
How to use inline_keyboard instead of keyboard in Telegram bot (Python)?
39,690,631
<p>I have this part of code (Python) that I'm using in my Telegram bot:</p> <pre><code>def reply(msg=None, img=None): if msg: resp = urllib2.urlopen(BASE_URL + 'sendMessage', urllib.urlencode({ 'chat_id': str(chat_id), 'text': msg.encode('utf-8'), 'di...
0
2016-09-25T18:58:23Z
39,742,993
<p>since the <a href="https://core.telegram.org/bots/api#inlinekeyboardmarkup" rel="nofollow">Inline Keyboard</a> is just a different json object, I'd say you only have to build it with <code>json.dumps</code> instead of your current build. Following your example, something like this should make the trick:</p> <pre><c...
0
2016-09-28T09:15:44Z
[ "python", "keyboard", "telegram", "telegram-bot" ]
overwriting output of function in terminal on same line
39,690,708
<p>I have a function, for example</p> <pre><code>def f(x): for i in range(x): print i </code></pre> <p>Without making any addition in f(x) function, is it possible to overwrite the terminal line during run? For example, in my case it shows like this:</p> <pre><code>print f(5) </code></pre> <p>output is...
0
2016-09-25T19:05:33Z
39,690,758
<p>In general, no; but depending on what the "terminal" is assumed to be, maybe. Many terminal windows emulate the ancient cursor positioning commands from one or more "glass tty" terminals. In which case, if you assume you know what terminal is being emulated, you can send cursor positioning commands to move back to...
0
2016-09-25T19:11:00Z
[ "python", "python-2.7" ]
overwriting output of function in terminal on same line
39,690,708
<p>I have a function, for example</p> <pre><code>def f(x): for i in range(x): print i </code></pre> <p>Without making any addition in f(x) function, is it possible to overwrite the terminal line during run? For example, in my case it shows like this:</p> <pre><code>print f(5) </code></pre> <p>output is...
0
2016-09-25T19:05:33Z
39,690,821
<p>Since <code>print</code> issues a newline, and you cannot go back after that, you have to prevent at all costs that a newline char to be issued in the terminal.</p> <p>You can do it by redirecting <code>sys.stdout</code>. <code>print</code> will output to your new stream. In your stream, remove the linefeed and add...
0
2016-09-25T19:16:47Z
[ "python", "python-2.7" ]
overwriting output of function in terminal on same line
39,690,708
<p>I have a function, for example</p> <pre><code>def f(x): for i in range(x): print i </code></pre> <p>Without making any addition in f(x) function, is it possible to overwrite the terminal line during run? For example, in my case it shows like this:</p> <pre><code>print f(5) </code></pre> <p>output is...
0
2016-09-25T19:05:33Z
39,693,070
<p>If you are trying to print only the last line, you can pipe the output and use tail command to retrieve only the last word.</p> <p>Useful link: <a href="https://kb.iu.edu/d/acrj" rel="nofollow">https://kb.iu.edu/d/acrj</a></p>
0
2016-09-26T00:12:04Z
[ "python", "python-2.7" ]
Convert float to int and leave nulls
39,690,742
<p>I have the following dataframe, I want to convert values in column 'b' to integer</p> <pre><code> a b c 0 1 NaN 3 1 5 7200.0 20 2 5 580.0 20 </code></pre> <p>The following code is throwing exception "ValueError: Cannot convert NA to integer"</p> <pre><code>df['b'] = df['b'].astype(i...
3
2016-09-25T19:09:25Z
39,694,672
<p><code>np.NaN</code> is a floating point only kind of thing, so it has to be removed in order to create an integer pd.Series. Jeon's suggestion work's great If 0 isn't a valid value in <code>df['b']</code>. For example:</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({'a': [1, 5, 5], 'b': [n...
1
2016-09-26T04:19:31Z
[ "python", "pandas", "numpy" ]
Unwanted timestamp when using print in python
39,690,816
<p>I am using autobahn[twisted] to achieve some WAMP communication. While subscribing to a topic a getting feed from it i print it. When i do it i get something like this:</p> <pre><code>2016-09-25T21:13:29+0200 (u'USDT_ETH', u'12.94669009', u'12.99998074', u'12.90000334', u'0.00035594', u'18396.86929477', u'1422.1952...
0
2016-09-25T19:16:33Z
39,691,914
<p>Well, <code>sys.stderr</code> and <code>sys.stdout</code> are redirected to a twisted logger.</p> <p>You need to change the logging format before running you app.</p> <p>See: <a href="https://twistedmatrix.com/documents/15.2.1/core/howto/logger.html" rel="nofollow">https://twistedmatrix.com/documents/15.2.1/core/h...
0
2016-09-25T21:14:11Z
[ "python", "printing", "timestamp", "autobahn" ]
GitPython "blame" does not give me all changed lines
39,690,910
<p>I am using GitPython. Below I print the total number of lines changed in a specific commit: <code>f092795fe94ba727f7368b63d8eb1ecd39749fc4</code>:</p> <pre><code>from git import Repo repo = Repo("C:/Users/shiro/Desktop/lucene-solr/") sum_lines = 0 for blame_commit, lines_list in repo.blame('HEAD', 'lucene/core/sr...
0
2016-09-25T19:26:12Z
39,691,814
<p><code>git blame</code> tells you which commit last changed each line in a given file.</p> <p>You're not counting the number of lines changed in that commit, but rather the number of lines in the file at your current HEAD that were last modified by that specific commit.</p> <p>Changing <code>HEAD</code> to <code>f0...
2
2016-09-25T21:03:21Z
[ "python", "git", "gitpython" ]
pass multiple arguments in the url
39,690,962
<p>I'm trying to make a simple django app that interacts with the database. But I'm having trouble passing more than one parameter in the url.</p> <p>To pass the arguments i do it this way:</p> <pre><code>127.0.0.1:8000/REST/insert/?n=test/?x=2/?y=2/?z=True </code></pre> <p>And then in my <strong>views.py</strong> I...
0
2016-09-25T19:30:25Z
39,690,983
<p>The separators between query parameters should be <code>&amp;</code> characters instead of slashes and question marks (except the first).</p> <pre><code>/?n=test/?x=2/?y=2/?z=True </code></pre> <p>should be</p> <pre><code>/?n=test&amp;x=2&amp;y=2&amp;z=True </code></pre> <p>Note: I'm not actually sure you should...
2
2016-09-25T19:32:58Z
[ "python", "django", "django-urls" ]
pass multiple arguments in the url
39,690,962
<p>I'm trying to make a simple django app that interacts with the database. But I'm having trouble passing more than one parameter in the url.</p> <p>To pass the arguments i do it this way:</p> <pre><code>127.0.0.1:8000/REST/insert/?n=test/?x=2/?y=2/?z=True </code></pre> <p>And then in my <strong>views.py</strong> I...
0
2016-09-25T19:30:25Z
39,691,517
<p>What you want to do is not safe. Since you do an insert operation, request type should be POST and you should send the information as json.</p> <p>Just write the data as json and put it to the body of the request.</p> <p>In your view;</p> <pre><code>import json def your_view(request): body_unicode = request.b...
1
2016-09-25T20:28:31Z
[ "python", "django", "django-urls" ]
sqlite3.OperationalError: near "WHERE": syntax error
39,691,052
<p>I want to update a series of columns Country1, Country2... Country 9 based on a comma delimited string of country names in column Country. I've programmed a single statement to accomplish this task. </p> <pre><code>cur.execute("\ UPDATE t \ SET Country1 = returnCountryName(Country,0),\ ...
-1
2016-09-25T19:40:14Z
39,691,086
<p>You have to remove the comma from the last assignment:</p> <pre><code>Country10 = returnCountryName(Country,9),\ </code></pre> <p>See also <a href="http://stackoverflow.com/a/39690916/6776093">my answer</a> to your original question</p>
0
2016-09-25T19:42:55Z
[ "python", "sqlite" ]
Erosion and dilation in Python OpenCV returns white
39,691,069
<p>I am trying to use dialation and ertion</p> <p>For example, like so:</p> <pre><code>dialated = cv2.dilate(edgesCopy, cv2.getStructuringElement(cv2.MORPH_CROSS,(3,3)), iterations = 1) </code></pre> <p>The input is a uint8 image that has only values of 0 and 255, as came out of</p> <pre><code>threshold, thresholde...
0
2016-09-25T19:41:32Z
39,692,474
<p>The result of the canny edge detection is image with binary edges of thickness 1. You are thresholding this edges (which is not needed by the way) with a threshold setting cv2.THRESH_BINARY_INV, which means that the threshold result gets value 1 where pixels are bellow threshold and 0 when above. The result of such ...
2
2016-09-25T22:37:53Z
[ "python", "opencv", "image-processing" ]
How to split up a string on multiple delimiters but only capture some?
39,691,091
<p>I want to split a string on any combination of delimiters I provide. For example, if the string is: </p> <pre><code>s = 'This, I think,., کباب MAKES , some sense ' </code></pre> <p>And the delimiters are <code>\.</code>, <code>,</code>, and <code>\s</code>. However I want to capture all delimiters except whit...
4
2016-09-25T19:43:22Z
39,691,298
<p>The following approach would be the most simple one, I suppose ...</p> <pre><code>s = 'This, I think,., کباب MAKES , some sense ' pattern = '([\.,\s]+)' splitted = [i.strip() for i in re.split(pattern, s) if i.strip()] </code></pre> <p>The output:</p> <pre><code>['This', ',', 'I', 'think', ',.,', 'کباب', ...
4
2016-09-25T20:06:05Z
[ "python", "regex" ]
How to split up a string on multiple delimiters but only capture some?
39,691,091
<p>I want to split a string on any combination of delimiters I provide. For example, if the string is: </p> <pre><code>s = 'This, I think,., کباب MAKES , some sense ' </code></pre> <p>And the delimiters are <code>\.</code>, <code>,</code>, and <code>\s</code>. However I want to capture all delimiters except whit...
4
2016-09-25T19:43:22Z
39,691,408
<p><em>Update based on OP's last edit</em></p> <p>Python 3.*:</p> <pre><code>list(filter(None, re.split('([.,]+(?:\s+[.,]+)*)|\s', s))) </code></pre> <p>Output:</p> <pre><code>['This', ',', 'I', 'think', ',.,', 'کباب', 'MAKES', ',', 'some', 'sense'] </code></pre>
0
2016-09-25T20:17:19Z
[ "python", "regex" ]
How to split up a string on multiple delimiters but only capture some?
39,691,091
<p>I want to split a string on any combination of delimiters I provide. For example, if the string is: </p> <pre><code>s = 'This, I think,., کباب MAKES , some sense ' </code></pre> <p>And the delimiters are <code>\.</code>, <code>,</code>, and <code>\s</code>. However I want to capture all delimiters except whit...
4
2016-09-25T19:43:22Z
39,691,418
<p>I believe this is the most efficient option regarding memory, and really efficient regarding computation time:</p> <pre><code>import re from itertools import chain from operator import methodcaller input_str = 'This, I think,., ???? MAKES , some sense ' iterator = filter(None, # Filter out all 'None's ...
0
2016-09-25T20:17:58Z
[ "python", "regex" ]
How to split up a string on multiple delimiters but only capture some?
39,691,091
<p>I want to split a string on any combination of delimiters I provide. For example, if the string is: </p> <pre><code>s = 'This, I think,., کباب MAKES , some sense ' </code></pre> <p>And the delimiters are <code>\.</code>, <code>,</code>, and <code>\s</code>. However I want to capture all delimiters except whit...
4
2016-09-25T19:43:22Z
39,691,580
<p><strong>NOTE:</strong> According to the new edit on the question, I've improved my old regex. The new one is quite long but trust me, it's work!</p> <p>I suggest a pattern below as a delimiter of the function <code>re.split()</code>:</p> <pre><code>(?&lt;![,\.\ ])(?=[,\.]+)|(?&lt;=[,\.])(?![,\.\ ])|(?&lt;=[,\.])\ ...
2
2016-09-25T20:36:02Z
[ "python", "regex" ]
How to to enable sharing for the secondary axis (twiny) in python
39,691,102
<p>I'm trying to enable sharing for both primary and secondary axis. The example plot is illustrated by the code below. The plot contains two horizontal axes, the primary axis grid is shown in green, while the other axis has red grid.</p> <pre><code>#!/usr/bin/python # -*- coding: utf-8 -*- import numpy as np import...
1
2016-09-25T19:44:10Z
39,706,112
<p>Thanks for clarifying your question. The intended use of <code>twiny</code> is to create a second fully independent x-axis with its own scale and offset, which you would then plot into. However in your case you are only using the secondary x-axis created by <code>twiny</code> as a way to display a second set of cust...
1
2016-09-26T14:58:14Z
[ "python", "matplotlib" ]
How to to enable sharing for the secondary axis (twiny) in python
39,691,102
<p>I'm trying to enable sharing for both primary and secondary axis. The example plot is illustrated by the code below. The plot contains two horizontal axes, the primary axis grid is shown in green, while the other axis has red grid.</p> <pre><code>#!/usr/bin/python # -*- coding: utf-8 -*- import numpy as np import...
1
2016-09-25T19:44:10Z
39,721,415
<p>Unfortunately the proposed callback solution is not robust enough. Most of the time panning works fine, but zooming is a disaster. Still, too often the grids get misaligned. </p> <p>Until I find out how to improve the callback solution, I decided to code a custom grid and annotate the values within the plot.</p> <...
0
2016-09-27T09:46:51Z
[ "python", "matplotlib" ]
scipy ndimage to fill array for matplotlib interpolated data
39,691,152
<p>I have an array of data representing what might look like a topographic map when plotted using a contour map. I am looking to expand the array to 'interpolate' data between points at a user-selected interval and then fill the missing elements with mean values between the existing data points. For example:</p> <pr...
0
2016-09-25T19:49:44Z
39,692,541
<p>I was doing something similar and had issues with ndimage.zoom. It was skewing the images and I was never happy with the results. I found skimage.transform.resize. This worked much better and might be useful for you. </p> <p><a href="http://scikit-image.org/docs/dev/api/skimage.transform.html#skimage.transform.resi...
0
2016-09-25T22:47:07Z
[ "python", "numpy", "matplotlib", "scipy" ]
How can I add an outline to an image?
39,691,158
<p>I'm fairly new to Python, and I have a python function that adds an outline to an image. However, the function currently adds the outline one pixel inside the image, instead of on the outside like it should. How can I modify this to make the outline further out by 1 pixel?</p> <pre><code>def addOutline(imageArray):...
0
2016-09-25T19:50:11Z
39,691,227
<p>I guess if you really want the outline to be outside the figure. You need to create a new image array with size <code>(len(newAr)+1)*(len(newAr[0]+1))</code>, where the extra pixel is to put your line. All the other pixels inside should be copied from your original image. </p>
3
2016-09-25T19:58:22Z
[ "python", "image", "python-3.x", "pillow" ]
Pandas GroupBy Doesn't Persist After Applying Quantiles?
39,691,164
<p>I'm trying to get quantiles for two distinct groups in a Pandas df. I'm able to apply to quantiles function and get a table with grouped results, however, I can't seem to call the groupby attributes on the dataframe after doing so. Example:</p> <pre><code>rand = np.random.RandomState(1) df = pd.DataFrame({'A': ['fo...
2
2016-09-25T19:51:11Z
39,691,213
<p>(First, note that your code is missing</p> <pre><code>import numpy as np import numpy.random as rand </code></pre> <p>or something like that. The second one is a bit annoying to guess.)</p> <p>Your two lines </p> <pre><code>gb = df.groupby(['A']) q=gb.quantile(np.arange(0,1.1,.1)) </code></pre> <p>Are equivalen...
2
2016-09-25T19:56:51Z
[ "python", "pandas" ]
Pandas GroupBy Doesn't Persist After Applying Quantiles?
39,691,164
<p>I'm trying to get quantiles for two distinct groups in a Pandas df. I'm able to apply to quantiles function and get a table with grouped results, however, I can't seem to call the groupby attributes on the dataframe after doing so. Example:</p> <pre><code>rand = np.random.RandomState(1) df = pd.DataFrame({'A': ['fo...
2
2016-09-25T19:51:11Z
39,694,401
<p>You can call specific groups using the index:</p> <pre><code>q.loc['foo'] </code></pre>
0
2016-09-26T03:45:09Z
[ "python", "pandas" ]
Display a matrix with putting a common factor in sympy
39,691,325
<p>I want to display a matrix with putting an extracted common factor on outside of the matrix after matrix calculation in sympy.</p> <p>I wrote below code.</p> <pre><code>from sympy import * a = symbols("a") b = symbols("b") A = Matrix([exp(I*a),exp(I*a)*exp(I*b)]) print simplify(A) </code></pre> <p>I got below ou...
1
2016-09-25T20:08:23Z
39,692,039
<p>I do not think <code>Sympy</code> provides a function for the task you want. However, you can do this manually, as per the method proposed in the accepted answer of a similar question asked in the Mathematica SE (<a href="http://mathematica.stackexchange.com/questions/44500/factor-a-vector">link</a>). </p> <p>The i...
1
2016-09-25T21:30:53Z
[ "python", "matrix", "sympy", "symbolic-math" ]
How to convert a nltk tree (Stanford) into newick format in python?
39,691,327
<p>I have this Stanford tree and I want to convert this into newick format.</p> <pre><code> (ROOT (S (NP (DT A) (NN friend)) (VP (VBZ comes) (NP (NP (JJ early)) (, ,) (NP (NP (NNS others)) (SBAR (WHADVP...
1
2016-09-25T20:08:37Z
39,691,651
<p>There might be ways to do this just using string processing, but I would parse them and print them in the newick format recursively. A somewhat minimal implementation:</p> <pre><code>import re class Tree(object): def __init__(self, label): self.label = label self.children = [] @staticmetho...
0
2016-09-25T20:43:28Z
[ "python", "tree", "nltk" ]
Finding correct path to files in subfolders with os.walk with python?
39,691,504
<p>I am trying to create a program that copies files with certain file extension to the given folder. When files are located in subfolders instead of the root folder the program fails to get correct path. In its current state the program works perfectly for the files in the root folder, but it crashes when it finds mat...
0
2016-09-25T20:26:41Z
39,691,532
<p><code>dirpath</code> is one of the things provided by <code>walk</code> for a reason: it gives the path to the directory that the items in <code>files</code> is located in. You can use that to determine the subfolder you should be using.</p>
1
2016-09-25T20:30:52Z
[ "python", "os.walk" ]
Finding correct path to files in subfolders with os.walk with python?
39,691,504
<p>I am trying to create a program that copies files with certain file extension to the given folder. When files are located in subfolders instead of the root folder the program fails to get correct path. In its current state the program works perfectly for the files in the root folder, but it crashes when it finds mat...
0
2016-09-25T20:26:41Z
39,691,701
<pre><code>file_path = os.path.abspath(i) </code></pre> <p>This line is blatantly wrong. Keep in mind that <code>filenames</code> keeps list of base file names. At this point it's just a list of strings and (technically) they are not associated at all with files in filesystem.</p> <p><a href="https://docs.python.org/...
0
2016-09-25T20:48:20Z
[ "python", "os.walk" ]
Sublime Text 3 subl command not working in windows 10
39,691,547
<p>when I run the subl command, it just pauses for a moment and doesn't give me any feedback as to what happened and doesn't open. I am currently on windows 10 running the latest sublime text 3 build. I already copied my subl.exe from my sublime text 3 directory to my system32 directory. What am I missing? I've tried s...
-1
2016-09-25T20:31:50Z
39,713,501
<p>I'm assuming that when you invoke <code>subl.exe</code> via an absolute path then it works.</p> <pre><code>&gt; "C:\Program Files\Sublime Text 3\subl.exe" </code></pre> <p>Assuming the above works, then the location of <code>subl.exe</code> can be added to the system path so that there is no need to specify the ab...
0
2016-09-26T22:41:34Z
[ "python", "command-line", "sublimetext3", "sublimetext" ]
Python 3.4 tkinter, not clearing frame after selecting a option from a menu
39,691,619
<p>This is a little program I made to find the area of different quadrilaterals, when I select a option from the drop down menu it works. But when I switch from let's say square to trapezium, I get this:</p> <p><img src="http://i.stack.imgur.com/qROin.png" alt="2"></p> <p>I want to clear the window leaving only the s...
0
2016-09-25T20:39:56Z
39,691,829
<p>When a different option from the drop down menu is selected you need to delete what you had before, then create the new widgets</p> <p>In each of your functions where you make a shape, you need to first destroy the widgets, then create the new ones</p> <p><strong>I have fixed the code:</strong></p> <pre><code>fro...
1
2016-09-25T21:05:00Z
[ "python", "tkinter" ]
Unicode encoding in email
39,691,628
<p>I have manually created and sent myself an html email in gmail. I want to be able to reuse this html output to programatically send it (using smtplib in python).</p> <p>In gmail, I view the source, which appears like:</p> <blockquote> <p>Mime-Version: 1.0 Content-Type: multipart/alternative; boundary="--==_mim...
0
2016-09-25T20:40:52Z
39,692,888
<p>There's are some <a href="https://docs.python.org/2/library/email-examples.html#email-examples" rel="nofollow">MIME examples</a> that are probably more suitable, but the simple answer from the headers is that it is UTF8 and <code>quoted-printable</code> encoding, so you can use the <code>quopri</code> module:</p> <...
1
2016-09-25T23:42:27Z
[ "python", "unicode", "unicode-string" ]
python recursion class variable
39,691,636
<p>Let me rewrite my question so that it is clearer. I encountered a issue on LeetCode problem: validate binary search tree. </p> <p>My first solution looks something like this:</p> <pre><code>class Solution(object): def recursion(self, input, var_x, ans): #update var_x #update ans self.re...
-2
2016-09-25T20:41:30Z
39,708,182
<p>The semantic difference is simple: <strong>var_x</strong> is merely a local variable, one per call instance. <strong>self.var_x</strong> is an attribute of the object, one per class instance.</p> <p>If you need the value only within the one call instance, use <strong>var_x</strong> and don't bother the objects wit...
0
2016-09-26T16:47:30Z
[ "python", "recursion", "binary-search-tree", "inorder" ]
Possible starting letters of uuid4() in Python
39,691,654
<p>I'm using uuid4() to generate random names for my files. However, I need to know the possible starting letters for these files. Can the uuid4()'s only start with [a-z,A-Z,0-9] or can they also include punctuation characters like [_-,]? I cannot find a reference for this.</p>
-2
2016-09-25T20:43:47Z
39,691,687
<p>I'm guessing you are using hex and so it would be 0-f. </p> <p>Otherwise from the spec it is: UUID.hex The UUID as a 32-character hexadecimal string.</p> <p>UUID.int The UUID as a 128-bit integer.</p> <p>UUID.urn The UUID as a URN as specified in RFC 4122.</p> <p>Ref -> <a href="https://www.ietf.org/rfc/rfc4122....
1
2016-09-25T20:47:13Z
[ "python" ]
Resampling timeseries with a given timedelta
39,691,671
<p>I am using Pandas to structure and process Data. This is my DataFrame:</p> <p><a href="http://i.stack.imgur.com/wDHTC.png" rel="nofollow"><img src="http://i.stack.imgur.com/wDHTC.png" alt="enter image description here"></a></p> <p>I want to do a resampling of time-series data, and have, for every ID (named here "3...
0
2016-09-25T20:45:58Z
39,692,605
<p>This should do the trick</p> <pre><code>all = [] for row in df.itertuples(): time_range = pd.date_range(row.beginning_time, row.end_time, freq='1S') all += (zip(time_range, [row.Id]*len(time_range), [row.bitrate]*len(time_range))) pd.DataFrame(all) In[209]: pd.DataFrame(all) Out[209]: ...
1
2016-09-25T22:58:31Z
[ "python", "datetime", "pandas", "group-by", "resampling" ]
Resampling timeseries with a given timedelta
39,691,671
<p>I am using Pandas to structure and process Data. This is my DataFrame:</p> <p><a href="http://i.stack.imgur.com/wDHTC.png" rel="nofollow"><img src="http://i.stack.imgur.com/wDHTC.png" alt="enter image description here"></a></p> <p>I want to do a resampling of time-series data, and have, for every ID (named here "3...
0
2016-09-25T20:45:58Z
39,697,742
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.melt.html" rel="nofollow"><code>melt</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/whatsnew.html#groupby-syntax-with-window-and-resample-operations" rel="nofollow"><code>resample</code> - 0.18.1 version of pandas...
1
2016-09-26T08:12:40Z
[ "python", "datetime", "pandas", "group-by", "resampling" ]
Proper model defination in django for a widget manager
39,691,679
<p>I have a model called <code>widgetManager</code> and 2 widget models called <code>emailWidget</code> and <code>TextWidget</code>. Now a single instance of widgetManager can have multiple instances of emailWidget and TextWidget. How can this be achieved with the following in mind</p> <ol> <li>Till now i only have tw...
0
2016-09-25T20:46:20Z
39,692,799
<p>If I understood your description correctly, you want a relationship where there can be many emailWidget or TextWidget for one instance of widgetManager. </p> <p>What you can do in this case is add a ForeignKey field for widgetManager to emailWidget and TextWidget. This way, you can have many instances of the widget...
0
2016-09-25T23:28:14Z
[ "python", "django", "django-models" ]
How to write nth value of list into csv file
39,691,707
<p>i have the following list :</p> <pre><code>sec_min=['37', '01', '37', '02', '37', '03', '37', '04', '37', '05',....] </code></pre> <p>i want to store this list into CVS file in following format:</p> <pre><code>37,01 37,02 37,03 37,04 ... and so on </code></pre> <p>this is what i coded:</p> <pre><code>with open(...
-1
2016-09-25T20:48:56Z
39,691,782
<p>compose a "matrix" of row length = 2, and write all the rows at once in a generator comprehension</p> <pre><code>with open('datas.csv','wb') as f: # python 2 with open('datas.csv','w',newline='') as f: # python 3 data=csv.writer(f) data.writerows(sec_min[l:l+2] for l in range(0,len(sec_min),2)) </code></pr...
1
2016-09-25T20:58:21Z
[ "python" ]
AlterField on auto generated _ptr field in migration causes FieldError
39,691,785
<p>I have two models:</p> <pre><code># app1 class ParentModel(models.Model): # some fields </code></pre> <p>Now, in another app, I have child model:</p> <pre><code># app2 from app1.models import ParentModel class ChildModel(ParentModel): # some fields here too </code></pre> <p>In initial migration for <co...
0
2016-09-25T20:59:08Z
39,692,180
<p>If your code supports it, you could just change the parent class to an abstract class and have all the fields in the child model. However, if you still do need the parent object separately, then I don't think you can change the Django OneToOne link without some serious hacking (not recommended). </p> <p>If you onl...
1
2016-09-25T21:50:06Z
[ "python", "django", "database-migration" ]
Counting phrases in Python using NLTK
39,691,816
<p>I am trying to get a phrase count from a text file but so far I am only able to obtain a word count (see below). I need to extend this logic to count the number of times a two-word phrase appears in the text file. </p> <p>Phrases can be defined/grouped by using logic from NLTK from my understanding. I believe the c...
0
2016-09-25T21:03:28Z
39,692,750
<p>You can get all the two word phrases using the <code>collocations</code> module. This tool identifies words that often appear consecutively within corpora.</p> <p>To find the two word phrases you need to first calculate the frequencies of words and their appearance in the context of other words. NLTK has a <code>Bi...
0
2016-09-25T23:21:51Z
[ "python", "nltk", "word-count", "phrase" ]
Counting phrases in Python using NLTK
39,691,816
<p>I am trying to get a phrase count from a text file but so far I am only able to obtain a word count (see below). I need to extend this logic to count the number of times a two-word phrase appears in the text file. </p> <p>Phrases can be defined/grouped by using logic from NLTK from my understanding. I believe the c...
0
2016-09-25T21:03:28Z
39,695,415
<p><code>nltk.brigrams</code> returns a pair of words and their frequency in an specific text. Try this:</p> <pre><code>import nltk from nltk import bigrams document_text = open('Words.txt', 'r') text_string = document_text.read().lower() tokens = word_tokenize(text_string) result = bigrams(tokens) </code></pre> <p>...
0
2016-09-26T05:43:39Z
[ "python", "nltk", "word-count", "phrase" ]
Itertools Chain on Nested List
39,691,830
<p>I have two lists combined sequentially to create a nested list with python's map and zip funcionality; however, I wish to recreate this with itertools. </p> <p>Furthermore, I am trying to understand why itertools.chain is returning a flattened list when I insert two lists, but when I add a nested list it simply ret...
0
2016-09-25T21:05:04Z
39,692,054
<p>I'll try to answer your questions as best I can.</p> <p>First off, <code>itertools.chain</code> doesn't work the way you think it does. <code>chain</code> takes <code>x</code> number of iterables and iterates over them in sequence. When you call <code>chain</code>, it essentially (internally) packs the objects into...
0
2016-09-25T21:32:14Z
[ "python", "python-3.x" ]
From Raw binary image data to PNG in Python
39,691,936
<p>After searching for a few hours, I ended up on <a href="http://stackoverflow.com/questions/32946436/read-img-medical-image-without-header-in-python">this</a> link. A little background information follows.</p> <p>I'm capturing live frames of a running embedded device via a hardware debugger. The captured frames are ...
2
2016-09-25T21:17:38Z
39,692,784
<p>An RGBA image has 4 channels, one for each color and one for the alpha value. The binary file seems to have a single channel, as you don't report an error when performing the <code>data.reshape(shape)</code> operation (the shape for the corresponding RGBA image would be (430, 430, 4)). I see two potential reasons:<...
2
2016-09-25T23:26:21Z
[ "python", "numpy", "matplotlib" ]
python POST request issue
39,691,962
<p>I am trying to get the title and the link of every article from <a href="https://latercera.com/resultadoBusqueda.html?q=enersis" rel="nofollow">this site</a>.</p> <p>The data of interest is loaded with javascript after some time in json response.</p> <pre><code> var ltcom = 'TEFURVJDRVJB'; var ltpapaer = 'TFRQQVB...
1
2016-09-25T21:21:09Z
39,692,546
<p>You need a <em>Referer</em> header:</p> <pre><code>headers = {"Referer": "http://www.latercera.com/resultadoBusqueda.html?q=enersis"} data = {"type": 'CONTENT', "fq": 'taxonomyId:24 AND status:2 AND launchDate:[2008-05-31T23:59:59.999Z TO NOW]', "sort": 'launchDate desc', "rows": 15, "siteCode": 'TEFURVJDRV...
0
2016-09-25T22:47:55Z
[ "python", "python-requests" ]
pandas assign value based on mean
39,692,099
<p>Let's say I have a dataframe column. I want to create a new column where the value for a given observation is 1 if the corresponding value in the old column is above average. But the value should be 0 if the value in the other column is average or below. </p> <p>What's the fastest way of doing this?</p>
0
2016-09-25T21:38:42Z
39,692,150
<p>Say you have the following DataFrame:</p> <pre><code>df = pd.DataFrame({'A': [1, 4, 6, 2, 8, 3, 7, 1, 5]}) df['A'].mean() Out: 4.111111111111111 </code></pre> <p>Comparison against the mean will get you a boolean vector. You can cast that to integer:</p> <pre><code>df['B'] = (df['A'] &gt; df['A'].mean()).astype(i...
3
2016-09-25T21:46:52Z
[ "python", "pandas" ]
Problems with my first python script
39,692,217
<p>I am trying to write a simple grading script based off an existing script that i found in a tutorial online. The goal is to ask the user their score and give the corresponding grade.</p> <p>Here is the original code:</p> <pre><code>def letterGrade(score): if score &gt;= 90: letter = 'A' else: # g...
-1
2016-09-25T21:55:28Z
39,692,252
<p>Since you are a noobie, let me give you a few tips. </p> <p>1: SO is hostile to easily google-able things</p> <p>If you google "python def" you'll see that it's the keyword for defining a function. What's a function? <em>google</em>. Oh, a function is a block of code that can be called multiple times.</p> <pre><c...
-1
2016-09-25T22:00:34Z
[ "python" ]
Problems with my first python script
39,692,217
<p>I am trying to write a simple grading script based off an existing script that i found in a tutorial online. The goal is to ask the user their score and give the corresponding grade.</p> <p>Here is the original code:</p> <pre><code>def letterGrade(score): if score &gt;= 90: letter = 'A' else: # g...
-1
2016-09-25T21:55:28Z
39,692,444
<p>The <code>def</code> keyword introduces a function. In order for your script to work interactively, can you call the <code>letterGrade</code> function like this:</p> <pre><code>def letterGrade(score): if score &gt;= 90: letter = 'A' else: # grade must be B, C, D or F if score &gt;= 80: ...
1
2016-09-25T22:32:29Z
[ "python" ]
Problems with my first python script
39,692,217
<p>I am trying to write a simple grading script based off an existing script that i found in a tutorial online. The goal is to ask the user their score and give the corresponding grade.</p> <p>Here is the original code:</p> <pre><code>def letterGrade(score): if score &gt;= 90: letter = 'A' else: # g...
-1
2016-09-25T21:55:28Z
39,692,504
<p>Ok let's first start with some pseudo code, I always try to pseudo code my problems and draw them out as much as possible, it helps me and it might help you. So the grading scale you seem to have implemented is something like this. If you have a grade lower than 100 but greater than or equal to 90 it is an A, lower ...
1
2016-09-25T22:42:37Z
[ "python" ]
Problems with my first python script
39,692,217
<p>I am trying to write a simple grading script based off an existing script that i found in a tutorial online. The goal is to ask the user their score and give the corresponding grade.</p> <p>Here is the original code:</p> <pre><code>def letterGrade(score): if score &gt;= 90: letter = 'A' else: # g...
-1
2016-09-25T21:55:28Z
39,694,567
<p>Omg hoooooooooooly crap! I need to apologize for wasting everyone's time. RPGillespie was correct, my code was working this entire time. Im new to using PyCharm and for some reason its set up in a way that you can be doing code at the top for one project, but actually "running" the code for a different project at ...
0
2016-09-26T04:07:02Z
[ "python" ]
Drawing multiple shapes at a time from a list of options (Python Turtle Graphics)?
39,692,334
<p>So, first of all, here's the requirements:</p> <ol> <li>user picks 3 shapes from a list of 6;</li> <li>user chooses size, fill color, and line color;</li> <li>user cannot pick the same shape twice</li> <li>shapes should be drawn evenly spaced, taking up 1/3 of the screen each</li> </ol> <p>Here's my code so far:</...
0
2016-09-25T22:12:47Z
39,692,994
<p>Below is an example framework that prompts the user from (a diminishing) list of shapes, divides the canvas and draws them. It only implements circles, you need to fill in the other shapes, and it's far from finished code, you need to add error checking and other finishing touches:</p> <pre><code>import turtle CA...
0
2016-09-25T23:58:44Z
[ "python", "turtle-graphics" ]
Slicing Cross-section of 2D NumPy array
39,692,351
<p>I'm looking to print a cross-section of a numpy array. I am looking to pull the first 15 rows and only data from the 5th index column.</p> <pre><code>import csv as csv import numpy as np csv_file_object = open('train.csv', 'rU') header = next(csv_file_object) data = [] for row in csv_file_object: data.append...
0
2016-09-25T22:14:58Z
39,692,430
<p>The <code>csv_file_object</code> is a file object contains all lines of your csv file without splitting. You have to use <code>csv</code> module to read them properly:</p> <pre><code>with open('train.csv', 'rU') as csv_file_object: reader = csv.DictReader(csv_file_object) data = np.array([row.values() for r...
0
2016-09-25T22:29:54Z
[ "python", "arrays", "numpy", "indices" ]
Slicing Cross-section of 2D NumPy array
39,692,351
<p>I'm looking to print a cross-section of a numpy array. I am looking to pull the first 15 rows and only data from the 5th index column.</p> <pre><code>import csv as csv import numpy as np csv_file_object = open('train.csv', 'rU') header = next(csv_file_object) data = [] for row in csv_file_object: data.append...
0
2016-09-25T22:14:58Z
39,692,734
<p>UPDATE: I did not call csv.reader() prior to opening the file</p> <pre><code>import csv as csv import numpy as np csv_file_object = csv.reader(open('train.csv', 'rU')) header = next(csv_file_object) data = [] for row in csv_file_object: data.append(row) data = np.array(data) print(data.shape) print(data[0:...
0
2016-09-25T23:19:24Z
[ "python", "arrays", "numpy", "indices" ]
Altering dictionaries/keys in Python
39,692,480
<p>I have ran the code below in Python to generate a list of words and their count from a text file. How would I go about filtering out words from my "frequency_list" variable that only have a count of 1? </p> <p>In addition, how would I export the print statement loop at the bottom to a CSV</p> <p>Thanks in advance ...
1
2016-09-25T22:39:06Z
39,692,759
<p>For the first part - you can use dict comprehension:</p> <p><code>frequency = {k:v for k,v in frequency.items() if v&gt;1}</code></p>
1
2016-09-25T23:22:34Z
[ "python", "dictionary", "export-to-csv" ]
Altering dictionaries/keys in Python
39,692,480
<p>I have ran the code below in Python to generate a list of words and their count from a text file. How would I go about filtering out words from my "frequency_list" variable that only have a count of 1? </p> <p>In addition, how would I export the print statement loop at the bottom to a CSV</p> <p>Thanks in advance ...
1
2016-09-25T22:39:06Z
39,693,023
<p>To filter out words, an alternative way would be:</p> <pre><code>frequency = dict(filter(lambda (k,v): v&gt;1, frequency.items())) </code></pre> <p>To export the print statement loop at the bottom to a CSV, you could do that:</p> <pre><code>import csv frequency_list = ['word1','word2','word3'] # example wi...
1
2016-09-26T00:03:54Z
[ "python", "dictionary", "export-to-csv" ]
Am I using the isalpha() method in my while loop correctly (Python)?
39,692,515
<p>I want to allow the user to construct an argument using premises (sentences that support your argument) and a conclusion. I want the program to raise a question (yes/no) if the user wants to add an additional premises after the first one. If yes --> premises: ____, If no --> Conclusion: ____. The problem is that i c...
-1
2016-09-25T22:43:33Z
39,692,611
<p>These lines seem problematic:</p> <pre><code>premises_qstn = raw_input("Would you like an additional premises(yes/no)? ") additional_premises = raw_input("Premises: ") </code></pre> <p>It asks if you want additional premises, but doesn't check the input (<code>premises_qstn</code>) before immediately asking for mo...
1
2016-09-25T22:59:11Z
[ "python", "while-loop" ]
RecursionError while trying to change background on multiple windows in python tkinter
39,692,529
<p>Last night I started a mini project where I wanted to make a game using <code>tkinter</code> (as opposed to <code>pygame</code> mainly because I don't know how to make multiple windows in <code>pygame</code>). </p> <p>I want the user to guess the RGB values and compute their accuracy. Yet, whenever I run my code I ...
0
2016-09-25T22:45:16Z
39,693,939
<p>Your program must have exactly one instance of <code>Tk</code>, and you must call <code>mainloop</code> exactly once. If you need additional windows, create instances of <code>Toplevel</code>. Nothing will work the way you expect if you have more than one instance of <code>Tk</code>. </p> <p>You also need to remove...
0
2016-09-26T02:36:49Z
[ "python", "tkinter", "python-3.5" ]
How to change the shape of the marker depending on a column variable?
39,692,554
<p>I am trying to create a scatter plot for a csv file in python which contains 4 columns <code>x</code>, <code>y</code>, <code>TL</code>, <code>L</code>. I am supposed to plot <code>x</code> versus <code>y</code> and change the color of the marker based on the <code>class ID</code> in the <code>TL</code> column which ...
1
2016-09-25T22:49:54Z
39,694,347
<p>You probably want something like this:</p> <pre><code>import pandas as pd from matplotlib import pyplot as plt import numpy as np df=pd.read_csv('knnDataSet.csv') df.columns=['SN','x','y','TL','L'] color=['red','green','blue'] groups = df.groupby('TL') fig, ax = plt.subplots(figsize=(11,8)) for name, group in g...
1
2016-09-26T03:38:40Z
[ "python", "matplotlib", "scatter-plot", "markers" ]
Ways to reach variables from one class to another class?
39,692,687
<p>I'm trying to create a basic game, but I'm fairly new to the python programming scene. I've come across a problem where with two classes (a player and enemy class), I want to access class variables like health from the player and enemy, and vice versa. What are some ways of doing this? </p> <p>Here's the code to be...
0
2016-09-25T23:11:07Z
39,692,741
<p>This code creates a class, and in the special <code>__init__</code> method, it assigns values to various <em>member variables</em>.</p> <pre><code>class Player(object): def __init__(self, image): self.x = 100 self.y = 240 self.health = 30 self.defense = 25 self.image = im...
0
2016-09-25T23:20:55Z
[ "python", "pygame" ]
Tensorflow: Filter must not be larger than the input
39,692,711
<p>I want to perform convolution along the training sample that is of shape [n*1] and apply zero-padding too. So far, no results.</p> <p>I am building a character-level CNN (idea taken from <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/skflow/text_classification_character_cnn.py" r...
0
2016-09-25T23:14:28Z
39,701,004
<blockquote> <p>Why is zero-padding not applied?</p> </blockquote> <p>Use <code>padding = 'SAME'</code> in conv2d for zero-padding.</p> <blockquote> <p>Could someone please explain what is happening?</p> </blockquote> <p>You can't use the 3x3 filter in the case of 'flat' image. To use the 3x3 filter, input shoul...
1
2016-09-26T10:56:25Z
[ "python", "machine-learning", "tensorflow", "deep-learning", "convolution" ]
Efficient numpy indexing: Take first N rows of every block of M rows
39,692,769
<pre><code>x = np.array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]) </code></pre> <p>I want to grab first 2 rows of array x from every block of 5, result should be:</p> <pre><code>x[fancy_indexing] = [1,2, 6,7, 11,12] </code></pre> <p>It's easy enough to build up an index like that using a for loop.</p> <p>Is there a on...
3
2016-09-25T23:24:21Z
39,692,812
<pre><code>import numpy as np x = np.array(range(1, 16)) y = np.vstack([x[0::5], x[1::5]]).T.ravel() y // =&gt; array([ 1, 2, 6, 7, 11, 12]) </code></pre> <p>Taking the first <code>N</code> rows of every block of <code>M</code> rows in the array <code>[1, 2, ..., K</code>]:</p> <pre><code>import numpy as np K = ...
0
2016-09-25T23:31:13Z
[ "python", "numpy", "vectorization" ]
Efficient numpy indexing: Take first N rows of every block of M rows
39,692,769
<pre><code>x = np.array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]) </code></pre> <p>I want to grab first 2 rows of array x from every block of 5, result should be:</p> <pre><code>x[fancy_indexing] = [1,2, 6,7, 11,12] </code></pre> <p>It's easy enough to build up an index like that using a for loop.</p> <p>Is there a on...
3
2016-09-25T23:24:21Z
39,692,899
<p>I first thought you need this to work for 2d arrays due to your phrasing of "first N rows of every block of M rows", so I'll leave my solution as this.</p> <p>You could work some magic by reshaping your array into 3d:</p> <pre><code>M = 5 # size of blocks N = 2 # number of columns to cut x = np.arange(3*4*M).resha...
0
2016-09-25T23:43:51Z
[ "python", "numpy", "vectorization" ]
Efficient numpy indexing: Take first N rows of every block of M rows
39,692,769
<pre><code>x = np.array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]) </code></pre> <p>I want to grab first 2 rows of array x from every block of 5, result should be:</p> <pre><code>x[fancy_indexing] = [1,2, 6,7, 11,12] </code></pre> <p>It's easy enough to build up an index like that using a for loop.</p> <p>Is there a on...
3
2016-09-25T23:24:21Z
39,692,907
<p>Reshape the array to multiple rows of five columns then take (slice) the first two columns of each row.</p> <pre><code>&gt;&gt;&gt; x array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]) &gt;&gt;&gt; x.reshape(x.shape[0] / 5, 5)[:,:2] array([[ 1, 2], [ 6, 7], [11, 12]]) </code></pre> ...
1
2016-09-25T23:45:05Z
[ "python", "numpy", "vectorization" ]
Efficient numpy indexing: Take first N rows of every block of M rows
39,692,769
<pre><code>x = np.array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]) </code></pre> <p>I want to grab first 2 rows of array x from every block of 5, result should be:</p> <pre><code>x[fancy_indexing] = [1,2, 6,7, 11,12] </code></pre> <p>It's easy enough to build up an index like that using a for loop.</p> <p>Is there a on...
3
2016-09-25T23:24:21Z
39,695,491
<p><strong>Approach #1</strong> Here's a vectorized one-liner using <a href="http://docs.scipy.org/doc/numpy-1.10.1/user/basics.indexing.html#boolean-or-mask-index-arrays" rel="nofollow"><code>boolean-indexing</code></a> -</p> <pre><code>x[np.mod(np.arange(x.size),M)&lt;N] </code></pre> <p><strong>Approach #2</strong...
3
2016-09-26T05:49:52Z
[ "python", "numpy", "vectorization" ]
Python Loop To Print Asterisks Based on User Input
39,692,890
<p>I'm trying to create a python program to print a certain number of asterisks based on user input. My code is below</p> <pre><code>num_stars = 3 num_printed = 0 while num_printed &lt;= num_stars: print('*') </code></pre> <p>The output is an infinite loop. I want to print the number of stars variable as asteris...
-2
2016-09-25T23:42:44Z
39,692,913
<p>You need to increment the num_printed variable.</p> <pre><code>num_stars = 3 num_printed = 0 while num_printed &lt; num_stars: print('*') num_printed += 1 </code></pre> <p>Also note that I changed the <code>&lt;=</code> to <code>&lt;</code>: you want to be checking for when <code>num_printed</code> is no ...
0
2016-09-25T23:45:50Z
[ "python" ]
Python Loop To Print Asterisks Based on User Input
39,692,890
<p>I'm trying to create a python program to print a certain number of asterisks based on user input. My code is below</p> <pre><code>num_stars = 3 num_printed = 0 while num_printed &lt;= num_stars: print('*') </code></pre> <p>The output is an infinite loop. I want to print the number of stars variable as asteris...
-2
2016-09-25T23:42:44Z
39,692,918
<p>Why not simply use</p> <pre><code>print num_stars * '*' </code></pre>
0
2016-09-25T23:46:40Z
[ "python" ]
Python Loop To Print Asterisks Based on User Input
39,692,890
<p>I'm trying to create a python program to print a certain number of asterisks based on user input. My code is below</p> <pre><code>num_stars = 3 num_printed = 0 while num_printed &lt;= num_stars: print('*') </code></pre> <p>The output is an infinite loop. I want to print the number of stars variable as asteris...
-2
2016-09-25T23:42:44Z
39,692,922
<p>The issue is that num_printed is not getting incremented.</p> <p>In the while loop, add <code>num_printed += 1</code>, and change the condition to <code>num_printed &lt; num_stars</code>, otherwise you will be printing 4 stars:</p> <pre><code>num_stars = 3 num_printed = 0 while num_printed &lt; num_stars: pri...
2
2016-09-25T23:47:03Z
[ "python" ]
Python Loop To Print Asterisks Based on User Input
39,692,890
<p>I'm trying to create a python program to print a certain number of asterisks based on user input. My code is below</p> <pre><code>num_stars = 3 num_printed = 0 while num_printed &lt;= num_stars: print('*') </code></pre> <p>The output is an infinite loop. I want to print the number of stars variable as asteris...
-2
2016-09-25T23:42:44Z
39,693,006
<p>If you don't want to use a loop here. Maybe do something like this:</p> <pre><code>stars = int(raw_input('number of stars: ')) star_list= ['*' for i in range(stars)] print ' '.join(['%s' % i for i in star_list]) </code></pre>
0
2016-09-26T00:00:36Z
[ "python" ]
Python - unorderable types: Car() > int
39,692,949
<p>I keep getting this error: </p> <pre><code>in move_the_car if self.car_fuel &gt; x_count + y_count: TypeError: unorderable types: Car() &gt; int() </code></pre> <p>From this code:</p> <pre><code>if self.fuel &gt; x_count + y_count: </code></pre> <p>I've heard global can resolve this, but I'm not sure how. If a...
-4
2016-09-25T23:50:59Z
39,693,084
<blockquote> <p>if self.car_fuel > x_count + y_count:</p> <p>TypeError: unorderable types: Car() > int()</p> </blockquote> <p>This is telling you that at some point you've assigned a <em>Car</em> instance to <code>self.car_fuel</code> when you likely intended to assign an <em>int</em> or a <em>float</em>.</p>
1
2016-09-26T00:14:40Z
[ "python" ]
If statement executes when it's false
39,692,999
<p>I am getting "Knob already attached to a node" when i try to add a knob</p> <p>i get this when i try to run my code from menu.py button.. if i run the script from the script editor i don't get the error.. why is that?</p> <pre><code>for i in nuke.allNodes(): if not i.knob("tempMb"): if sum0 == 0: ...
2
2016-09-25T23:59:07Z
39,693,035
<p>First I'm going to change the <code>elif</code> to just <code>else</code> because your if condition is already testing the elif condition and I don't see how that would be changing while in this code.</p> <pre><code>for i in nuke.allNodes(): if not i.knob("tempMb"): if sum0 == 0: nuke.messag...
1
2016-09-26T00:05:29Z
[ "python", "nuke" ]
If statement executes when it's false
39,692,999
<p>I am getting "Knob already attached to a node" when i try to add a knob</p> <p>i get this when i try to run my code from menu.py button.. if i run the script from the script editor i don't get the error.. why is that?</p> <pre><code>for i in nuke.allNodes(): if not i.knob("tempMb"): if sum0 == 0: ...
2
2016-09-25T23:59:07Z
39,693,100
<p><code>nuke.exists("Name of Knob")</code> will check if your knob exists. Try using that in your if statement.</p> <p>More details on <a href="http://community.thefoundry.co.uk/discussion/topic.aspx?f=190&amp;t=101399" rel="nofollow">Nuke forum</a>.</p> <p>See also <a href="https://www.thefoundry.co.uk/products/nuk...
0
2016-09-26T00:18:09Z
[ "python", "nuke" ]
If statement executes when it's false
39,692,999
<p>I am getting "Knob already attached to a node" when i try to add a knob</p> <p>i get this when i try to run my code from menu.py button.. if i run the script from the script editor i don't get the error.. why is that?</p> <pre><code>for i in nuke.allNodes(): if not i.knob("tempMb"): if sum0 == 0: ...
2
2016-09-25T23:59:07Z
40,057,021
<p>Try this solution:</p> <pre><code>t = nuke.Int_Knob( 'tempMb', 'tempMb' ) for i in nuke.allNodes(): if not i.knob("tempMb"): if nuke.exists("sum0"): nuke.message("First tmp knob created") i.addKnob(t) else: nuke.message("Second tmp knob created") else: ...
0
2016-10-15T08:53:09Z
[ "python", "nuke" ]
pymc determine sum of random variables
39,693,005
<p>I have two independent Normal distributed random variables <code>a, b</code>. In pymc, it's something like:</p> <pre><code>from pymc import Normal def model(): a = Normal('a', tau=0.01) b = Normal('b', tau=0.1) </code></pre> <p>I'd like to know what's <code>a+b</code> if we can see it as a normal distrib...
-2
2016-09-26T00:00:24Z
39,729,738
<p>If I understood correctly your question and code you should be doing something simpler. If you want to estimate the parameters of the distribution given by the sum of a and b, then use only the first block in the following example. If you also want to estimate the parameters for the variable a independently of the p...
0
2016-09-27T16:22:03Z
[ "python", "statistics", "probability", "pymc", "pymc3" ]
How to use Boolean OR inside a regex
39,693,056
<p>I want to use a regex to find a substring, followed by a variable number of characters, followed by any of several substrings.</p> <p>an re.findall of</p> <pre><code>"ATGTCAGGTAAGCTTAGGGCTTTAGGATT" </code></pre> <p>should give me:</p> <pre><code>['ATGTCAGGTAA', 'ATGTCAGGTAAGCTTAG', 'ATGTCAGGTAAGCTTAGGGCTTTAG'] <...
2
2016-09-26T00:09:20Z
39,693,127
<p>This is not super-easy, because a) you want overlapping matches, and b) you want greedy and non-greedy and everything inbetween.</p> <p>As long as the strings are fairly short, you can check every substring:</p> <pre><code>import re s = "ATGTCAGGTAAGCTTAGGGCTTTAGGATT" p = re.compile(r'ATG.*TA[GA]$') for start in ...
3
2016-09-26T00:23:22Z
[ "python", "regex", "parsing", "boolean-logic" ]
How to use Boolean OR inside a regex
39,693,056
<p>I want to use a regex to find a substring, followed by a variable number of characters, followed by any of several substrings.</p> <p>an re.findall of</p> <pre><code>"ATGTCAGGTAAGCTTAGGGCTTTAGGATT" </code></pre> <p>should give me:</p> <pre><code>['ATGTCAGGTAA', 'ATGTCAGGTAAGCTTAG', 'ATGTCAGGTAAGCTTAGGGCTTTAG'] <...
2
2016-09-26T00:09:20Z
39,693,824
<p>I like the accepted answer just fine :-) That is, I'm adding this for info, not looking for points.</p> <p>If you have heavy need for this, trying a match on <code>O(N^2)</code> pairs of indices may soon become unbearably slow. One improvement is to use the <code>.search()</code> method to "leap" directly to the ...
0
2016-09-26T02:18:58Z
[ "python", "regex", "parsing", "boolean-logic" ]
How to select words of equal max length from a text document
39,693,099
<p>I am trying to write a program to read a text document and output the longest word in the document. If there are multiple longest words (i.e., all of equal length) then I need to output them all in the same order in which they occur. For example, if the longest words were dog and cat your code should produce:</p> <...
0
2016-09-26T00:17:46Z
39,693,148
<p>What you need to do is to keep a list of all the longest words you've seen so far and keep the longest length. So for example, if the longest word so far has the length 5, you will have a list of all words with 5 characters in it. As soon as you see a word with 6 or more characters, you will clear that list and only...
0
2016-09-26T00:25:58Z
[ "python", "string", "maxlength" ]
How to select words of equal max length from a text document
39,693,099
<p>I am trying to write a program to read a text document and output the longest word in the document. If there are multiple longest words (i.e., all of equal length) then I need to output them all in the same order in which they occur. For example, if the longest words were dog and cat your code should produce:</p> <...
0
2016-09-26T00:17:46Z
39,693,191
<p>Ok, first off, you should probably use a <code>with</code> <code>as</code> statement, it just simplifies things and makes sure you don't mess up. So</p> <p><code>fh = open('poem.txt', 'r')</code></p> <p>becomes</p> <p><code>with open('poem.txt','r') as file:</code></p> <p>and since you're just concerned with wor...
1
2016-09-26T00:34:12Z
[ "python", "string", "maxlength" ]
Selecting text using multiple splits
39,693,115
<p>I've started to learn python and am stuck on an assignment regarding manipulating text data. An example of the text lines I need to manipulate:</p> <pre><code>From [email protected] Sat Jan 5 09:14:16 2008 </code></pre> <p>I need to extract the hours from each line (in this case 09) and then find the mos...
1
2016-09-26T00:21:29Z
39,693,257
<p>First, </p> <pre><code>import re </code></pre> <p>Then replace</p> <pre><code>words = line.split(':') for word in words: counts[word] = counts.get(word,0) + 1 </code></pre> <p>by</p> <pre><code>line = re.search("[0-9]{2}:[0-9]{2}:[0-9]{2}", line).group(0) words = line.split(':') hour = words[0] counts[hou...
1
2016-09-26T00:44:26Z
[ "python", "split" ]
Selecting text using multiple splits
39,693,115
<p>I've started to learn python and am stuck on an assignment regarding manipulating text data. An example of the text lines I need to manipulate:</p> <pre><code>From [email protected] Sat Jan 5 09:14:16 2008 </code></pre> <p>I need to extract the hours from each line (in this case 09) and then find the mos...
1
2016-09-26T00:21:29Z
39,693,330
<p>Using the same test file as Marcel Jacques Machado:</p> <pre><code>&gt;&gt;&gt; from collections import Counter &gt;&gt;&gt; Counter(line.split(' ')[-2].split(':')[0] for line in open('input')).items() [('12', 3), ('09', 4), ('15', 1), ('13', 1)] </code></pre> <p>This shows that <code>09</code> occurs 4 times whil...
1
2016-09-26T00:57:16Z
[ "python", "split" ]
Django: How do I use a foreign key field in aggregation?
39,693,126
<p>Let's say I have the following two models:</p> <pre><code>class Parent(models.Model): factor = models.DecimalField(...) ... other fields class Child(models.Model): field_a = models.DecimalField(...) field_b = models.DecimalField(...) parent = models.ForeignKey(Parent) ... other fields </cod...
5
2016-09-26T00:23:10Z
39,693,157
<p>Django let's you follow relationships with the double underscore (__) as deep as you like. So in your case <code>F('parent__factor')</code> should do the trick.</p> <p>The full queryset:</p> <pre><code>Child.objects.aggregate(value=Sum(F('field_a') * F('field_b') * F('parent__factor'), output_field=DecimalField())...
5
2016-09-26T00:27:15Z
[ "python", "django" ]
Stripe is creating customers when charge declined
39,693,185
<p>For some reason when some one charges to sign up to the subscription plan if their card is declined stripe is still creating the customer.</p> <p>I'm not particularly sure why this is happening since I am creating the customer with the charge, how do I make it so if some one signs up but their card does not go thro...
0
2016-09-26T00:33:01Z
39,694,625
<p>Are you sure its a <code>CardError</code> that would be thrown? Try doing a general <code>Exception</code>, see what error gets thrown when the card is bad. Also their API docs don't actually say an error will be thrown if the card is declined:</p> <blockquote> <p>If an invoice payment is due and a source is no...
0
2016-09-26T04:12:55Z
[ "python", "flask", "stripe-payments" ]
Stripe is creating customers when charge declined
39,693,185
<p>For some reason when some one charges to sign up to the subscription plan if their card is declined stripe is still creating the customer.</p> <p>I'm not particularly sure why this is happening since I am creating the customer with the charge, how do I make it so if some one signs up but their card does not go thro...
0
2016-09-26T00:33:01Z
39,699,269
<p>Because you <a href="https://stripe.com/docs/api#create_customer" rel="nofollow">create the customer</a> with the <code>plan</code> parameter, Stripe will attempt to create both the customer and the subscription in one go. Unless the plan has a trial period, Stripe will immediately attempt to bill the customer for t...
1
2016-09-26T09:32:39Z
[ "python", "flask", "stripe-payments" ]
Monthly credit card payment calculator shows Syntax Error
39,693,248
<p>This program is supposed to calculate the credit card balance after one year if a person only pays the minimum monthly payment required by the credit card company. When I try to run it, it shows a SyntaxError, and I'm not sure why. Here's my code:</p> <pre><code>def ccb(balance, annualInterestRate, monthlyPaymentRa...
-1
2016-09-26T00:43:21Z
39,693,338
<p>A few things (though none appear to throw SyntaxError - seconding Andrew in the comments, if it's a SyntaxError - share the full message):</p> <p>1) You can't implicitly make an integer a string, you need to cast it. Ex:</p> <pre><code>str(round(balance)) </code></pre> <p>instead of</p> <pre><code>round(balance)...
-1
2016-09-26T00:58:23Z
[ "python", "syntax-error", "banking" ]
Python mysql.connector module, Passing data into string VALUES %s
39,693,265
<p>I'm having trouble passing data into %s token. I've looked around and noticed that this Mysql module handles the %s token differently, and that it should be escaped for security reasons, my code is throwing this error. </p> <p>mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syn...
0
2016-09-26T00:45:29Z
39,693,279
<p>Pythonic string formatting is:</p> <pre><code>str1 = 'hello' str2 = 'world' '%s, %s' % (str1, str2) </code></pre> <p>Use <code>%</code> with <code>tuple</code>, not <code>,</code></p> <p>For your particular case, try:</p> <pre><code>cursor.execute(sql_insert % (data)) </code></pre>
0
2016-09-26T00:47:59Z
[ "python", "mysql" ]
Python mysql.connector module, Passing data into string VALUES %s
39,693,265
<p>I'm having trouble passing data into %s token. I've looked around and noticed that this Mysql module handles the %s token differently, and that it should be escaped for security reasons, my code is throwing this error. </p> <p>mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syn...
0
2016-09-26T00:45:29Z
39,693,357
<p>No, don't do it the way @Jeon suggested - by using string formatting you are exposing your code to <a href="https://en.wikipedia.org/wiki/SQL_injection" rel="nofollow">SQL injection attacks</a>. Instead, <em>properly parameterize the query</em>:</p> <pre><code>query = """ INSERT INTO Products ...
1
2016-09-26T01:01:03Z
[ "python", "mysql" ]
Add image to pull request comment
39,693,292
<p>I'm using the github3.py library to create a comment in a pull request from the columns field in a csv file. I would like to add an image to the comment along with the output from the columns, but I can't find a way to do this. I've read up on using PIL to open images, but <code>.create_comment()</code> only takes a...
1
2016-09-26T00:49:53Z
39,728,703
<p>The GitHub API does not support this. Commenting on a pull request is the same thing as <a href="https://developer.github.com/v3/issues/comments/#create-a-comment" rel="nofollow">commenting on a issue</a>. You'll need to host the image elsewhere and use image tag markdown to display it, e.g.,</p> <pre><code>![image...
2
2016-09-27T15:31:14Z
[ "python", "github3.py" ]
Change specific elements of a list from string to integers in python
39,693,346
<p>If I have a list such as </p> <p><code>c=['my', 'age', 'is', '5\n','The', 'temperature', 'today' 'is' ,'87\n']</code></p> <p>How do I specifically Convert the numbers of the the list into integers leaving the rest of the string as it is and get rid of the \n ?</p> <p>expected output: </p> <pre><code>`c=['my', 'a...
0
2016-09-26T00:59:59Z
39,693,370
<p>You can write a function that tries to convert to an <code>int</code> and if it fails return the original, e.g:</p> <pre><code>def conv(x): try: x = int(x) except ValueError: pass return x &gt;&gt;&gt; c = ['my', 'age', 'is', '5\n','The', 'temperature', 'today' 'is' ,'87\n'] &gt;&gt;&gt...
0
2016-09-26T01:04:31Z
[ "python", "string", "list" ]
Change specific elements of a list from string to integers in python
39,693,346
<p>If I have a list such as </p> <p><code>c=['my', 'age', 'is', '5\n','The', 'temperature', 'today' 'is' ,'87\n']</code></p> <p>How do I specifically Convert the numbers of the the list into integers leaving the rest of the string as it is and get rid of the \n ?</p> <p>expected output: </p> <pre><code>`c=['my', 'a...
0
2016-09-26T00:59:59Z
39,693,395
<p>If you don't know the format of integers in your text, or there are just too many variations, then one approach is simply to try <code>int()</code> on everything and see what succeeds or fails:</p> <pre><code>original = ['my', 'age', 'is', '5\n', 'The', 'temperature', 'today', 'is', '87\n'] revised = [] for token ...
0
2016-09-26T01:09:55Z
[ "python", "string", "list" ]
How to filter out elements from list by comparison function, which works with pairs in this list?
39,693,354
<p>I have list of PIL <em>images</em> (more than 2) and function <em>diff (im1, im2)</em>, which return True if percentage difference in images is small - i.e. if it return True, then 2 compared images - duplicate. How do I get PIL list of images without duplicates (i.e. if I have 3 equal images of sun and 2 images of ...
0
2016-09-26T01:00:44Z
39,693,451
<p>Construct a set of all the duplicates and subtract from original set. I've changed the diff to similarity test rather than an equality test to better reflect the problem description:</p> <pre><code>images_list = [ 'image red contents1', 'image green contents', 'image red contents2', ] import itertools a...
0
2016-09-26T01:19:04Z
[ "python", "list", "filter", "set", "itertools" ]
How do I replace all values equal to x in nth level of a multi index
39,693,359
<p>Consider the <code>pd.Series</code> <code>s</code></p> <pre><code>s = pd.Series(np.arange(6), pd.MultiIndex.from_product([[1, 2], [1, 2, 3]])) 1 1 0 2 1 3 2 2 1 3 2 4 3 5 dtype: int64 </code></pre> <p>I want to replace all values of <code>3</code> in the index with <c...
1
2016-09-26T01:02:17Z
39,693,548
<p>You could use <code>s.index.levels = [[1, 2], [1, 2, 4]]</code> but you may get a FutureWarning:</p> <blockquote> <p>FutureWarning: setting `levels` directly is deprecated. Use set_levels instead</p> </blockquote> <p>So you may try</p> <pre><code>&gt;&gt;&gt; s.index = s.index.set_levels([[1, 2], [1, 2, 4]]) ...
1
2016-09-26T01:32:35Z
[ "python", "pandas", "numpy", "multi-index" ]
How do I replace all values equal to x in nth level of a multi index
39,693,359
<p>Consider the <code>pd.Series</code> <code>s</code></p> <pre><code>s = pd.Series(np.arange(6), pd.MultiIndex.from_product([[1, 2], [1, 2, 3]])) 1 1 0 2 1 3 2 2 1 3 2 4 3 5 dtype: int64 </code></pre> <p>I want to replace all values of <code>3</code> in the index with <c...
1
2016-09-26T01:02:17Z
39,693,569
<p>you could reset the index</p> <pre><code>s = s.reset_index() s[s==3] = 4 In[227]: s Out[227]: level_0 level_1 0 0 1 1 0 1 1 2 1 2 1 4 2 3 2 1 4 4 2 2 4 5 2 4 5 </code></pre>
1
2016-09-26T01:36:08Z
[ "python", "pandas", "numpy", "multi-index" ]
What is a robust method for parsing a string that can be used to issue commands
39,693,396
<p>Certain tools that we all use often allow strings to be parsed as optional commands. For example, with most IRC tools one can write something like <code>/msg &lt;nick&gt; hi there!</code>, resulting in the string being parsed and executing a command.</p> <p>I was thinking about this on the weekend, and realised th...
0
2016-09-26T01:10:13Z
39,693,516
<p>Rather than hacking away at the class internals, you would be better off using a dictionary to map the command strings to a function that performs the command. Set up the dictionary at the class level, or in the <code>__init__()</code> if it might vary between instances.</p> <p>This way the dictionary serves two pu...
0
2016-09-26T01:28:11Z
[ "python", "string", "command", "irc" ]
Pandas: when can I directly assign to values array
39,693,431
<p>I was messing with pandas in the interpreter and the following behavior took me by surprise:</p> <pre><code>&gt;&gt;&gt; data2 = [[1, np.nan], [2, -17]] &gt;&gt;&gt; f2 = pd.DataFrame(data2) &gt;&gt;&gt; f2 0 1 0 1 NaN 1 2 -17.0 &gt;&gt;&gt; f2.values[1, 1] = -99.0 &gt;&gt;&gt; f2 0 1 0 1 NaN 1...
0
2016-09-26T01:15:10Z
39,693,521
<p>using .values returns a numpy array. so whatever you do after doing <code>df.values</code> will be exactly like using a numpy array.</p> <p>using<code>df.iloc[i,i]</code> allows you to set values or extract value using an integer position</p>
0
2016-09-26T01:29:12Z
[ "python", "pandas" ]
Pandas: when can I directly assign to values array
39,693,431
<p>I was messing with pandas in the interpreter and the following behavior took me by surprise:</p> <pre><code>&gt;&gt;&gt; data2 = [[1, np.nan], [2, -17]] &gt;&gt;&gt; f2 = pd.DataFrame(data2) &gt;&gt;&gt; f2 0 1 0 1 NaN 1 2 -17.0 &gt;&gt;&gt; f2.values[1, 1] = -99.0 &gt;&gt;&gt; f2 0 1 0 1 NaN 1...
0
2016-09-26T01:15:10Z
39,693,522
<p>Pandas does not guarantee when assignments to <code>df.values</code> affect <code>df</code>, so I would recommend <em>never</em> trying to modify <code>df</code> via <code>df.values</code>. How and when this works is an implementation detail. As <a href="http://stackoverflow.com/a/39693521/190597">StevenG states</a>...
1
2016-09-26T01:29:17Z
[ "python", "pandas" ]
In python how can I add a special case to a regex function?
39,693,490
<p>Say for example I want to remove the following strings from a string: </p> <pre><code>remove = ['\\u266a','\\n'] </code></pre> <p>And I have regex like this:</p> <pre><code>string = re.sub('[^A-Za-z0-9]+', '', string) </code></pre> <p>How can I add "remove" to my regex function?</p>
1
2016-09-26T01:25:12Z
39,693,576
<p>you can always remove them before doing the regex like so:</p> <pre><code>remove = ['\\u266a','\\n'] for substr in remove: string = string.replace(substr, '') </code></pre>
2
2016-09-26T01:36:56Z
[ "python", "regex" ]