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 3 Sockets - Receiving more then 1 character
39,649,551
<p>So when I open up the CMD and create a telnet connection with:</p> <p>telnet localhost 5555</p> <p>It will apear a "Welcome", as you can see on the screen below. After that every single character I type into the CMD will be printed out/send immediately. My Question is: Is it, and if yes, how is it possible to type...
0
2016-09-22T22:01:32Z
39,649,717
<p>It depends if you want to run on character mode or line mode. Presently your code is fine, but your windows telnet client runs in character mode. You could use putty to give it a try in line mode, or if you really need to run in char mode, then keep reading the buffer until a newline is sent. </p> <p>Here is what t...
0
2016-09-22T22:15:57Z
[ "python", "sockets", "python-3.x" ]
Better way to convert dialog from QT Creator and incorporate it into my mainwindow
39,649,572
<p>I'm creating a simple popup box that contains settings. I want this to be a modal dialog box. I created the window from qt creator and converted the .ui to .py using pyuic. With the main window i'm able to import the .py file into my main project so that I can make changes to the gui and not have them overwritten ev...
1
2016-09-22T22:03:45Z
39,651,176
<p>Generally, you would override the Qt Widget (i.e. <code>QMainWindow</code>) and not the class that Qt creator generates, but you can still do it the way you're doing if you want. You just need to pass the parent <code>QMainWindow</code> to the Dialog. Currently, you're not storing a reference to it.</p> <pre><cod...
1
2016-09-23T01:26:36Z
[ "python", "pyqt", "pyqt4", "qt-creator" ]
Index values of specific rows in python
39,649,649
<p>I am trying to find out Index of such rows before "None" occurs.</p> <pre><code>pId=["a","b","c","None","d","e","None"] df = pd.DataFrame(pId,columns=['pId']) pId 0 a 1 b 2 c 3 None 4 d 5 e 6 None df.index[df...
0
2016-09-22T22:10:34Z
39,649,809
<p>I am not sure for the specific example you showed. Anyway, you could do it in a more simple way:</p> <pre><code>indexes = [i-1 for i,x in enumerate(pId) if x == 'None'] </code></pre>
1
2016-09-22T22:24:52Z
[ "python", "pandas", "indexing", "shift" ]
Index values of specific rows in python
39,649,649
<p>I am trying to find out Index of such rows before "None" occurs.</p> <pre><code>pId=["a","b","c","None","d","e","None"] df = pd.DataFrame(pId,columns=['pId']) pId 0 a 1 b 2 c 3 None 4 d 5 e 6 None df.index[df...
0
2016-09-22T22:10:34Z
39,649,838
<p>The problem is that you're returning the index of the "None". You <em>compare</em> it against the previous item, but you're still reporting the index of the "None". Note that your accepted answer doesn't make this check.</p> <p>In short, you still need to plaster a "-1" onto the result of your checking.</p>
0
2016-09-22T22:27:06Z
[ "python", "pandas", "indexing", "shift" ]
Index values of specific rows in python
39,649,649
<p>I am trying to find out Index of such rows before "None" occurs.</p> <pre><code>pId=["a","b","c","None","d","e","None"] df = pd.DataFrame(pId,columns=['pId']) pId 0 a 1 b 2 c 3 None 4 d 5 e 6 None df.index[df...
0
2016-09-22T22:10:34Z
39,649,927
<p>Just <code>-1</code> from <code>df[df["pId"] == "None"].index</code>:</p> <pre><code>import pandas as pd pId=["a","b","c","None","d","e","None"] df = pd.DataFrame(pId,columns=['pId']) print(df[df["pId"] == "None"].index - 1) </code></pre> <p>Which gives you:</p> <pre><code>Int64Index([2, 5], dtype='int64') </co...
0
2016-09-22T22:37:15Z
[ "python", "pandas", "indexing", "shift" ]
In python How can I extract data from webservices response using suds
39,649,665
<p>I am using python 2.71. I got this response from webservices call using python and suds library. I would like to extract the value of tag problemName. How can I do that ?</p> <p>(200, (TESTResult){ ProblemList = (ArrayList){ Items = (ArrayOfAnyType){ Item[] = ...
0
2016-09-22T22:11:36Z
39,652,022
<p>I was able to remove (200, (TESTResult) by calling webservice without faults=False parameter for example :</p> <pre><code>#client = Client(url, transport=t, faults=False) client = Client(url, transport=t) resp = client.service.getProblemHistory(ProblemRequest) probs = resp.ProblemList.Items.Item for prob in probs ...
0
2016-09-23T03:18:16Z
[ "python", "suds" ]
Add escape characters to a variable in Python
39,649,709
<p>I need to add an escape character to a variable which I'm appending to another string and have it apply its effects. This is what I have:</p> <pre><code>h1 = ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'] h2 = ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'] ...
2
2016-09-22T22:15:25Z
39,649,787
<p>Use <code>int()</code> to convert your hex value to an integer and then <code>chr()</code> to convert that number to a character:</p> <pre><code>import itertools hexdigits = "123456789abcdef" for dig1, dig2 in itertools.product(hexdigits, hexdigits): char = chr(int(dig1 + dig2, 16)) temp = char + '\x7e\x1...
0
2016-09-22T22:23:36Z
[ "python" ]
Add escape characters to a variable in Python
39,649,709
<p>I need to add an escape character to a variable which I'm appending to another string and have it apply its effects. This is what I have:</p> <pre><code>h1 = ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'] h2 = ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'] ...
2
2016-09-22T22:15:25Z
39,649,879
<p>A somewhat faster solution that repeated <code>int</code>/<code>chr</code> calls (assuming you're using more than just the first byte produced) is to create a complete hex string and parse it all at once:</p> <pre><code>import itertools import binascii hexdigits = "123456789abcdef" completehex = ''.join(map(''.joi...
1
2016-09-22T22:32:52Z
[ "python" ]
Add escape characters to a variable in Python
39,649,709
<p>I need to add an escape character to a variable which I'm appending to another string and have it apply its effects. This is what I have:</p> <pre><code>h1 = ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'] h2 = ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'] ...
2
2016-09-22T22:15:25Z
39,650,183
<p>To answer the OP question, here is a way to convert, <strong>using the escape notation</strong>, a string containing two hexadecimal digits to a character</p> <pre><code>h = '11' temp = eval( r"'\x" + h + "'" ) </code></pre> <p>It is not, however, the best way to do the conversion (see other answers). I would sug...
0
2016-09-22T23:08:42Z
[ "python" ]
Python loop not cooperating
39,649,737
<p>I'm trying to create a loop for the given problem. I need help; it's not printing the way it should.</p> <blockquote> <p>Given positive integer num_insects, write a while loop that prints that number doubled without exceeding 100. Follow each number with a space. </p> <p>Ex: If num_insects = 8, print:</p...
-2
2016-09-22T22:18:28Z
39,649,770
<p>the <code>print</code> function implicitly adds a newline: <a href="https://docs.python.org/2/library/functions.html#print" rel="nofollow">https://docs.python.org/2/library/functions.html#print</a></p> <p>You can pass an alternative ending with the <code>end =</code> argument; try passing <code>None</code> or <code...
2
2016-09-22T22:21:50Z
[ "python" ]
Python loop not cooperating
39,649,737
<p>I'm trying to create a loop for the given problem. I need help; it's not printing the way it should.</p> <blockquote> <p>Given positive integer num_insects, write a while loop that prints that number doubled without exceeding 100. Follow each number with a space. </p> <p>Ex: If num_insects = 8, print:</p...
-2
2016-09-22T22:18:28Z
39,649,843
<p>You want to multiply <code>num_insects</code> after you print out the result. You can pass in an empty string to the end parameter as stated in matt's answer:</p> <pre><code>num_insects = 8 while num_insects &lt;= 100: print(num_insects,'', end="") num_insects = num_insects * 2 print("") # newline </cod...
3
2016-09-22T22:27:48Z
[ "python" ]
divide a disk image into smaller parts using Python
39,649,744
<p>I would like to write a program that takes a .dmg file that is 1.6 GB and split it into 100 MB chunks.</p> <p>I would like to also write another program that later can put everything back together so that it can be mounted and used.</p> <p>I am very new to Python (and any type of programming language in general) a...
0
2016-09-22T22:19:05Z
39,650,248
<p>Try this example:</p> <p><strong>split.py</strong></p> <pre><code>import sys, os kilobytes = 1024 megabytes = kilobytes * 1000 chunksize = int(1.4 * megabytes) def split(fromfile, todir, chunksize=chunksize): if not os.path.exists(todir): os.mkdir(todir) else: for fname ...
0
2016-09-22T23:16:21Z
[ "python", "python-3.x", "dmg" ]
how to deform an image deforming the coordinates
39,649,761
<p>I would like to see how an image get deformed if I know how its coordinates are deformed.</p> <p>for example: here I draw a circle</p> <pre><code>import numpy as np import matplotlib.pyplot as plt from math import * plane_side = 500.0 #arcsec y_l, x_l, = np.mgrid[-plane_side:plane_side:1000j, -plane_side:plane_s...
1
2016-09-22T22:20:31Z
39,650,032
<p>You can use <code>plt.pcolormesh()</code>:</p> <pre><code>y_c = (y_l/plane_side)**3 x_c = (x_l/plane_side)**2 ax = plt.gca() ax.set_aspect("equal") plt.pcolormesh(x_c, y_c, image, cmap="rainbow") ax.set_xlim(0, 0.2) ax.set_ylim(-0.1, 0.1); </code></pre> <p>the result:</p> <p><a href="http://i.stack.imgur.com/7Np...
2
2016-09-22T22:50:11Z
[ "python", "python-2.7", "numpy", "matplotlib" ]
how to deform an image deforming the coordinates
39,649,761
<p>I would like to see how an image get deformed if I know how its coordinates are deformed.</p> <p>for example: here I draw a circle</p> <pre><code>import numpy as np import matplotlib.pyplot as plt from math import * plane_side = 500.0 #arcsec y_l, x_l, = np.mgrid[-plane_side:plane_side:1000j, -plane_side:plane_s...
1
2016-09-22T22:20:31Z
39,650,341
<p>In general (without using a dedicated library), you should apply an inverse transformation to the coordinates of the new image. Than, you interpolate values from the original image at the calculated coordinates.</p> <p>For example, if you want to apply the following transformation:</p> <pre><code>x_new = x**2 y_ne...
1
2016-09-22T23:27:33Z
[ "python", "python-2.7", "numpy", "matplotlib" ]
python pandas 'AttributeError: Can only use .dt accessor with datetimelike values' decimal to hours
39,649,902
<p>I have a column in a df that looks like </p> <pre><code>hour 1.0 2.0 3.0 6.0 Nan </code></pre> <p>I want to convert this into a time format so like below</p> <pre><code>hour 1:00 2:00 3:00 6:00 </code></pre> <p>However I cannot get the formatting correct. I have tried to coerce the format like below. I would al...
1
2016-09-22T22:35:01Z
39,653,829
<p>Here:</p> <pre><code>pd.to_datetime(df['hour'], unit='h') </code></pre> <p>Change the <code>format</code> to <code>unit</code>. If you are using numeric data (like you are), then you <strong>cannot</strong> use <code>format</code>. <code>format</code> works only on strings.</p> <p><code>%H</code>, for example is ...
0
2016-09-23T06:18:07Z
[ "python", "pandas" ]
self.request.GET[] with href HTML
39,649,904
<p>I need to have self.request.GET[] have the correct code for when the user clicks, based on what they click in the HTML.</p> <p>Below is Main.py:</p> <pre><code>import webapp2 from data import Fighter from data import Data from pages import Page from pages import ContentPage class MainHandler(webapp2.RequestHandl...
0
2016-09-22T22:35:07Z
39,651,343
<p>I have solved my own question. It's:</p> <pre><code> if self.request.GET: if self.request.GET['fighter']: self.response.write(c.results(d.fighter_data[0].name, d.fighter_data[0].rank, d.fighter_data[0].age, d.fighter_data[0].hometown, d.fighter_data[0].fights_out_of, d.fighter_dat...
0
2016-09-23T01:48:28Z
[ "python" ]
How to output a variable inside a Listbox in Tkinter
39,650,018
<p>I've looked up on the net different guides on how to do what I want to, but i didn't find any solution that I could understand. What I want to do is to display the content stored in any variable in a Listbox in Tkinter.</p> <pre><code>#! /usr/bin/env python from tkinter import * window = Tk() test = Listbox(wind...
-1
2016-09-22T22:48:40Z
39,661,275
<p>Your listbox is disabled, which means you can't insert or delete items. Set the state to <code>"normal"</code> before inserting.</p>
0
2016-09-23T12:52:19Z
[ "python", "tkinter" ]
Import different files based on where script is being called from
39,650,075
<p>I have a file <code>global_params.py</code> which defines some global parameters that are used by a script <code>client_script.py</code>.</p> <p>Now <code>client_script.py</code> can be called from the terminal, or it can be called from another python script <code>caller.py</code>. When it's called from the termina...
0
2016-09-22T22:54:09Z
39,650,762
<p><code>__name__</code> has the name of the caller, it is <code>__main__</code> if you call <code>client_script.py</code> from the terminal, and the name of the calling script if it is called from another script. If <code>client_script.py</code> is called from within <code>caller.py</code> then <code>__name__</code>...
0
2016-09-23T00:23:01Z
[ "python", "python-2.7", "import" ]
I cant align FloatLayout in center in Kivy
39,650,082
<p>Iam tried align floatlayout in center, help-me? Uploaded image for understanding... My idea is recreate layout Windows 8 retro in Kivy, after add icons windows 8 retro in button.</p> <p><a href="http://i.stack.imgur.com/XrLFb.png" rel="nofollow"><img src="http://i.stack.imgur.com/XrLFb.png" alt="enter image descrip...
0
2016-09-22T22:54:43Z
39,650,403
<p>You can set FloatLayout size and add <code>pos_hint: {'center_y': 0.5, 'center_x': 0.5}</code>, so for example: your widest button has size_hint_x = 0.45 and buttons have size_hint_y = 0.18 + 0.3.</p> <p>Size of container: <code>size_hint: 0.45, 0.48</code></p> <p>Now, if button has <code>size_hint: 1, 1</code>, i...
0
2016-09-22T23:35:51Z
[ "python", "kivy" ]
Group list of tuples by item
39,650,110
<p>I have this list as example:</p> <pre><code>[(148, Decimal('3.0')), (325, Decimal('3.0')), (148, Decimal('2.0')), (183, Decimal('1.0')), (308, Decimal('1.0')), (530, Decimal('1.0')), (594, Decimal('1.0')), (686, Decimal('1.0')), (756, Decimal('1.0')), (806, Decimal('1.0'))] </code></pre> <p>Now i want to group by ...
2
2016-09-22T22:58:05Z
39,650,142
<p><code>itertools.groupby()</code> requires the data to be consistent or sorted.</p> <p><code>[(148, Decimal('3.0')), (148, Decimal('2.0')), (325, Decimal('3.0'))]</code> will work but <code>[(148, Decimal('3.0')), (325, Decimal('3.0')), (148, Decimal('2.0'))]</code> will not as the id is <code>148, 325, 148</code> i...
2
2016-09-22T23:01:26Z
[ "python", "python-2.7", "itertools" ]
Group list of tuples by item
39,650,110
<p>I have this list as example:</p> <pre><code>[(148, Decimal('3.0')), (325, Decimal('3.0')), (148, Decimal('2.0')), (183, Decimal('1.0')), (308, Decimal('1.0')), (530, Decimal('1.0')), (594, Decimal('1.0')), (686, Decimal('1.0')), (756, Decimal('1.0')), (806, Decimal('1.0'))] </code></pre> <p>Now i want to group by ...
2
2016-09-22T22:58:05Z
39,650,170
<p>You would first need to <em>sort</em> the data for the <em>groupby</em> to work, it groups <em>consecutive elements</em> based on the key you provide:</p> <pre><code>import operator, itertools from decimal import * test=[(148, Decimal('3.0')), (325, Decimal('3.0')), (148, Decimal('2.0')), (183, Decimal('1.0')), (30...
4
2016-09-22T23:07:04Z
[ "python", "python-2.7", "itertools" ]
How to calculate data transfer ifconfig per second in python?
39,650,173
<p>I have script like this</p> <pre><code>import os import time os.chdir('/sys/class/net/wlan1/statistics') while True: up = open('tx_bytes').read() time.sleep(1) print 'UP:',up </code></pre> <p>And the value is</p> <pre><code>UP: 2177453 UP: 2177539 UP: 2177789 UP: 2177990 </code></pre> <p>How to ...
0
2016-09-22T23:07:22Z
39,650,242
<p>Just like you did I guess.</p> <p>It's quite rough and not very accurate but the same time spent reading the before is taken into account in reading the after so I guess it's fine.</p> <pre><code>with open('/sys/class/net/wlan1/statistics/tx_bytes') as myfile: before = myfile.read() time.sleep(3) # The longer...
0
2016-09-22T23:15:51Z
[ "python", "time", "ifconfig" ]
How to calculate data transfer ifconfig per second in python?
39,650,173
<p>I have script like this</p> <pre><code>import os import time os.chdir('/sys/class/net/wlan1/statistics') while True: up = open('tx_bytes').read() time.sleep(1) print 'UP:',up </code></pre> <p>And the value is</p> <pre><code>UP: 2177453 UP: 2177539 UP: 2177789 UP: 2177990 </code></pre> <p>How to ...
0
2016-09-22T23:07:22Z
39,650,274
<p>What is your worry so far? YOu have a certain amount of innate overhead, since you have to return to the start of the file. We can reduce it somewhat by getting rid of the superfluous <strong>open</strong> commands:</p> <pre><code>import time old = 0 with open('/sys/class/net/wlan1/statistics/tx_bytes') as vol: ...
1
2016-09-22T23:19:40Z
[ "python", "time", "ifconfig" ]
UTF-16 Code Units In Python Polyglot
39,650,198
<p>I need to extract the number of UTF-16 code units from the start of the string at which a location name starts from a Python sting. I am using Polyglot NER to tag a location in a Python string. For example, "Obama was born in the United States. But I was born in Alabama", would mark "United States" and "Alabama". Th...
0
2016-09-22T23:10:21Z
39,650,900
<p>Just to clarify some of @Ignacio Vazquez-Abrams' comments. When processing or analyzing text you don't want to have to worry about how many bytes a given character takes up. That's why you take the 'encoding' out of the equation by first 'decoding' the encoded text to a separate text/str representation.</p> <pre><...
0
2016-09-23T00:42:57Z
[ "python", "utf-8", "utf", "polyglot" ]
Convert a numpy array into an array of signs with 0 as positive
39,650,312
<p>I have a large numpy array with positive data, negative data and 0s. I want to convert it to an array with the signs of the current values such that 0 is considered positive. If I use <code>numpy.sign</code> it returns 0 if the current value is 0 but I want something that returns 1 instead. Is there an easy way to d...
0
2016-09-22T23:24:16Z
39,650,350
<p>If <code>x</code> is the array, you could use <code>2*(x &gt;= 0) - 1</code>.</p> <p><code>x &gt;= 0</code> will be an array of boolean values (i.e. <code>False</code> and <code>True</code>), but when you do arithmetic with it, it is effectively cast to an array of 0s and 1s.</p> <p>You could also do <code>np.sign...
1
2016-09-22T23:28:59Z
[ "python", "numpy" ]
Creating a Number Pyramid
39,650,318
<p>I first off would like to say this may be classified as a duplicate post, based on my current research:</p> <p><a href="http://stackoverflow.com/questions/38537364/how-to-do-print-formatting-in-python-with-chunks-of-strings?noredirect=1&amp;lq=1">How to do print formatting in Python with chunks of strings?</a> and ...
0
2016-09-22T23:25:09Z
39,650,568
<ol> <li>You need to print one space more for the numbers from 10 to 15 because there is an extra character you have to take into consideration. If you change your max number to 100, you will need another space(total of 3), and so on. This means that instead if <code>print(" ")</code> you have to use <code>print(" " * ...
0
2016-09-22T23:56:02Z
[ "python", "python-3.x", "numbers", "alignment", "shapes" ]
accessing elements of a counter containing ngrams
39,650,355
<p>I am taking a string, tokenizing it, and want to look at the most common bigrams, here is what I have got:</p> <pre><code>import nltk import collections from nltk import ngrams someString="this is some text. this is some more test. this is even more text." tokens=nltk.word_tokenize(someString) tokens=[token.lower(...
0
2016-09-22T23:30:11Z
39,650,392
<p>You're probably looking for something that already exists, namely, the <a href="https://docs.python.org/3/library/collections.html#collections.Counter.most_common" rel="nofollow"><code>most_common</code></a> method on counters. From the docs: </p> <blockquote> <p>Return a list of the <code>n</code> most common el...
2
2016-09-22T23:34:18Z
[ "python", "python-3.x", "nltk", "n-gram" ]
How to add checking for more than 1dp
39,650,356
<p>Id like to stop a decimal input from being more than 00.0 (1dp). So they input a number but i want it to 1dp as its percentage (such as 44.7% or 7.5%) Here is the code:</p> <pre><code>while nameSave &lt;=0 or nameSave &gt;99: while True: try: nameSave = float(input("Enter % Sav...
0
2016-09-22T23:30:18Z
39,650,386
<pre><code>while nameSave &lt;=0 or nameSave &gt;99: while True: try: nameSave = float(input("Enter % Savings (Between 1-99%): ")) check = str(nameSave) if (check[1] == '.' and len(check) &gt; 3) or len(check) &gt; 4: print("Needs to be precise to 1 decima...
0
2016-09-22T23:33:31Z
[ "python", "python-3.4" ]
Is there a faster way to make GET requests in Go?
39,650,397
<p>Consider this program:</p> <pre><code>package main import ( "net/http" "os" ) var url = "https://upload.wikimedia.org/wikipedia/commons/f/fe/FlumeRide%2C_Liseberg_-_last_steep_POV.ogv" func main() { response, _ := http.Get(url) defer response.Body.Close() f, _ := os.Create("output.ogv") ...
3
2016-09-22T23:35:31Z
39,652,442
<p>I'm not sure what to tell you. I just tried to duplicate your findings, but for me, all 3 versions take roughly the same amount of time</p> <pre><code>wget 8.035s go 8.174s python 8.242s </code></pre> <p>Maybe try the same experiment inside a clean VM or docker container?</p>
3
2016-09-23T04:05:24Z
[ "python", "http", "go", "wget" ]
Pandas.read_csv() with special characters (accents) in column names �
39,650,407
<p>I have a <code>csv</code> file that contains some data with columns names:</p> <ul> <li><em>"PERIODE"</em></li> <li><em>"IAS_brut"</em></li> <li><em>"IAS_lissé"</em></li> <li><em>"Incidence_Sentinelles"</em></li> </ul> <p>I have a problem with the third one <strong><em>"IAS_lissé"</em></strong> which is misinter...
1
2016-09-22T23:36:12Z
39,650,730
<p>You can change the <code>encoding</code> parameter for read_csv, see the pandas doc <a href="http://pandas.pydata.org/pandas-docs/stable/io.html#dealing-with-unicode-data" rel="nofollow">here</a>. Also the python standard encodings are <a href="https://docs.python.org/3/library/codecs.html#standard-encodings" rel="n...
0
2016-09-23T00:17:57Z
[ "python", "pandas", "unicode", "utf-8", "special-characters" ]
'self' parameter in Python non-class functions
39,650,515
<p>I'm currently teaching some basic Python to an eager primary school student, and I'm having a bit of trouble wrapping my head around a strange little anomaly in this code for an etch-a-sketch.</p> <pre><code># myEtchASketch application from tkinter import * #####Set variables canvas_height = 400 canvas_width=600 ...
-2
2016-09-22T23:48:00Z
39,650,572
<p>The callable passed to <code>bind</code> takes one argument: event. So, the correct way to define the function is e.g.:</p> <pre><code>def p1_move_W(event): global p1_x canvas.create_line(p1_x, p1_y, (p1_x-line_length), p1_y, width=line_width, fill=p1_colour) p1_x=p1_x-line_length </code></pre> <p><cod...
0
2016-09-22T23:56:50Z
[ "python", "class", "tkinter", "key-bindings" ]
making change counter, cant divide coins
39,650,539
<p>I have to design a program that when an amount of an item is entered, asks the user for the amount paid,and then provides change in 20's 10's 5's 1s quarters, dimes, nickels, and pennies. I've spent hours trying to find the flaws in my code but I can't get it right. If someone could help me out that would be greatl...
1
2016-09-22T23:51:22Z
39,650,672
<pre><code>import math def to_pennies(amt): return int(math.floor(amt * 100)) def make_change(amt): pennies = to_pennies(amt) twenties = pennies % 2000 pennies -= twenties * 2000 fives = pennies % 500 pennies -= fives * 500 ... # Fill in the rest nickels = pennies % 5 pennies -= nickels * 5 retur...
-1
2016-09-23T00:10:50Z
[ "python" ]
making change counter, cant divide coins
39,650,539
<p>I have to design a program that when an amount of an item is entered, asks the user for the amount paid,and then provides change in 20's 10's 5's 1s quarters, dimes, nickels, and pennies. I've spent hours trying to find the flaws in my code but I can't get it right. If someone could help me out that would be greatl...
1
2016-09-22T23:51:22Z
39,650,778
<p>I'd recommend you to avoid using floating point numbers if the problem can be solved with integers. Think about it, in this particular problem you can convert all ammounts into pennies (multiplied by 100). That way the solution becomes straightforward, for instance:</p> <pre><code>def distribute(value): result ...
1
2016-09-23T00:24:17Z
[ "python" ]
making change counter, cant divide coins
39,650,539
<p>I have to design a program that when an amount of an item is entered, asks the user for the amount paid,and then provides change in 20's 10's 5's 1s quarters, dimes, nickels, and pennies. I've spent hours trying to find the flaws in my code but I can't get it right. If someone could help me out that would be greatl...
1
2016-09-22T23:51:22Z
39,650,893
<p>Your primary problem is that monetary calculations (and remainder operations) don't work so well with <code>float</code>. Convert to an <code>int</code> number of pennies up front, and most sources of error disappear (as long as you round properly).</p> <p>You can also simplify the code a lot. Right now, every deno...
0
2016-09-23T00:42:10Z
[ "python" ]
Convert a simple command into an AST in python
39,650,579
<p>I would like a function in Python that converts a string command into an AST (Abstract Syntax Tree).</p> <p>The syntax for the command is as follows:</p> <pre><code>commandName(3, "hello", 5.0, x::int) </code></pre> <p>A command can accept any number of comma separated values that can be either</p> <ol> <li>Inte...
0
2016-09-22T23:57:20Z
39,650,641
<p>Seems like you could just evaluate the string and then pick off the types from there:</p> <pre><code>&gt;&gt;&gt; items = ast.literal_eval('(404.5, "Hello", 5)') &gt;&gt;&gt; [{'type': type(item).__name__, 'value': item} for item in items] [{'type': 'float', 'value': 404.5}, {'type': 'str', 'value': 'Hello'}, {'typ...
5
2016-09-23T00:05:03Z
[ "python", "parsing", "abstract-syntax-tree", "pyparsing" ]
sentry-youtrack plugin: PicklingError: Can't pickle <type 'generator'>: attribute lookup __builtin__.generator failed
39,650,623
<ul> <li>sentry: 8.4.0</li> <li>sentry-youtrack plugin: 0.3.1</li> <li>youtrack-6.5.17105</li> <li>python-memcached: 1.53</li> </ul> <p>I'm trying to integrate <a href="https://www.jetbrains.com/youtrack/" rel="nofollow">youtrack</a> into <a href="https://github.com/getsentry/sentry" rel="nofollow">sentry</a> using <a...
1
2016-09-23T00:02:55Z
39,663,322
<p>This is a bug for sentry-youtrack, it should not cache a generator object. python-memcached might have a pyc file, that's why it did not dump the value like you modified. And you added (i for i in list) which also is a generator.</p> <p>You should use getsentry/sentry-youtrack since it has the <a href="https://gith...
2
2016-09-23T14:30:07Z
[ "python", "django", "generator", "sentry", "youtrack" ]
How to convert a string list to integer in python?
39,650,735
<p>I have the following list of values:</p> <pre><code>DATA = [['5', '1'], ['5', '5'], ['3', '1'], ['6', '1'], ['4', '3']] </code></pre> <p>How can I convert it to :</p> <pre><code>DATA = [[5, 1], [5, 5], [3, 1], [6, 1], [4, 3]] </code></pre> <p>Note : I have already tried the following but all are not working in ...
3
2016-09-23T00:18:39Z
39,650,771
<p>Your third one is actually correct. In Python 3 <a href="https://docs.python.org/3/library/functions.html#map">map</a> returns a map object, so you just have to call <code>list</code> on it to get a <em>list</em>. </p> <pre><code>DATA = [['5', '1'], ['5', '5'], ['3', '1'], ['6', '1'], ['4', '3']] d = [list(map(in...
5
2016-09-23T00:23:36Z
[ "python", "python-3.x" ]
Group by sparse matrix in scipy and return a matrix
39,650,749
<p>There are a few questions on SO dealing with using <code>groupby</code> with sparse matrices. However the output seem to be lists, <a href="http://stackoverflow.com/questions/35410839/group-by-on-scipy-sparse-matrix">dictionaries</a>, <a href="http://stackoverflow.duapp.com/questions/30295570/groupby-sum-sparse-matr...
1
2016-09-23T00:20:38Z
39,651,444
<p>The best way of calculating the sum of selected columns (or rows) of a <code>csr</code> sparse matrix is a matrix product with another sparse matrix that has 1's where you want to sum. In fact <code>csr</code> sum (for a whole row or column) works by matrix product, and index rows (or columns) is also done with a p...
1
2016-09-23T02:02:45Z
[ "python", "matrix", "scipy", "nlp" ]
How can I "jump" into stackframe from exception?
39,650,793
<p>Having a raised <code>exception</code> I would like to jump into that frame. To explain better what I mean I wrote this mwe:</p> <p>Assuming I have the following code:</p> <pre><code>from multiprocessing import Pool import sys # Setup debugger def raiseDebugger(*args): """ http://code.activestate.com/recipes/...
1
2016-09-23T00:26:12Z
39,651,127
<p>The call that <code>pm</code> (or <code>post_mortem</code>) calls is from the value field of <a href="https://docs.python.org/3/library/sys.html#sys.exc_info" rel="nofollow"><code>sys.exc_info</code></a>, and the default invocation of <code>post_mortem</code> is done on the <code>__traceback__</code> of that value. ...
1
2016-09-23T01:18:27Z
[ "python", "python-3.x", "debugging", "exception" ]
Python: multiplying 'for i in range(..) iteration'
39,650,852
<p>So I have an assignment where I am required to return <code>inf</code> by multiplying <code>x</code> by 10 multiple times using a:</p> <pre><code>for i in range(...) </code></pre> <p>so the main part of my code is:</p> <pre><code> def g(x): x = 10.*x for i in range(308): return x </code></...
-2
2016-09-23T00:35:42Z
39,650,979
<p>The reason it isn't iterating like you expect is because of the <code>return</code> statement. <code>return</code> exits from whatever procedure/function that you are running immediately and returns the value given to it. Here is a walk through of your first function, assuming it was called with the value of <code>4...
0
2016-09-23T00:54:35Z
[ "python", "python-3.x" ]
Python: multiplying 'for i in range(..) iteration'
39,650,852
<p>So I have an assignment where I am required to return <code>inf</code> by multiplying <code>x</code> by 10 multiple times using a:</p> <pre><code>for i in range(...) </code></pre> <p>so the main part of my code is:</p> <pre><code> def g(x): x = 10.*x for i in range(308): return x </code></...
-2
2016-09-23T00:35:42Z
39,651,079
<p>I think you have the right parts, just not arranged correctly. Try something like this:</p> <pre><code>def g(x): for i in range(308): x = 10.*x # because we've moved this line into the loop, it gets run 308 times return x # since we've unindented this line, it runs only once (after the ...
0
2016-09-23T01:09:57Z
[ "python", "python-3.x" ]
tkinter window/frame blinks on button click
39,650,869
<p>This is a tkinter program with a start/stop button to enter and exit an infinite loop that logs to a text logger widget. I cannot for the life of me figure out why, but only when the start <em>button</em> is pressed, the frame blinks/flashes, but the function runs fine. When I select start from the file menu, there ...
0
2016-09-23T00:37:58Z
39,659,394
<p>I'm not totally sure why, but adjusting my code like so has fixed this screen blink.</p> <p>I moved the <code>stop</code> and <code>loop</code> functions into the <code>TextHandler</code> class as methods. This allowed me to remove the second call to <code>TextHandler</code> and the <code>create</code> method that ...
1
2016-09-23T11:14:05Z
[ "python", "tkinter" ]
Python: TypeError: 'int' object is not subscriptable and IndexError: string index out of range
39,650,883
<p>What's the way to tokenize/separate the input passed in the function? For example, if <code>12356</code> is passed as an input, and I want to access, let's say 3rd symbol, which is <code>3</code>, what will I do? I have tried the below code in my function, but it's giving error:</p> <pre><code>print(s[2]) IndexErro...
1
2016-09-23T00:40:01Z
39,651,335
<p>The main problems are into the following <code>function</code>. </p> <pre><code>def TestComponents(months, days, years, seps): print("\nTest Months FSA") # print(months.m[0][1]) for input in ["", "0", "1", "9", "10", "11", "12", "13"]: print("'%s'\t%s" % (input, NDRecognize(input, months))) ...
0
2016-09-23T01:47:17Z
[ "python" ]
How can I make the FigureCanvas fill the entire Figure in a matplotlib widget embedded in a pyqt GUI?
39,650,940
<p>I have attempted to make a GUI with embedded matplotlib widget in it. I just need the figure to be completely filled by the FigureCanvas, I have tried about 100 different things and nothing has changed the size of the canvas one bit. I left a few of my attempts in the code denoted by "#useless" to let you know that ...
0
2016-09-23T00:49:56Z
39,663,721
<p>I figured it out after continued studying. I had made a mess early on in the project and had failed to carefully reread my code when changing the initial design. The issue was that I was creating a canvas widget and passing that widget to the MplWidget. The MplWidget correctly had its own canvas, and therefor did no...
0
2016-09-23T14:50:12Z
[ "python", "matplotlib", "pyqt4" ]
Login using Python 3.5 to SobrusPharma
39,650,967
<p>I'm trying to crawl my erp (SobrusPharma), I tried a whole lot of modules for python 3.5 and nothing works, if only someone can give me the solution for the login part, as for the crawling part it's done. The login url is : </p> <p><a href="https://sobruspharma.com/auth/login" rel="nofollow">https://sobruspharma.co...
0
2016-09-23T00:53:32Z
39,658,918
<p>It is pretty straightforward, all you need to parse is the <em>hash</em> from the form:</p> <pre><code>id="connex_form" class=" login_form"&gt; &lt;input type="hidden" name="hash" value="e60f5fef37fe07b0b516d71666071316" id="hash"&gt; </code></pre...
0
2016-09-23T10:48:41Z
[ "python", "python-requests", "python-3.5" ]
Nginx Not Serving Static Files (Django + Gunicorn) Permission denied
39,650,974
<p>nginx.conf</p> <pre><code>server { listen 80; server_name serveraddress.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/ec2-user/projectname; } location / { proxy_set_header Host $http_host; proxy_set_header X-Real-...
0
2016-09-23T00:54:27Z
39,651,048
<p>You have a permission denied issue it seems. <code>(13: Permission denied)</code></p> <p>nginx often runs under it's own <code>nginx</code> user, and this user probably does not have the permissions to access the location/files and can't serve them.</p>
0
2016-09-23T01:05:13Z
[ "python", "django", "nginx", "static", "gunicorn" ]
Nginx Not Serving Static Files (Django + Gunicorn) Permission denied
39,650,974
<p>nginx.conf</p> <pre><code>server { listen 80; server_name serveraddress.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/ec2-user/projectname; } location / { proxy_set_header Host $http_host; proxy_set_header X-Real-...
0
2016-09-23T00:54:27Z
39,651,067
<p>I just fixed it by disabling SELinux, which caused me another problem a few days ago with nginx.</p>
-1
2016-09-23T01:08:19Z
[ "python", "django", "nginx", "static", "gunicorn" ]
Sqlite3 Insertion does not retain records with Python
39,651,106
<p>I am trying to insert multiple records to sqlite database. This is my test script. </p> <pre><code>import sqlite3 from datetime import datetime company = 'fghjk' keyword = 'awesome' filename = 'test.txt' date_found = datetime.now() conn = sqlite3.connect('C:\\sqlite\\test.db') c = conn.cursor() for i in range(0,4)...
0
2016-09-23T01:15:33Z
39,651,242
<p>The problem looks to be that you're not committing the data to the database.</p> <p>Each time you open the database, you put in 4 rows, then print them, then let the cursor and connection be destroyed without committing your changes.</p> <p>Calling <code>conn.commit()</code> after all of your inserts are done will...
2
2016-09-23T01:34:13Z
[ "python", "python-2.7", "sqlite" ]
Sqlite3 Insertion does not retain records with Python
39,651,106
<p>I am trying to insert multiple records to sqlite database. This is my test script. </p> <pre><code>import sqlite3 from datetime import datetime company = 'fghjk' keyword = 'awesome' filename = 'test.txt' date_found = datetime.now() conn = sqlite3.connect('C:\\sqlite\\test.db') c = conn.cursor() for i in range(0,4)...
0
2016-09-23T01:15:33Z
39,651,263
<p>You can use the connection as a context manager. This will properly terminate the connection, including a commit.</p> <pre><code>import sqlite3 from datetime import datetime company = 'fghjk' keyword = 'awesome' filename = 'test.txt' date_found = datetime.now() conn = sqlite3.connect('test.db') first = False # use...
3
2016-09-23T01:37:06Z
[ "python", "python-2.7", "sqlite" ]
Storing location of characters in string
39,651,141
<p>I am writing a Hangman program during my free time at school, as an entry level project for Python, and I have finally run into an obstacle. </p> <h1>What I want to do:</h1> <p>So far I have printed a board to the size of the word inputted, and I can decide if the guesses are correct or not, with a working score. ...
0
2016-09-23T01:21:08Z
39,651,251
<p>I'm going to propose an alternative solution to your real problem. Mutating strings is not very idiomatic in Python and is prone to errors. My approach instead will be to keep track of which letters have been guessed and then compute the board state from that and the actual answer.</p> <pre><code>answer = 'hello wo...
1
2016-09-23T01:35:32Z
[ "python" ]
How to check and get the newest file(.xlsx) in a tempfolder?
39,651,164
<p>Here is a complicated problem...<br> When I run Python, I want to determine the newest Excel file in temporary folder (<code>%USERPROFILE%\\AppData\\Local\\Temp\\</code>) and copy it to the <code>D</code> drive on Windows.</p> <p>I searched for examples but there weren't any...</p> <p>How can I solve this problem?...
-1
2016-09-23T01:24:36Z
39,690,739
<p>Obviously you missed <code>os.chdir(os.getenv('TEMP'))</code> before the list comprehension. Or you should do <code>os.path.join(os.getenv('TEMP'), fn)</code> to pass it into <code>os.path.getmtime</code>.</p> <p>In more details:</p> <p><code>getmtime</code> cannot find the file <code>fn</code> in the current work...
1
2016-09-25T19:09:11Z
[ "python", "excel", "python-3.x" ]
Raspberry Pi Python Code Won't Move Servo
39,651,222
<p>So I am doing a little project with a Raspberry Pi that involves moving a servo motor. In the following code in <strong>Python 3</strong>, I begin by starting the servo at approximately 45 degrees. Later in the code, a different angle is determined based on the previous angle, and the the Duty Cycle is changed.</p> ...
0
2016-09-23T01:31:59Z
39,651,434
<p>According to the docs on <a href="https://sourceforge.net/p/raspberry-gpio-python/wiki/PWM/" rel="nofollow">https://sourceforge.net/p/raspberry-gpio-python/wiki/PWM/</a><a href="https://sourceforge.net/p/raspberry-gpio-python/wiki/PWM/" rel="nofollow">sourceforge</a>, the PWM will stop when the the instance variable...
0
2016-09-23T02:01:48Z
[ "python", "python-3.x", "raspberry-pi", "servo" ]
Raspberry Pi Python Code Won't Move Servo
39,651,222
<p>So I am doing a little project with a Raspberry Pi that involves moving a servo motor. In the following code in <strong>Python 3</strong>, I begin by starting the servo at approximately 45 degrees. Later in the code, a different angle is determined based on the previous angle, and the the Duty Cycle is changed.</p> ...
0
2016-09-23T01:31:59Z
39,693,140
<p>There needed to be a common ground. I was using two separate breadboards, and did not connect a common ground. As soon as I connected a common ground, the servo began to operate as I wanted. </p> <p>Thank you for the coding help!</p>
0
2016-09-26T00:24:45Z
[ "python", "python-3.x", "raspberry-pi", "servo" ]
Download a gzipped file, md5 checksum it, and then save extracted data if matches
39,651,277
<p>I'm currently attempting to download two files using Python, one a gzipped file, and the other, its checksum.</p> <p>I would like to verify that the gzipped file's contents match the md5 checksum, and then I would like to save the contents to a target directory.</p> <p>I found out how to download the files <a href...
0
2016-09-23T01:39:16Z
39,652,515
<p>In your <code>md5Gzip</code>, return a <code>tuple</code> instead of just the hash.</p> <pre><code>def md5Gzip(fname): hash_md5 = hashlib.md5() file_content = None with gzip.open(fname, 'rb') as f: # Make an iterable of the file and divide into 4096 byte chunks # The iteration ends when...
1
2016-09-23T04:13:13Z
[ "python", "io", "gzip", "md5", "downloading" ]
int() not working for floats?
39,651,352
<p>I recently ran into this in Python 3.5:</p> <pre><code>&gt;&gt;&gt; flt = '3.14' &gt;&gt;&gt; integer = '5' &gt;&gt;&gt; float(integer) 5.0 &gt;&gt;&gt; float(flt) 3.14 &gt;&gt;&gt; int(integer) 5 &gt;&gt;&gt; int(flt) Traceback (most recent call last): File "&lt;pyshell#7&gt;", line 1, in &lt;module&gt; int(...
1
2016-09-23T01:50:00Z
39,651,371
<p>It does not work because <code>flt</code> is not a string representation of an integer. You would need to convert it to <code>float</code> first then an <code>int</code>.</p> <p>e.g.</p> <pre><code>flt = '3.14' f = int(float(flt)) </code></pre> <p>output is</p> <pre><code>3 </code></pre>
3
2016-09-23T01:53:30Z
[ "python", "python-3.x", "floating-point", "int" ]
int() not working for floats?
39,651,352
<p>I recently ran into this in Python 3.5:</p> <pre><code>&gt;&gt;&gt; flt = '3.14' &gt;&gt;&gt; integer = '5' &gt;&gt;&gt; float(integer) 5.0 &gt;&gt;&gt; float(flt) 3.14 &gt;&gt;&gt; int(integer) 5 &gt;&gt;&gt; int(flt) Traceback (most recent call last): File "&lt;pyshell#7&gt;", line 1, in &lt;module&gt; int(...
1
2016-09-23T01:50:00Z
39,651,391
<p><code>int()</code> expects an number or string that contains an integer literal. Per the <a href="https://docs.python.org/3/library/functions.html#int" rel="nofollow">Python 3.5.2</a> documentation:</p> <blockquote> <p>If <em>x</em> is not a number or if <em>base</em> is given, then <strong><em>x</em> must be a s...
5
2016-09-23T01:55:34Z
[ "python", "python-3.x", "floating-point", "int" ]
int() not working for floats?
39,651,352
<p>I recently ran into this in Python 3.5:</p> <pre><code>&gt;&gt;&gt; flt = '3.14' &gt;&gt;&gt; integer = '5' &gt;&gt;&gt; float(integer) 5.0 &gt;&gt;&gt; float(flt) 3.14 &gt;&gt;&gt; int(integer) 5 &gt;&gt;&gt; int(flt) Traceback (most recent call last): File "&lt;pyshell#7&gt;", line 1, in &lt;module&gt; int(...
1
2016-09-23T01:50:00Z
39,651,548
<p>The other answers already give you a good explanation about your issue, another way to understand what's going would be doing something like this:</p> <pre><code>import sys for c in ['3.14', '5']: try: sys.stdout.write( "Casting {0} {1} to float({0})...".format(c, c.__class__)) valu...
0
2016-09-23T02:15:24Z
[ "python", "python-3.x", "floating-point", "int" ]
Error : The program 'django-admin' is currently not installed
39,651,380
<p>But it is installed, coz when I run </p> <p><code>python -m django --version</code></p> <p>it shows </p> <p><code>1.10.1</code>.</p> <p>But when I try to start some project <code>django-admin startproject mysite</code> or check the version with <code>django-admin --version</code> , it shows</p> <pre><code>The ...
0
2016-09-23T01:54:35Z
39,652,745
<p>Reinstall django:</p> <pre><code>sudo apt-get purge python-django sudo pip uninstall django sudo apt-get install python-django sudo pip install django --upgrade </code></pre> <p>Also you can use <a href="https://virtualenv.pypa.io/en/stable/" rel="nofollow">virtualenv</a> and <a href="https://virtualenvwrapper...
1
2016-09-23T04:40:16Z
[ "python", "django" ]
Tally votes from an input file?
39,651,527
<p>I'm trying to use python to create a program that can tally votes using an input file.</p> <p>Say the input file contains:</p> <pre class="lang-none prettyprint-override"><code>Abby 10 Bob 3 Abby 5 Cathy 7 Cathy 2 Bob 1 Abby 22 </code></pre> <p>I would want the program to be able to tally the numbers linked to th...
0
2016-09-23T02:12:38Z
39,651,737
<p>It looks like you're using <code>+</code> where you want <code>+=</code>:</p> <pre><code>if voteinfo[i] in candidates: candidates[voteinfo[i]] + int(voteinfo[i+1]) </code></pre> <p>Should be:</p> <pre><code>if voteinfo[i] in candidates: candidates[voteinfo[i]] += int(voteinfo[i+1]) </code></pre>
0
2016-09-23T02:39:59Z
[ "python", "loops", "dictionary", "file-io" ]
First Unique Character in a String
39,651,540
<p>Given a string, find the first non-repeating character in it and return its index. If it doesn't exist, return -1.</p> <pre><code>first_unique('leetcode') # 0 first_unique('loveleetcode') # 2 </code></pre> <p>I came up with the following solution. How can I make it more efficient for very long input strings?</p...
2
2016-09-23T02:14:11Z
39,651,600
<p>My solution uses <code>Counter</code> form the <code>collections</code> module.</p> <pre><code>from collections import Counter def first_unique(s): c = Counter(s) for i in range(len(s)): if c[s[i]] == 1: return i return -1 </code></pre>
4
2016-09-23T02:23:59Z
[ "python" ]
First Unique Character in a String
39,651,540
<p>Given a string, find the first non-repeating character in it and return its index. If it doesn't exist, return -1.</p> <pre><code>first_unique('leetcode') # 0 first_unique('loveleetcode') # 2 </code></pre> <p>I came up with the following solution. How can I make it more efficient for very long input strings?</p...
2
2016-09-23T02:14:11Z
39,651,637
<p>Suave version:</p> <pre><code>from collections import Counter, OrderedDict class OrderedCounter(Counter, OrderedDict): pass def first_unique(s): counter = OrderedCounter(s) try: return counter.values().index(1) except ValueError: return -1 </code></pre> <hr> <p>Weird version:</p>...
4
2016-09-23T02:27:47Z
[ "python" ]
First Unique Character in a String
39,651,540
<p>Given a string, find the first non-repeating character in it and return its index. If it doesn't exist, return -1.</p> <pre><code>first_unique('leetcode') # 0 first_unique('loveleetcode') # 2 </code></pre> <p>I came up with the following solution. How can I make it more efficient for very long input strings?</p...
2
2016-09-23T02:14:11Z
39,651,698
<p>Your version isn't bad for few cases with "nice" strings... but using count is quite expensive for long "bad" strings, I'd suggest you cache items, for instance:</p> <pre><code>def f1(s): if s == '': return -1 for item in s: if s.count(item) == 1: return s.index(item) ...
1
2016-09-23T02:35:22Z
[ "python" ]
First Unique Character in a String
39,651,540
<p>Given a string, find the first non-repeating character in it and return its index. If it doesn't exist, return -1.</p> <pre><code>first_unique('leetcode') # 0 first_unique('loveleetcode') # 2 </code></pre> <p>I came up with the following solution. How can I make it more efficient for very long input strings?</p...
2
2016-09-23T02:14:11Z
39,651,714
<p>I would use a for loop to iterate the <code>String</code> from the beginning and at each index, I would check if the rest of the <code>String</code> has the character at the current index by using Substring.</p> <p>Try this:</p> <pre><code>def firstUniqChar(word): for i in range(0,len(word)): ## iterate through t...
0
2016-09-23T02:37:06Z
[ "python" ]
First Unique Character in a String
39,651,540
<p>Given a string, find the first non-repeating character in it and return its index. If it doesn't exist, return -1.</p> <pre><code>first_unique('leetcode') # 0 first_unique('loveleetcode') # 2 </code></pre> <p>I came up with the following solution. How can I make it more efficient for very long input strings?</p...
2
2016-09-23T02:14:11Z
39,652,337
<p>The idea in this solution is to use a pair of defaultdicts. The first one contains an integer count of each character and the second contains the index location of the latest character read.</p> <p>After reading all of the characters, a list comprehension is used to find all of those that only occurred once (<code>...
0
2016-09-23T03:56:06Z
[ "python" ]
Override the class patch with method patch (decorator)
39,651,686
<p>I have several test methods in a class that use one type of patching for a object, so I have patched with class decorator. For a single another method i want to patch the same object differently. I tried the following approach, but the patch made as class decorator is in effect despite the method itself being decora...
0
2016-09-23T02:32:50Z
39,651,756
<p>This can only work if the class decorator is written to account for the use of method decorators. Although the class decorator appears first, it can only run after the class object has been created, which happens after all of the methods have been defined (and decorated).</p> <p>Class decorators run <em>after</em>...
0
2016-09-23T02:42:15Z
[ "python", "unit-testing", "tdd", "python-unittest", "python-unittest.mock" ]
Override the class patch with method patch (decorator)
39,651,686
<p>I have several test methods in a class that use one type of patching for a object, so I have patched with class decorator. For a single another method i want to patch the same object differently. I tried the following approach, but the patch made as class decorator is in effect despite the method itself being decora...
0
2016-09-23T02:32:50Z
39,665,324
<p>I would take an entirely different approach.</p> <pre><code>class SwitchViewTest(TestCase): class SwitchViewStub(SwitchView): """ Stub out class under test """ def __init__(self): """ Bypass Constructor """ self.args = None ... # Fill in the rest def setUp(): self.helper = self.Sw...
0
2016-09-23T16:16:42Z
[ "python", "unit-testing", "tdd", "python-unittest", "python-unittest.mock" ]
Does import call __new__ static method?
39,651,989
<p>I know that <code>__new__</code> method is called when attempt to create an instance of a class before <code>__init__</code> is called.</p> <p>But i happened to find that, import a module withou create instance will also call <code>__new__</code></p> <p>suppose i have this:</p> <p>a.py:</p> <pre><code>import abc...
1
2016-09-23T03:14:11Z
39,652,110
<p>When you use a metaclass to define a class, the metaclass is "called" implicitly (which invokes <code>__new__</code> since the metaclass here is an actual class), see <a href="https://www.python.org/dev/peps/pep-3115/" rel="nofollow">Invoking the metaclass</a>. I can't say why you see three prints here (you only hav...
2
2016-09-23T03:29:36Z
[ "python", "class", "metaclass" ]
"'module' object has no attribute 'SSLContext'" error when using flocker-api
39,651,998
<p>This is the flocker api url </p> <p><a href="https://docs.clusterhq.com/en/latest/reference/api.html" rel="nofollow">https://docs.clusterhq.com/en/latest/reference/api.html</a></p> <p>I try to use httplib to make https connection,but I can not get through the ssl verification [SSL: CERTIFICATE_VERIFY_FAILED] certi...
0
2016-09-23T03:15:22Z
39,652,872
<p>i solved my problem myself,this is my code import httplib import ssl import json import socket</p> <pre><code>httpsConn = None # KEY_FILE = "/etc/flocker/scio01.key" # CERT_FILE = "/etc/flocker/scio01.crt" # CA_FILE = "/etc/flocker/cluster.crt" KEY_FILE = "/root/lichao_test/scio01.key" CERT_FILE = ...
0
2016-09-23T04:54:55Z
[ "python", "ssl" ]
What is wrong with my histogram?
39,652,026
<pre><code>import matplotlib.pyplot as plt import numpy as np import xlrd import xlwt wb = xlrd.open_workbook('Scatter plot.xlsx') sh1 = wb.sheet_by_name('T180') sh2=wb.sheet_by_name("T181") sh3=wb.sheet_by_name("Sheet1") x= np.array([sh1.col_values(7, start_rowx=50, end_rowx=315)]) x1= np.array([sh2.col_values(1, s...
0
2016-09-23T03:18:45Z
39,674,127
<p>The shape of <code>x</code> is <code>(1, 265)</code>, it's a 2-dim array, you need to convert it to 1-dim array first:</p> <pre><code>plt.hist(x.ravel(), bins=50) </code></pre>
1
2016-09-24T08:15:34Z
[ "python", "arrays", "numpy", "histogram" ]
Django - Filtering inside of get_context_data
39,652,109
<p>Using class-based views in Django, I'm having a problem filering inside of a DetailView.</p> <p>What i would like to get is a list of all movies in a specific genre ie: <code>Movie.objects.all().filter(genre=genre_id)</code>.</p> <pre><code>class GenreView(generic.DetailView): model = Genre template_name =...
1
2016-09-23T03:29:32Z
39,652,198
<pre><code> 'all_movies': Movie.objects.all().filter(genre=pk) </code></pre> <p>you literally haven't defined pk. You need to assign the pk to the pk variable first.</p> <p>Also you don't need to include all:</p> <pre><code>Movie.objects.filter(genre=pk) </code></pre>
0
2016-09-23T03:39:41Z
[ "python", "django" ]
Django - Filtering inside of get_context_data
39,652,109
<p>Using class-based views in Django, I'm having a problem filering inside of a DetailView.</p> <p>What i would like to get is a list of all movies in a specific genre ie: <code>Movie.objects.all().filter(genre=genre_id)</code>.</p> <pre><code>class GenreView(generic.DetailView): model = Genre template_name =...
1
2016-09-23T03:29:32Z
39,652,206
<p>The <code>kwargs</code> parameter passed to <code>get_context_data</code> doesn't contain the primary key value of the object. You can get it from <code>self.kwargs</code> though:</p> <pre><code>Movie.objects.all().filter(genre=self.kwargs['pk']) </code></pre> <p>Furthermore, you will see <code>self.object</code> ...
2
2016-09-23T03:40:27Z
[ "python", "django" ]
How can I improve the speed of this shortest path/shortcut(array graph DS) solution?
39,652,116
<p>Given a maze as an array of arrays where 1 is a wall and 0 is a passable area: </p> <pre><code>Must include start node in distance, if you BFS this it will give you 21. [0][0] is the start point. | [ V [0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1], [0, 1, ...
1
2016-09-23T03:30:14Z
39,652,368
<p>You seem to be on the right track. The following approach can be considered:</p> <ol> <li><p>Form a graph of <code>n x m</code> nodes where <code>n</code> and <code>m</code> are the dimensions of the maze matrix.</p></li> <li><p>There is an edge of cost <strong>zero</strong> between two nodes if they are adjacent <...
1
2016-09-23T03:58:37Z
[ "python", "algorithm", "data-structures", "array-algorithms" ]
Error when trying to write a matplotlib plot from Pandas DataFrame to pdf
39,652,147
<p>I'm trying to write a plot from matplotlib to a pdf file but getting an error. </p> <p>I'm creating a plot using matplotlib from a Pandas DataFrame like this:</p> <pre><code>bplot = dfbuild.plot(x='Build',kind='barh',stacked='True') </code></pre> <p>From the documentation: <a href="http://matplotlib.org/faq/howto...
0
2016-09-23T03:34:03Z
39,652,874
<p>I works when I do it this way.</p> <pre><code>pp = PdfPages(r'c:\temp\page.pdf') dfbuild.plot(x=['Build','Opperator'],kind='barh',stacked='True') pp.savefig() pp.close() </code></pre> <p>From <a href="http://stackoverflow.com/questions/21364405/saving-plots-to-pdf-files-using-matplotlib">Saving plots to pdf files ...
0
2016-09-23T04:54:59Z
[ "python", "pandas", "matplotlib", "plot", "pdfpages" ]
Error when trying to write a matplotlib plot from Pandas DataFrame to pdf
39,652,147
<p>I'm trying to write a plot from matplotlib to a pdf file but getting an error. </p> <p>I'm creating a plot using matplotlib from a Pandas DataFrame like this:</p> <pre><code>bplot = dfbuild.plot(x='Build',kind='barh',stacked='True') </code></pre> <p>From the documentation: <a href="http://matplotlib.org/faq/howto...
0
2016-09-23T03:34:03Z
39,656,357
<p>The problem is that <code>dfbuild.plot</code> returns an <code>AxesSubplot</code> and not a <code>Figure</code> instance, which is required by the <code>savefig</code> function.</p> <p>This solves the issue:</p> <pre><code>pp.savefig(bplot.figure) </code></pre>
1
2016-09-23T08:37:56Z
[ "python", "pandas", "matplotlib", "plot", "pdfpages" ]
Django Integration tests for urls
39,652,204
<p>I have a django app I wanted to write tests for. For now Im writing integration tests for the urls. </p> <p>For my <code>signin</code> test , my url looks like: <code>url(r'^signin/$', login_forbidden(signin), name='signin')</code></p> <p>and my test looks like:</p> <pre><code>from django.test import TestCase c...
0
2016-09-23T03:40:23Z
39,652,238
<p>why not use reverse: <a href="https://docs.djangoproject.com/en/1.10/ref/urlresolvers/#reverse" rel="nofollow">https://docs.djangoproject.com/en/1.10/ref/urlresolvers/#reverse</a></p> <pre><code>from django.core.urlresolvers import reverse .... resp = self.client.get(reverse('campaigns', args=[1])) </code></pre> ...
1
2016-09-23T03:44:40Z
[ "python", "django", "integration-testing" ]
Django Integration tests for urls
39,652,204
<p>I have a django app I wanted to write tests for. For now Im writing integration tests for the urls. </p> <p>For my <code>signin</code> test , my url looks like: <code>url(r'^signin/$', login_forbidden(signin), name='signin')</code></p> <p>and my test looks like:</p> <pre><code>from django.test import TestCase c...
0
2016-09-23T03:40:23Z
39,652,433
<pre><code>from django.test import TestCase from django.test import Client from django.core.urlresolvers import reverse client = Client() class MainTest(TestCase): ##user login in django def user_login(self, username, password): response = self.client.login(username=username, password=username) ...
0
2016-09-23T04:04:56Z
[ "python", "django", "integration-testing" ]
Django Integration tests for urls
39,652,204
<p>I have a django app I wanted to write tests for. For now Im writing integration tests for the urls. </p> <p>For my <code>signin</code> test , my url looks like: <code>url(r'^signin/$', login_forbidden(signin), name='signin')</code></p> <p>and my test looks like:</p> <pre><code>from django.test import TestCase c...
0
2016-09-23T03:40:23Z
39,652,671
<p>For the test failure, you should first <a href="https://docs.djangoproject.com/en/1.10/topics/testing/tools/#django.test.Client.login" rel="nofollow">login</a> with some test user then make a request, otherwise the page will be redirected to the login page and thus you will get a 302 status code.</p> <p>Also you ca...
0
2016-09-23T04:32:04Z
[ "python", "django", "integration-testing" ]
Python multiprocessing lock strange behavior
39,652,270
<p>I notice a behaviour in my code that I cannot explain. This is the code:</p> <pre><code>import multiprocessing from collections import deque LOCK = multiprocessing.Lock() data = deque(['apple', 'orange', 'melon']) def f(*args): with LOCK: data.rotate() print data[0] pool = multiprocessing.Po...
0
2016-09-23T03:48:46Z
39,652,421
<p>As Tim Peters commented, the problem is not the <code>Lock</code> but that the <code>deque</code> is not shared across the processes but every process will have their own copy.</p> <p>There are some data structures provided by the <code>multiprocessing</code> module which will be shared across processes, e.g. <a hr...
1
2016-09-23T04:04:19Z
[ "python", "multiprocessing", "python-multiprocessing" ]
or statement invalid syntax
39,652,319
<p>So, a friend of mine told me about or statements but when I use it, it says invalid syntax... but won't tell me where </p> <pre><code>#Fun Game print("Enter name") firstname = input() print ("Thousands of years further from our time, the continents collided, creating mass devastation and heat.You,"+firstname+" l...
0
2016-09-23T03:54:25Z
39,652,375
<pre><code>print("Enter name") firstname = input() print ("Thousands of years further from our time, the continents collided, creating mass devastation and heat.You,"+firstname+" lived in a peacful village until") print (" your village was raided by four men, everyone else died other than you, who was trained as an ...
0
2016-09-23T03:59:09Z
[ "python", "python-3.x" ]
or statement invalid syntax
39,652,319
<p>So, a friend of mine told me about or statements but when I use it, it says invalid syntax... but won't tell me where </p> <pre><code>#Fun Game print("Enter name") firstname = input() print ("Thousands of years further from our time, the continents collided, creating mass devastation and heat.You,"+firstname+" l...
0
2016-09-23T03:54:25Z
39,652,438
<p>When you use the 'or' operator, you use it as part of the condition. For example:</p> <pre><code>if x == 1 or x == 5: print(x) </code></pre> <p>So your code would be one long line, without all of the print statements:</p> <pre><code>if age1 == "20" or age1 == "21" or age1 == "22" or age1 == "23" or age1 == "2...
0
2016-09-23T04:05:09Z
[ "python", "python-3.x" ]
or statement invalid syntax
39,652,319
<p>So, a friend of mine told me about or statements but when I use it, it says invalid syntax... but won't tell me where </p> <pre><code>#Fun Game print("Enter name") firstname = input() print ("Thousands of years further from our time, the continents collided, creating mass devastation and heat.You,"+firstname+" l...
0
2016-09-23T03:54:25Z
39,652,451
<p>Poonam's answer looks fine, but you probably also don't want that many if statements:</p> <pre><code>print("Enter name") firstname = input() print ("Thousands of years further from our time, the continents collided, creating mass devastation and heat.You,"+firstname+" lived in a peacful village until") print (" ...
0
2016-09-23T04:06:25Z
[ "python", "python-3.x" ]
regex - merge repeated consecutive words preserving last space
39,652,420
<p>I have a string like this</p> <p><code>{{TAG}} {{TAG}}{{TAG}} {{TAG}} some other text. {{TAG}} {{TAG}}</code></p> <p>and I am trying to merge multiple consecutive occurrences of <code>{{TAG}}</code> into one. So I have this regex <code>re.sub(r'(({{TAG}})\s*)+', "{{TAG}}", text)</code> which works fine to remove m...
0
2016-09-23T04:04:17Z
39,652,519
<p>One simple way is that instead of <code>+</code> you can split the regex into two as</p> <pre><code>&gt;&gt;&gt; re.sub(r'(?:{{TAG}}\s*)*{{TAG}}', r'{{TAG}}', string) '{{TAG}} some other text. {{TAG}}' </code></pre> <ul> <li><p><code>(?:{{TAG}}\s*)*</code> Matches zero or more <code>{{TAG}}</code> with space at th...
3
2016-09-23T04:13:20Z
[ "python", "regex" ]
regex - merge repeated consecutive words preserving last space
39,652,420
<p>I have a string like this</p> <p><code>{{TAG}} {{TAG}}{{TAG}} {{TAG}} some other text. {{TAG}} {{TAG}}</code></p> <p>and I am trying to merge multiple consecutive occurrences of <code>{{TAG}}</code> into one. So I have this regex <code>re.sub(r'(({{TAG}})\s*)+', "{{TAG}}", text)</code> which works fine to remove m...
0
2016-09-23T04:04:17Z
39,652,581
<p>You're matching <code>{{TAG}}\s*</code> once or more, but you want to match <code>{{TAG}}</code> once, followed by zero or more instances of <code>\s*{{TAG}}</code>.</p> <pre><code>re.sub('({{TAG}}(?:\s*{{TAG}})*)', '{{TAG}}', text) </code></pre>
1
2016-09-23T04:20:08Z
[ "python", "regex" ]
Confusion matrix raws are mismatched
39,652,447
<p>I've created a confusion matrix that works all right but its raws don't seem to be connected with the labels as should be.</p> <p>I have some list of strings which is splitted into train and test sections:</p> <pre><code> train + test: positive: 16 + 4 = 20 negprivate: 53 + 14 = 67 negstratified: 893 + 224 = 1...
0
2016-09-23T04:06:11Z
39,653,103
<p>I think it is just sort-order of your labels, i.e. the output of <code>np.unique(target)</code>.</p>
0
2016-09-23T05:20:06Z
[ "python", "scikit-learn", "confusion-matrix" ]
Confusion matrix raws are mismatched
39,652,447
<p>I've created a confusion matrix that works all right but its raws don't seem to be connected with the labels as should be.</p> <p>I have some list of strings which is splitted into train and test sections:</p> <pre><code> train + test: positive: 16 + 4 = 20 negprivate: 53 + 14 = 67 negstratified: 893 + 224 = 1...
0
2016-09-23T04:06:11Z
39,659,665
<p>It's always best to have integer class labels, everything seems to run a bit smoother. You can get these using <code>LabelEncoder</code>, i.e.</p> <pre><code>from sklearn import preprocessing my_tags = ['negprivate', 'negstratified', 'positive'] le = preprocessing.LabelEncoder() new_tags = le.fit_transform(my_tags)...
0
2016-09-23T11:27:49Z
[ "python", "scikit-learn", "confusion-matrix" ]
Can't kick out of while loop
39,652,449
<pre><code>#Fiery Elsa #ID:899525 #Homework 2, Program 2 #Initialization count=0 name=input("Enter stock name OR -999 to Quit:") #Input while name!=-999: count=count+1 name=input("Enter stock name OR -999 to Quit:") shares=int(input("Enter number of shares:")) pp=float(input("Enter purchase price:"))...
0
2016-09-23T04:06:18Z
39,652,568
<p>Your problem seems to be that <code>name</code> is type <code>string</code>, but you're comparing it to <code>-999</code> which has type <code>int</code>.</p> <p>If you change your loop to read <code>name != "-999"</code> then the comparison works. You'll need to refactor your code some more to make it behave the ...
0
2016-09-23T04:18:31Z
[ "python", "python-3.x", "while-loop" ]
Can't kick out of while loop
39,652,449
<pre><code>#Fiery Elsa #ID:899525 #Homework 2, Program 2 #Initialization count=0 name=input("Enter stock name OR -999 to Quit:") #Input while name!=-999: count=count+1 name=input("Enter stock name OR -999 to Quit:") shares=int(input("Enter number of shares:")) pp=float(input("Enter purchase price:"))...
0
2016-09-23T04:06:18Z
39,667,764
<p>You need to evaluate the value of name after each input.</p> <pre><code>stock_name = [] # make a list for stock name shares = [] # change also all other input variables into list type while True: # this will allow you to loop the input part name = input() if name != '-999': # this will evaluate the ...
0
2016-09-23T18:56:55Z
[ "python", "python-3.x", "while-loop" ]
Can't kick out of while loop
39,652,449
<pre><code>#Fiery Elsa #ID:899525 #Homework 2, Program 2 #Initialization count=0 name=input("Enter stock name OR -999 to Quit:") #Input while name!=-999: count=count+1 name=input("Enter stock name OR -999 to Quit:") shares=int(input("Enter number of shares:")) pp=float(input("Enter purchase price:"))...
0
2016-09-23T04:06:18Z
39,673,570
<pre><code>while name!="-999": #try this one count=count+1 name=input("Enter stock name OR -999 to Quit:") shares=int(input("Enter number of shares:")) pp=float(input("Enter purchase price:")) sp=float(input("Enter selling price:")) commission=float(input("Enter commission:")) </code></pre>
0
2016-09-24T07:05:26Z
[ "python", "python-3.x", "while-loop" ]
How do I not declare a variable in a loop in Python when I have an except argument
39,652,464
<p>I am trying to iterate through all of the rows on the xml list and write those to csv I need each element value, if it exists, to be written, pipe delimited into the row, or else display a null value. I am able to create the header row and write in the first row of data by using variables, (which is obviously incorr...
0
2016-09-23T04:07:51Z
39,653,079
<p>Actually, if you indent the last two lines one level, I think you'd have what you're looking for. Your comment in the code mentions "declaring the variable in the loop", but Python variables aren't declared - the only rule is that they must be defined before they are used, which is what you are doing.</p> <p>As fa...
0
2016-09-23T05:17:50Z
[ "python", "xml", "list", "loops", "csv" ]
pillow image TypeError: an integer is required (got type tuple)
39,652,480
<p>I am a bit lost as to why this is happening any help would be greatly appreciated. So I am trying to take the median value of images and create a new image from them, but when trying to make newpix take in the values of my red green and blue median pixel the error: </p> <p>TypeError: an integer is required (got typ...
1
2016-09-23T04:09:42Z
39,672,503
<p>Problem is at the lines</p> <pre><code> red = z.getpixel((x,y)) blue = z.getpixel((x,y)) green = z.getpixel((x,y)) redPixels.append(red) greenPixels.append(green) bluePixels.append(blue) </code></pre> <p><code>red = z.getpixel((x,y))</code> will get all R,G,B data a...
2
2016-09-24T04:28:20Z
[ "python", "image", "python-3.x", "python-imaging-library", "pillow" ]
unable to write to CSV after replace
39,652,537
<p>I have an input file, in which I am making an string replace operation.</p> <p>I read the file cell by cell, replace the string and then write it back to a new CSV file.</p> <pre><code>input_file = open('/Users/tcssig/Desktop/unstacked2.csv', 'r', encoding='utf-8') output_file = open('/Users/tcssig/Desktop/unstack...
1
2016-09-23T04:14:56Z
39,652,627
<p>Close your files: </p> <pre><code>output_file.close() input_file.close() </code></pre> <p>Also see this answer regarding use of context managers <a href="http://stackoverflow.com/a/441446/4663466">http://stackoverflow.com/a/441446/4663466</a></p>
2
2016-09-23T04:26:23Z
[ "python", "csv" ]
unable to write to CSV after replace
39,652,537
<p>I have an input file, in which I am making an string replace operation.</p> <p>I read the file cell by cell, replace the string and then write it back to a new CSV file.</p> <pre><code>input_file = open('/Users/tcssig/Desktop/unstacked2.csv', 'r', encoding='utf-8') output_file = open('/Users/tcssig/Desktop/unstack...
1
2016-09-23T04:14:56Z
39,653,046
<p>Content of input file:</p> <pre><code>"Roll No" English read Science "Roll No" English Write Science </code></pre> <p><strong>Problem with your code:</strong></p> <ol> <li>As mentioned by <strong>@Scott</strong>, files are not closed.</li> <li><p>Your are reading cell by <code>for string in row:</code> and replac...
1
2016-09-23T05:15:04Z
[ "python", "csv" ]
How to know which .whl module is suitable for my system with so many?
39,652,553
<p>We have so may versions of wheel. How could we know which version should be installed into my system? I remember there is a certain command which could check my system environment. Or is there any other ways?</p> <p>---------------------Example Below this line -----------</p> <p>scikit_learn-0.17.1-cp27-cp27m-win...
0
2016-09-23T04:16:44Z
39,652,742
<p>You don't have to know. Use <code>pip</code> - it will select the most specific wheel available.</p>
0
2016-09-23T04:40:01Z
[ "python", "python-wheel", "python-install" ]
Creating EC2 instances with key pairs in Boto2
39,652,655
<p>I have the following code using boto.ec2 to connect to Amazon EC2 from python, but I'm struggling to deal with the .pem files. If I pass None to the run_instances call as the key name, I can create instances without any problem. However, if I pass any key name (whether or not I create it using the console, or manual...
0
2016-09-23T04:29:58Z
39,669,962
<p>This code (derived from yours) worked for me:</p> <pre><code>&gt;&gt;&gt; import boto.ec2 &gt;&gt;&gt; conn = boto.ec2.connect_to_region('ap-southeast-2') &gt;&gt;&gt; key_res = conn.get_all_key_pairs(keynames=['class'])[0] &gt;&gt;&gt; key_res KeyPair:class &gt;&gt;&gt; key_res.name u'class' &gt;&gt;&gt; conn.run_...
1
2016-09-23T21:41:50Z
[ "python", "amazon-web-services", "amazon-ec2", "boto" ]
Dask Bag read_text() line order
39,652,733
<p>Does dask.bag.read_text() preserve the line order? Is it still preserved when reading from multiple files?</p> <pre><code>bag = db.read_text('program.log') bag = db.read_text(['program.log', 'program.log.1']) </code></pre>
0
2016-09-23T04:39:03Z
39,653,040
<p>Informally, yes, most Dask.bag operations do preserve order. </p> <p>This behavior is not strictly guaranteed, however I don't see any reason to anticipate a change in the near future.</p>
1
2016-09-23T05:14:41Z
[ "python", "data-science", "dask", "bag" ]
How to refactor polymorphic method to keep code DRY
39,652,788
<p>Here is an example of the code I am working with while learning polymorphic behaviour in python. My question is: Why do I have to declare the very similar function of show_affection twice? Why not check if the caller (the instance calling the method) and if it is Dog, do one thing, if it is a cat do another.</p> <p...
0
2016-09-23T04:45:28Z
39,653,050
<p>This is not an example of "repeating yourself", because <code>Cat.show_affection()</code> does something different from <code>Dog.show_affection()</code>. If the two methods were the same, then you could avoid repetition by defining the implementation once in <code>Animal</code>. But since you want to have differe...
1
2016-09-23T05:15:24Z
[ "python", "polymorphism" ]
Regex Match Whole Multiline Comment Cointaining Special Word
39,652,922
<p>I've been trying to design this regex but for the life of me I could not get it to not match if */ was hit before the special word.</p> <p>I'm trying to match a whole multi line comment only if it contains a special word. I tried negative lookaheads/behinds but I could not figure out how to do it properly.</p> <p...
2
2016-09-23T05:01:13Z
39,652,970
<p>You were not totally off base:</p> <pre><code>/\* # match /* (?:(?!\*/)[\s\S])+? # match anything lazily, do not overrun */ special # match special [\s\S]+? # match anything lazily afterwards \*/ # match the closing */ </code></pre> <p>The technique is called ...
2
2016-09-23T05:06:06Z
[ "python", "regex" ]
Repeated "Kernel died, restarting" forever
39,652,946
<p>When I attempt to run</p> <pre><code>$ jupyter qtconsole </code></pre> <p>The console shows up, with the message</p> <pre><code>Kernel died, restarting ________________________ Kernel died, restarting ________________________ Kernel died, restarting ________________________ Kernel died, restarting _______________...
0
2016-09-23T05:04:00Z
39,652,947
<p>Given that the kernel is another process, I was able to catch the command line it was started with, using Process Explorer. The command line was</p> <pre><code>$ pythonw -m ipykernel -f "$USERHOME/AppData/Roaming/jupyter/runtime/kernel-2744.json" </code></pre> <p>Then, I just launched <code>python</code> and tried...
0
2016-09-23T05:04:00Z
[ "python", "jupyter", "qtconsole", "jupyter-console" ]
Django How PermissionRequireMixin class works in code level?(I am even looking into mixins.py in auth folder)
39,652,954
<p>I would like to know how PermissionRequireMixin works in Django. (I couldn't find any question explaining how PermissionRequireMixin works in very detail. I am looking into code 'mixins.py' in path of 'django.contrib.auth'.)</p> <p>For example, if write codes like below, it will check if login-user has permission n...
0
2016-09-23T05:04:21Z
39,653,258
<p>In the end the authentication backends are responsible to grant or deny access.</p> <p>As you might have noticed, the <code>PermissionRequiredMixin</code> in the end calls <code>has_perm</code> on the user object with the defined permissions. This method just wraps an internal method called <a href="https://github....
0
2016-09-23T05:33:53Z
[ "python", "django" ]
How to parse dates for incomplete dates in Python
39,653,042
<p>I am using dateutil.parser to parse dates and I want to throw an exception if the date is incomplete i.e January 1 (missing year) or January 2016 (missing day). So far I have the following </p> <pre><code>try: parse(date) return parse(date).isoformat() except ValueError: return 'invalid' </code></pre>
0
2016-09-23T05:14:47Z
39,655,096
<p>You can use private method <code>_parse</code> of class <code>dateutil.parser.parser</code> to determine if day, month and year have been supplied. Since the method is private its behaviour may change and it is generally not advisable to use private methods of other classes in production code, but in this particular...
0
2016-09-23T07:29:51Z
[ "python" ]