title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
How does Python determine which type to cast something to?
38,211,657
<p>Suppose I have the following:</p> <pre><code>x = "0" y = 0 if x == y: print "You're winner!" </code></pre> <p>Will Python convert <code>x</code> to an int, or <code>y</code> to a string? Is there any way to control this behavior?</p>
0
2016-07-05T19:54:36Z
38,211,717
<p>Python doesn't do any typecasting for you. If you want to control it, then you should be explicit.</p> <hr> <p>Note that just because python doesn't do any typecasting for you, various objects <em>might</em>. In this case, all of the magic is in the <code>__eq__</code> method for <code>int</code> and <code>str</...
4
2016-07-05T19:58:33Z
[ "python", "casting", "comparison" ]
Return dictionary value as tuple or list from a string
38,211,770
<p>I have a long string which I'm reading from a file line by line.I'm trying to convert the lines to dictionary and trying to check if the given is present in the dictionary key values it has to return true.</p> <p><strong>Example:</strong></p> <pre><code>&gt;&gt;&gt; data 'Xyz pqrs,uvw' &gt;&gt;&gt; dict(li...
3
2016-07-05T20:02:22Z
38,211,904
<p>You have to clarify your rules. But from what you've shown us this regular expression should do the job</p> <pre><code>import re pattern = re.compile(r'[\s,]*') result = {} for line in data.strip().splitlines(): parts = pattern.split(line) key = parts[0] values = parts[1:] if 'pqrs' in values: ...
0
2016-07-05T20:11:01Z
[ "python", "dictionary" ]
Return dictionary value as tuple or list from a string
38,211,770
<p>I have a long string which I'm reading from a file line by line.I'm trying to convert the lines to dictionary and trying to check if the given is present in the dictionary key values it has to return true.</p> <p><strong>Example:</strong></p> <pre><code>&gt;&gt;&gt; data 'Xyz pqrs,uvw' &gt;&gt;&gt; dict(li...
3
2016-07-05T20:02:22Z
38,211,945
<p>You can create the dictionary with a nested dictionary-comprehension:</p> <pre><code>&gt;&gt;&gt; data = """Xyz pqrs,uvw ... Abc foo,bar,blub""" &gt;&gt;&gt; d = {key: values.split(",") for key, values in (line.split() for line in data.splitlines())} &gt;&gt;&gt; d {'Xyz': ['pqrs', ...
4
2016-07-05T20:13:55Z
[ "python", "dictionary" ]
How to get an expression between balanced parentheses
38,211,773
<p>Suppose I am given the following kind of string:</p> <pre><code>"(this is (haha) a string(()and it's sneaky)) ipsom (lorem) bla" </code></pre> <p>and I want to extract substrings contained within a topmost layer of parentheses. I.e. I want to obtain the strings:<code>"this is (haha) a string(()and it's sneaky)"</c...
3
2016-07-05T20:02:29Z
38,212,000
<p>Are you sure regex isn't good enough?</p> <pre><code>&gt;&gt;&gt; x=re.compile(r'\((?:(?:\(.*?\))|(?:[^\(\)]*?))\)') &gt;&gt;&gt; x.findall("(this is (haha) a string(()and it's sneaky)) ipsom (lorem) bla") ["(this is (haha) a string(()and it's sneaky)", '(lorem)'] &gt;&gt;&gt; x.findall("((((this is (haha) a string...
1
2016-07-05T20:18:04Z
[ "python", "string", "xml-parsing", "parentheses" ]
How to get an expression between balanced parentheses
38,211,773
<p>Suppose I am given the following kind of string:</p> <pre><code>"(this is (haha) a string(()and it's sneaky)) ipsom (lorem) bla" </code></pre> <p>and I want to extract substrings contained within a topmost layer of parentheses. I.e. I want to obtain the strings:<code>"this is (haha) a string(()and it's sneaky)"</c...
3
2016-07-05T20:02:29Z
38,212,049
<p>this isnt very "pythonic"...but </p> <pre><code>def find_strings_inside(what_open,what_close,s): stack = [] msg = [] for c in s: s1="" if c == what_open: stack.append(c) if len(stack) == 1: continue elif c == what_close and stack: s...
0
2016-07-05T20:20:53Z
[ "python", "string", "xml-parsing", "parentheses" ]
How to get an expression between balanced parentheses
38,211,773
<p>Suppose I am given the following kind of string:</p> <pre><code>"(this is (haha) a string(()and it's sneaky)) ipsom (lorem) bla" </code></pre> <p>and I want to extract substrings contained within a topmost layer of parentheses. I.e. I want to obtain the strings:<code>"this is (haha) a string(()and it's sneaky)"</c...
3
2016-07-05T20:02:29Z
38,212,061
<p>This is a standard use case for a stack: You read the string character-wise and whenever you encounter an opening parenthesis, you push the symbol to the stack; if you encounter a closing parenthesis, you pop the symbol from the stack.</p> <p>Since you only have a single type of parentheses, you don’t actually ne...
4
2016-07-05T20:21:20Z
[ "python", "string", "xml-parsing", "parentheses" ]
How to get an expression between balanced parentheses
38,211,773
<p>Suppose I am given the following kind of string:</p> <pre><code>"(this is (haha) a string(()and it's sneaky)) ipsom (lorem) bla" </code></pre> <p>and I want to extract substrings contained within a topmost layer of parentheses. I.e. I want to obtain the strings:<code>"this is (haha) a string(()and it's sneaky)"</c...
3
2016-07-05T20:02:29Z
38,212,660
<p>This more or less repeats what's already been said, but might be a bit easier to read:</p> <pre><code>def extract(string): flag = 0 result, accum = [], [] for c in string: if c == ')': flag -= 1 if flag: accum.append(c) if c == '(': flag += 1 ...
0
2016-07-05T21:01:11Z
[ "python", "string", "xml-parsing", "parentheses" ]
Not understanding output of MonthEnd() in pandas
38,211,814
<p>Say i have the following:</p> <pre><code>start = dt.datetime(2015,07,01) end = dt.datetime(2016,06,30) rng = pd.date_range(start, end,freq='M') print rng DatetimeIndex(['2015-07-31', '2015-08-31', '2015-09-30', '2015-10-31', '2015-11-30', '2015-12-31', '2016-01-31', '2016-02-29', '2016-03-3...
1
2016-07-05T20:05:06Z
38,211,963
<p>See the <a href="http://pandas.pydata.org/pandas-docs/stable/timeseries.html#anchored-offset-semantics" rel="nofollow">Anchored Offset Semantics</a> section of the documentation. </p> <p>Anchored offsets will snap to the <em>next</em> anchor point. If your date is within a month, <code>MonthBegin()</code> will sna...
2
2016-07-05T20:15:08Z
[ "python", "datetime", "pandas" ]
WindowsError: [Error 2] The system cannot find the file specified: 'tmp'
38,211,916
<pre><code>import os def create_temporary_directory(path, name): if not os.path.exists(os.path.join(path, name)): os.mkdir(os.path.join(path, name)) if __name__ == "__main__": name = 'tmp' create_temporary_directory('..', name) os.chdir(name) print os.getcwd() </code></pre> <p>when i tried t...
0
2016-07-05T20:11:58Z
38,212,012
<p><code>os.chrdir(name)</code> tries to reach <code>'./tmp'</code>, but you created your directory at <code>'../tmp'</code></p> <p>just update your code that way :</p> <pre><code>if __name__ == "__main__": name = 'tmp' create_temporary_directory('..', name) os.chdir(os.path.join('..',name)) </code></pre>...
0
2016-07-05T20:18:43Z
[ "python" ]
WindowsError: [Error 2] The system cannot find the file specified: 'tmp'
38,211,916
<pre><code>import os def create_temporary_directory(path, name): if not os.path.exists(os.path.join(path, name)): os.mkdir(os.path.join(path, name)) if __name__ == "__main__": name = 'tmp' create_temporary_directory('..', name) os.chdir(name) print os.getcwd() </code></pre> <p>when i tried t...
0
2016-07-05T20:11:58Z
38,212,101
<p>Here's how you can do this:</p> <pre><code>import os def create_temporary_directory(path, name): if not os.path.exists(os.path.join(path, name)): os.mkdir(os.path.join(path, name)) return os.path.join(path, name) if __name__ == "__main__": name = 'tmp' path = create_temporary_directory('....
0
2016-07-05T20:23:59Z
[ "python" ]
Python Ivona (Pyvona) script issue (local variable unbound)
38,212,019
<p>I'm using the pyvona package (from July 3rd 2016). I have all dependencies installed. It works correctly when I call it to speak for the first time. But if I run the command again, it gives me the local unbound error:</p> <pre><code>&gt;&gt;&gt; import pyvona &gt;&gt;&gt; v = pyvona.create_voice('&lt;key&gt;', '&lt...
0
2016-07-05T20:18:53Z
38,213,307
<p>Was able to find a workaround by adding:</p> <p>pygame.mixer.init()</p> <p>channel = pygame.mixer.Channel(5)</p> <p>immediately after defining the speak function:</p> <p>def speak(self, text_to_speak, use_cache=False):</p> <pre><code>def speak(self, text_to_speak, use_cache=False): """Speak a given text...
0
2016-07-05T21:45:49Z
[ "python", "text-to-speech", "ivona" ]
Python Ivona (Pyvona) script issue (local variable unbound)
38,212,019
<p>I'm using the pyvona package (from July 3rd 2016). I have all dependencies installed. It works correctly when I call it to speak for the first time. But if I run the command again, it gives me the local unbound error:</p> <pre><code>&gt;&gt;&gt; import pyvona &gt;&gt;&gt; v = pyvona.create_voice('&lt;key&gt;', '&lt...
0
2016-07-05T20:18:53Z
38,485,766
<p>Usually UnboundLocalError relates to Scopes and Namespaces in Python <a href="https://docs.python.org/3.3/tutorial/classes.html#python-scopes-and-namespaces" rel="nofollow">Scopes and NameSpaces</a> , but in Your case: In function speak() You create channel in code </p> <pre><code>if not pygame.mixer.get_init(): ...
0
2016-07-20T16:18:03Z
[ "python", "text-to-speech", "ivona" ]
How to write this Python for loop as a ternary operator
38,212,118
<p>I have the following code: </p> <pre><code>stuart = 0 kevin = 0 for itr, char in enumerate(word_list): if char in "aeiou": kevin += len(word_list) - itr else: stuart += len(word_list) - itr </code></pre> <p>Can I write the if/else statement as a ternary operator? </p> <p>I tried the fo...
1
2016-07-05T20:25:24Z
38,212,187
<p>Put your variables in a dictionary instead, and then you can vary the <em>key</em> you are assigning to:</p> <pre><code>names = {'stuart': 0, 'kevin': 0} for itr, char in enumerate(word_list): names['kevin' if char in "aeiou" else 'stuart'] += len(word_list) - itr </code></pre> <p>You can't otherwise use a con...
9
2016-07-05T20:29:30Z
[ "python", "python-3.x" ]
How to write this Python for loop as a ternary operator
38,212,118
<p>I have the following code: </p> <pre><code>stuart = 0 kevin = 0 for itr, char in enumerate(word_list): if char in "aeiou": kevin += len(word_list) - itr else: stuart += len(word_list) - itr </code></pre> <p>Can I write the if/else statement as a ternary operator? </p> <p>I tried the fo...
1
2016-07-05T20:25:24Z
38,212,460
<p>It is not possible to change the <em>variable</em> on left-hand side of assignment. However you can use the <code>globals()</code> trick to assign to a global variable, though this is frowned upon, thus never do this:</p> <p><s></p> <pre><code>stuart = 0 kevin = 0 globs = globals() for itr, char in enumerate(w...
4
2016-07-05T20:48:53Z
[ "python", "python-3.x" ]
How to write this Python for loop as a ternary operator
38,212,118
<p>I have the following code: </p> <pre><code>stuart = 0 kevin = 0 for itr, char in enumerate(word_list): if char in "aeiou": kevin += len(word_list) - itr else: stuart += len(word_list) - itr </code></pre> <p>Can I write the if/else statement as a ternary operator? </p> <p>I tried the fo...
1
2016-07-05T20:25:24Z
38,213,334
<pre><code> kevin, stuart = ( kevin + len(word_list) - itr, stuart ) if char in "aeiou" else ( kevin, stuart + len(word_list) - itr ) </code></pre>
0
2016-07-05T21:47:56Z
[ "python", "python-3.x" ]
tkinter Multiple Buttons Colour Change
38,212,206
<p>I'm using tkinter to create a 8x8 button matrix, which when the individual buttons are pressed add to a final list (eg finalList = ((0,0),(5,7),(6,6), ...), allowing me to quickly create 8x8 (x,y) co-ordinate images. I have created the window with the buttons but now have issues trying to reference these buttons in ...
1
2016-07-05T20:31:11Z
38,212,947
<p><code>self.xY</code> is set to <code>7,7</code> in your double for loop and never changed. If you want it to be different for each button, you may want to change <code>updateChange</code> to take two parameters (x,y), and pass them in as the command for the button using something like; <code>lambda x=matrixColumn y=...
0
2016-07-05T21:21:05Z
[ "python", "python-3.x", "button", "tkinter", "command" ]
tkinter Multiple Buttons Colour Change
38,212,206
<p>I'm using tkinter to create a 8x8 button matrix, which when the individual buttons are pressed add to a final list (eg finalList = ((0,0),(5,7),(6,6), ...), allowing me to quickly create 8x8 (x,y) co-ordinate images. I have created the window with the buttons but now have issues trying to reference these buttons in ...
1
2016-07-05T20:31:11Z
38,216,153
<p>Below are 2 examples, the first is if you just want to change the colour and nothing else then you can do it without using a list. The second involves using a list and demonstrates what Delioth has pointed out</p> <pre><code>class App(object): def __init__(self, master): self._master = master f...
1
2016-07-06T04:03:34Z
[ "python", "python-3.x", "button", "tkinter", "command" ]
xlrd reading a string as a float
38,212,210
<p>I have the following cell in excel which is a string:</p> <pre><code>72% </code></pre> <p>This is the name of a movie (<a href="http://www.imdb.com/title/tt3807620/" rel="nofollow">http://www.imdb.com/title/tt3807620/</a>). However, when I import it into xlrd, using:</p> <pre><code>wb = xlrd.open_workbook('/Users...
1
2016-07-05T20:31:16Z
38,212,373
<p>is it possible that when you wrote the cell in excel you didn't check the type of the cell? if yes the default type is <code>percentage</code> and it is probably converted to 0.72 you could try to write the value again and this time check that the cell type is <code>text</code></p> <p><strong>update:</strong> I che...
1
2016-07-05T20:42:14Z
[ "python", "excel", "xlrd" ]
Row is sum of 3 latest values
38,212,221
<pre><code>df = pd.DataFrame({'values':[2,6,1,5,8,9]}) </code></pre> <p>I'm trying to create a new rom called <code>sum</code> that is the sum of the 3 latest values. So it would return this <code>[np.nan, np.nan, 9, 12, 14, 22]</code></p>
3
2016-07-05T20:31:47Z
38,212,237
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.rolling.html" rel="nofollow"><code>rolling</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.window.Rolling.sum.html" rel="nofollow"><code>Rolling.sum</code></a>:</p> <pre><code>print (df.rol...
3
2016-07-05T20:33:23Z
[ "python", "pandas", "dataframe", "sum", "row" ]
Row is sum of 3 latest values
38,212,221
<pre><code>df = pd.DataFrame({'values':[2,6,1,5,8,9]}) </code></pre> <p>I'm trying to create a new rom called <code>sum</code> that is the sum of the 3 latest values. So it would return this <code>[np.nan, np.nan, 9, 12, 14, 22]</code></p>
3
2016-07-05T20:31:47Z
38,212,463
<p>With focus on performance, here's one approach using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.convolve.html" rel="nofollow"><code>NumPy's 1D convolution</code></a> -</p> <pre><code>np.append([np.nan]*2,np.convolve(df['values'],np.ones((3,)),'valid')) </code></pre>
1
2016-07-05T20:49:06Z
[ "python", "pandas", "dataframe", "sum", "row" ]
Python integer caching
38,212,252
<p>In the following python script, why the second assert goes through (i.e., when adding 0 to 257 and stores the result in y, then x and y become different objects)? Thanks!</p> <pre><code>x = 257 y = 257 assert x is y x = 257 y = 257 + 0 assert x is not y </code></pre>
4
2016-07-05T20:34:20Z
38,212,364
<p>When you use <code>is</code>, you are checking whether or not the two objects point to the same memory location. If they do, then the result is True. Otherwise, the result is False.</p> <p>To check if the values are equivalent, use <code>==</code>, e.g. <code>assert x == y</code>. Alternatively, to assert that th...
1
2016-07-05T20:41:30Z
[ "python", "caching" ]
Python integer caching
38,212,252
<p>In the following python script, why the second assert goes through (i.e., when adding 0 to 257 and stores the result in y, then x and y become different objects)? Thanks!</p> <pre><code>x = 257 y = 257 assert x is y x = 257 y = 257 + 0 assert x is not y </code></pre>
4
2016-07-05T20:34:20Z
38,212,365
<p>integers are non mutable so any operation to change them results in a new memory location</p> <pre><code>&gt;&gt;&gt; a =9876 &gt;&gt;&gt; id(a) 38478552 &gt;&gt;&gt; a+=1 &gt;&gt;&gt; id(a) 38478576 &gt;&gt;&gt; a+=0 &gt;&gt;&gt; id(a) 38478528 </code></pre> <p><code>is</code> is checking the actual memory locati...
1
2016-07-05T20:41:31Z
[ "python", "caching" ]
Implementing Pool on a for loop with a lot of inputs
38,212,265
<p>I have been trying to improve my code (with numba and multiprocessing), but I cannot quite get it, because my function has a lot of arguments. </p> <p>I have already simplified it with other functions (see below)...</p> <p>As each agent (a class instance) is independent of each other for these actions, I would lik...
1
2016-07-05T20:35:04Z
38,212,911
<p>Yes, there is a lot of parameters! Consider using a class.</p> <p>Well, since <code>Pool.map</code> support only one iterable argument, you need to group everything in one place. I suggest you to use the "Facade" pattern: an intermediate class used to store all required parameters and having a single method (I call...
1
2016-07-05T21:18:52Z
[ "python", "performance", "multiprocessing", "pool" ]
Django: Filter by calculated field
38,212,321
<p>In my Django project I need to calculate a date range for a trip to see if the trip is currently on its way.</p> <pre><code>class TourTemplate(models.Model): length= models.IntegerField() description = models.TextField(max_length=1000) ... class Trip(models.Model): tourtemplate= models.ForeignKey(TourTemplate) sta...
0
2016-07-05T20:38:17Z
38,219,113
<pre><code># First, define a manager subclass class TripManager(models.Manager): def get_queryset(self): length= self.tourtemplate.length start= self.start end=start+ timedelta(days=length) return super(TripManager, self).get_queryset().filter(date__range=[start, end]) class Trip(mo...
1
2016-07-06T08:07:54Z
[ "python", "django", "django-models", "django-views" ]
Django: Filter by calculated field
38,212,321
<p>In my Django project I need to calculate a date range for a trip to see if the trip is currently on its way.</p> <pre><code>class TourTemplate(models.Model): length= models.IntegerField() description = models.TextField(max_length=1000) ... class Trip(models.Model): tourtemplate= models.ForeignKey(TourTemplate) sta...
0
2016-07-05T20:38:17Z
38,279,816
<p>Couldn't figure out how to insert my calculated values into a queryset. My solution was adding another datefield for the end date (editable=False) and calculate and save the end date when creating a new trip:</p> <pre><code># Calculate end date on save def save(self, *args, **kwargs): self.end = self.start+ tim...
0
2016-07-09T08:13:35Z
[ "python", "django", "django-models", "django-views" ]
Webdriver find elements by regex in python
38,212,340
<p>I am trying to extract all those tags whose class name fits the regex pattern frag-0-0, frag-1-0, etc. from <a href="http://de.vroniplag.wikia.com/wiki/Aak/002" rel="nofollow">this link</a></p> <p>I am trying to retrieve it using the following code</p> <pre><code> driver = webdriver.Chrome(chromedriver) for...
0
2016-07-05T20:39:53Z
38,216,496
<p>The function <code>find_elements_by_id</code> <a href="http://selenium-python.readthedocs.io/api.html#selenium.webdriver.remote.webdriver.WebDriver.find_elements_by_id" rel="nofollow">takes a string as an object, not a regular expression</a>. I'm not sure if the function you're using can take regex, even as a string...
1
2016-07-06T04:51:30Z
[ "python", "regex", "selenium" ]
Webdriver find elements by regex in python
38,212,340
<p>I am trying to extract all those tags whose class name fits the regex pattern frag-0-0, frag-1-0, etc. from <a href="http://de.vroniplag.wikia.com/wiki/Aak/002" rel="nofollow">this link</a></p> <p>I am trying to retrieve it using the following code</p> <pre><code> driver = webdriver.Chrome(chromedriver) for...
0
2016-07-05T20:39:53Z
38,216,822
<p>The Selenium <code>find_elements_by_id</code> method expects a simple string but the output of <code>re.compile</code> is a regular expression object which can be used for matching using its <code>match()</code> and <code>search()</code> methods, described below:</p> <pre><code>reobject = re.compile(pattern) result...
1
2016-07-06T05:23:46Z
[ "python", "regex", "selenium" ]
Retrieving partial keys 'key for key in part...' - Networkx
38,212,352
<p>I'm attempting this tutorial: <a href="http://www.sociology-hacks.org/?p=67" rel="nofollow">"Networks on Maps (with Python)"</a>. With the kind help of the original author, I've got most of it working. It was originally created in Python 2.7, and I'm using 3.5. Changes include data in graphml format (not pickle), in...
1
2016-07-05T20:40:39Z
38,250,563
<p>The following code worked nearly completely. A couple of small issues remain, e.g. the map appears "above" the edges and nodes, 'deg_weight' not defined, but it mostly works. Will post if I get around to fixing fully. Posting here for anyone who's interested. Thanks to Dr. Raphael Heiberger for generous assistance.<...
0
2016-07-07T16:18:21Z
[ "python", "networkx", "matplotlib-basemap" ]
python tkinter draw capital alphabet fro dot matrix display
38,212,353
<p>How can I draw all alphabet in capital mode with python tkinter? Does using canvas polygon helpfull? something like this for <code>A</code>:</p> <pre><code>w = Canvas(master, width=canvas_width, height=canvas_height).pack() points = [100,0, 0, 100, 200,100] w.create_polygon(points, outline=python_green, fill='yello...
0
2016-07-05T20:40:46Z
38,381,387
<p>For the capital alphabet, you could use a very large font to write the capital letters (I don't see why you want to draw them):</p> <pre><code>from tkinter import Tk, Canvas master = Tk() canvas = Canvas(master, bg="white", width=200, height=200) canvas.pack() canvas.create_text(50,50, text="A", fill="red", font="...
1
2016-07-14T18:15:29Z
[ "python", "tkinter", "tkinter-canvas" ]
Java Process immediately exits
38,212,411
<p>I am creating a Process as follows: </p> <pre><code>Process p = Runtime.getRuntime().exec("nohup /usr/bin/python " + filePath + " &amp;"); Process q = Runtime.getRuntime().exec("/usr/bin/python -m -webbrowser " + url); </code></pre> <p>I am trying to run the <code>p</code> in the background so that <code>q</code> ...
0
2016-07-05T20:45:53Z
38,212,925
<p>Take a look at the documentation for the <code>&amp;</code> operator <a href="http://stackoverflow.com/questions/13338870/what-does-at-the-end-of-a-linux-command-mean">here</a>. Your process is running in the background. As far as the Java program you're writing (and the shell, for that matter) are concerned, the ca...
0
2016-07-05T21:19:54Z
[ "java", "python" ]
Java Process immediately exits
38,212,411
<p>I am creating a Process as follows: </p> <pre><code>Process p = Runtime.getRuntime().exec("nohup /usr/bin/python " + filePath + " &amp;"); Process q = Runtime.getRuntime().exec("/usr/bin/python -m -webbrowser " + url); </code></pre> <p>I am trying to run the <code>p</code> in the background so that <code>q</code> ...
0
2016-07-05T20:45:53Z
38,213,345
<p>As Sean Bright mentioned take the '&amp;' character out of the end of the script that you are running. Basically on all *nix systems. If you call make a type a command and use the ampersand, it will run that process in the background. That's why the call to java process is returning finished. </p> <p>It would p...
0
2016-07-05T21:48:37Z
[ "java", "python" ]
Java Process immediately exits
38,212,411
<p>I am creating a Process as follows: </p> <pre><code>Process p = Runtime.getRuntime().exec("nohup /usr/bin/python " + filePath + " &amp;"); Process q = Runtime.getRuntime().exec("/usr/bin/python -m -webbrowser " + url); </code></pre> <p>I am trying to run the <code>p</code> in the background so that <code>q</code> ...
0
2016-07-05T20:45:53Z
38,214,432
<p>The command you ran is <code>nohup</code>, and it did exit immediately. <code>nohup</code> <em>started</em> a separate Python process, but that's not the process <code>p</code> is controlling.</p> <p>Why are you using <code>nohup</code> and <code>&amp;</code> if that isn't the functionality you want? If you simply ...
1
2016-07-05T23:34:41Z
[ "java", "python" ]
Python unhexlify hex to alpha conversion failed
38,212,451
<p>So I'm using the code from <a href="http://stackoverflow.com/a/11132916/778694">this SO answer</a> to create a 2-way alphanumeric encryption function.</p> <p>Basically, the functions look like this: </p> <pre class="lang-py prettyprint-override"><code>from Crypto import Random from Crypto.Cipher import AES from b...
1
2016-07-05T20:48:32Z
38,295,368
<p>Okay so I made a few modifications to the file you posted...</p> <pre><code> from Crypto import Random from Crypto.Cipher import AES from binascii import hexlify, unhexlify import hashlib from sys import stdout as puts class AESCipher: def __init__(self, key): self.key = key def e...
1
2016-07-10T18:49:31Z
[ "python", "hex" ]
Is there a way to keep selenium webdriver objects from becoming stale when moving from page to page?
38,212,456
<p>I've run into an intractable problem trying to scrap an ajax filled site. After much struggle I've been able to automate my browser to download a single file off the site. Unfortunately, the task at hand requires me to leave the main page to get to the file. My problem is that after getting a list of the driver obje...
-2
2016-07-05T20:48:46Z
38,273,772
<p>I was able to get around this by using the map function to update the list:</p> <p><code>while loop: open_folders() #drFolder = driver.find_elements_by_xpath("//*[@data-rights='16777215']") drSurveys = driver.find_elements_by_xpath("//*[@data-rights='16711680']") elecontainer = drive...
0
2016-07-08T19:06:47Z
[ "python", "selenium" ]
get the href link after traversing through divs using selenium in python
38,212,473
<p>I am new to Selenium.. I am trying to get the href link which is present inside two div elements</p> <pre><code>&lt;div class="abc def"&gt; &lt;div class="foo xyz"&gt; &lt;a href="/watch123" &gt;&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>How do I get the href link? I have tried</p> ...
0
2016-07-05T20:49:56Z
38,213,207
<p>Try this: assuming your browser driver is called "driver" and all your elements' attributes are unique.</p> <ul> <li><p>Xpath: </p> <pre><code>element = driver.find_element_by_xpath("//div[@class='foo xyz']/a") link = element.get_attribute("href") </code></pre></li> <li><p>Css selector:</p> <pre><code>element = d...
1
2016-07-05T21:38:25Z
[ "python", "selenium" ]
Fastest way to search MySQL Text for multiple terms: MySQL vs Python
38,212,482
<p>I have a database with 700 million rows (each with a <code>TEXT</code> field) and 500+ search terms. What is the fastest way to find all rows that contain at least one search term and insert them into a new table?</p> <p>My first thought was to use the following </p> <pre><code>INSERT INTO my_new_table SELECT ...
-2
2016-07-05T20:50:40Z
38,212,593
<p>the search in 700 million rows in my opinion it is bad to retrieve all data and search after (your python solution) and it is bad do make a query with like search (your sql solution)</p> <p>a better solution based on mysql is to use full text search, <a href="http://dev.mysql.com/doc/refman/5.7/en/fulltext-search.h...
1
2016-07-05T20:57:20Z
[ "python", "mysql" ]
finding the minimum of two cells in different rows
38,212,484
<p>I have following data frame with columns <code>A</code> and <code>B</code>. Column <code>C</code> shall be the minimum value of A.shift(1), the preceding row, and B, the current row:</p> <pre><code> A B C Index 1 100 200 NaN 2 150 230 100 3 130 110 110 </code></pre> <p...
1
2016-07-05T20:50:44Z
38,212,633
<p>You can use <code>numpy.minimum()</code> to find out the minimum element of two Series in sequence:</p> <pre><code>import numpy as np df['C'] = np.minimum(df.A.shift(), df.B) df # A B C # Index # 1 100 200 NaN # 2 150 230 100.0 # 3 130 110 110.0 </code></pre>
5
2016-07-05T20:59:51Z
[ "python", "pandas" ]
Feature Importance with XGBClassifier
38,212,649
<p>Hopefully I'm reading this wrong but in the XGBoost library <a href="http://xgboost.readthedocs.io/en/latest/python/python_api.html#module-xgboost.sklearn" rel="nofollow">documentation</a>, there is note of extracting the feature importance attributes using <code>feature_importances_</code> much like sklearn's rando...
3
2016-07-05T21:00:30Z
38,227,721
<p>As the comments indicate, I suspect your issue is a versioning one. However if you do not want to/can't update, then the following function should work for you.</p> <pre><code>def get_xgb_imp(xgb, feat_names): from numpy import array imp_vals = xgb.booster().get_fscore() imp_dict = {feat_names[i]:float(...
4
2016-07-06T15:22:45Z
[ "python", "scikit-learn", "xgboost" ]
Feature Importance with XGBClassifier
38,212,649
<p>Hopefully I'm reading this wrong but in the XGBoost library <a href="http://xgboost.readthedocs.io/en/latest/python/python_api.html#module-xgboost.sklearn" rel="nofollow">documentation</a>, there is note of extracting the feature importance attributes using <code>feature_importances_</code> much like sklearn's rando...
3
2016-07-05T21:00:30Z
38,277,116
<p>I found out the answer. It appears that version <code>0.4a30</code> does not have <code>feature_importance_</code> attribute. Therefore if you install the xgboost package using <code>pip install xgboost</code> you will be unable to conduct feature extraction from the <code>XGBClassifier</code> object, you can refer ...
1
2016-07-09T00:32:54Z
[ "python", "scikit-learn", "xgboost" ]
Confirming equality of two pandas dataframes?
38,212,697
<p>How to assert that the following two dataframes <code>df1</code> and <code>df2</code> are equal?</p> <pre><code>import pandas as pd df1 = pd.DataFrame([1, 2, 3]) df2 = pd.DataFrame([1.0, 2, 3]) </code></pre> <p>The output of <code>df1.equals(df2)</code> is <code>False</code>. As of now, I know two ways:</p> <pre>...
3
2016-07-05T21:03:25Z
38,213,101
<p>Using <a href="http://stackoverflow.com/questions/38212697/confirming-equality-of-two-pandas-dataframes?noredirect=1#comment63849479_38212697">elegant @Divakar's idea</a> - numpy's <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.allclose.html" rel="nofollow">allclose()</a> will do the main trick f...
1
2016-07-05T21:30:44Z
[ "python", "pandas" ]
Confirming equality of two pandas dataframes?
38,212,697
<p>How to assert that the following two dataframes <code>df1</code> and <code>df2</code> are equal?</p> <pre><code>import pandas as pd df1 = pd.DataFrame([1, 2, 3]) df2 = pd.DataFrame([1.0, 2, 3]) </code></pre> <p>The output of <code>df1.equals(df2)</code> is <code>False</code>. As of now, I know two ways:</p> <pre>...
3
2016-07-05T21:03:25Z
38,213,972
<p>You can use <code>assert_frame_equal</code> and not check the dtype of the columns.</p> <pre><code>from pandas.util.testing import assert_frame_equal assert_frame_equal(df1, df2, check_dtype=False) </code></pre>
5
2016-07-05T22:40:20Z
[ "python", "pandas" ]
Python json print key from structure
38,212,824
<p>I have this structure</p> <pre><code>&gt; api.open_orders(url.api) [ # List of open orders { 'id': string, ## Order ID 'type': string, ## Order type - one of }, ... ] </code></pre> <p>I tried to print with print int(open_o['type']) but does no...
2
2016-07-05T21:12:51Z
38,212,924
<p>Try:</p> <pre><code>api.open_orders(url.api)[0]["type"] </code></pre> <p>The traceback tells you, that you have a list, where you index into with type, so the first dict is one level more deeply nested as element at index 0 of the list (the square brackets denote a list and also the index operator which is OK as w...
3
2016-07-05T21:19:54Z
[ "python", "json" ]
Daily calculation of time difference between two Pandas DF rows
38,212,850
<p>Please see my <a href="https://dl.dropboxusercontent.com/u/32282382/for_stack" rel="nofollow">for_stack</a> dataframe data which was saved via <code>for_stack.to_pickle('for_stack')</code></p> <p>As per following image I need to add a new column showing the amount of time between Timestamp (09:30) and 'Gap Lower Cl...
0
2016-07-05T21:14:56Z
38,213,020
<p>You can use the <code>pandas.TimeGrouper</code> (i couldn't find the documentation for it) and the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.first.html" rel="nofollow"><code>first</code> aggregate</a>.</p> <p>Example:</p> <pre><code>In [26]: df = pandas.DataFrame(in...
2
2016-07-05T21:25:48Z
[ "python", "pandas" ]
Daily calculation of time difference between two Pandas DF rows
38,212,850
<p>Please see my <a href="https://dl.dropboxusercontent.com/u/32282382/for_stack" rel="nofollow">for_stack</a> dataframe data which was saved via <code>for_stack.to_pickle('for_stack')</code></p> <p>As per following image I need to add a new column showing the amount of time between Timestamp (09:30) and 'Gap Lower Cl...
0
2016-07-05T21:14:56Z
38,213,157
<p>This I think does what you want:</p> <pre><code>import pandas as pd import numpy as np import datetime data = {'t1':[datetime.datetime(2014, 3, 10, 9, 30, 0), datetime.datetime(2014, 3, 10, 8, 33, 0)], 't2':[datetime.datetime(2014, 3, 11, 10, 34, 0), datetime.datetime(2014, 3...
1
2016-07-05T21:35:15Z
[ "python", "pandas" ]
How to get rrule.between() to only include start timestamp
38,213,018
<p>How would I create an rrule that excludes only the end timestamp using dateutil? Would I have to create a custom function or is there a way to do it natively?</p> <p>here is an example</p> <pre><code>rule = rrule.rrule(rule.HOURLY,tsstart=somedate,until=somedate_four_hours_later) </code></pre> <p>I want the outpu...
2
2016-07-05T21:25:33Z
38,213,650
<p>You can set the count:</p> <pre><code>In [1]: from dateutil import rrule In [2]: from datetime import datetime, timedelta In [3]: st = datetime(2016, 7, 5, 23, 30) In [4]: rule = rrule.rrule(rrule.HOURLY, st, count=4) In [5]: print(list(rule)) [datetime.datetime(2016, 7, 5, 23, 30), datetime.datetime(2016, 7, ...
1
2016-07-05T22:10:27Z
[ "python", "python-dateutil" ]
How to get rrule.between() to only include start timestamp
38,213,018
<p>How would I create an rrule that excludes only the end timestamp using dateutil? Would I have to create a custom function or is there a way to do it natively?</p> <p>here is an example</p> <pre><code>rule = rrule.rrule(rule.HOURLY,tsstart=somedate,until=somedate_four_hours_later) </code></pre> <p>I want the outpu...
2
2016-07-05T21:25:33Z
38,215,244
<p>One way to do this is to use an <a href="https://dateutil.readthedocs.io/en/stable/rrule.html#dateutil.rrule.rruleset" rel="nofollow"><code>rruleset</code></a>, which allows you to combine recurrence rules and specific dates as required. In this case, what you'd do is set the <code>until</code> date as an <code>exda...
2
2016-07-06T01:40:25Z
[ "python", "python-dateutil" ]
How to keep a session authenticated while crawling with scrapy?
38,213,025
<p>I have followed the response for this question (<a href="http://stackoverflow.com/questions/5851213/crawling-with-an-authenticated-session-in-scrapy">Crawling with an authenticated session in Scrapy</a>) to use scrapy with an authenticated session. The problem is that it seems to log in successfully, but when I make...
1
2016-07-05T21:26:02Z
38,234,353
<p>I found by enabling the cookies debugger <code>COOKIES_DEBUG = True</code> in the configuration file that the authentication was being done correctly. By messing with the configuration file, I managed to make the script work and crawl the site authenticated. For anyone with the same problem, I added<code>ROBOTSTXT_O...
0
2016-07-06T21:48:38Z
[ "python", "session", "scrapy", "web-crawler" ]
Using Pyinstaller with -noconsole gives Pop-ups instead
38,213,339
<p>I have python file, saved with .pyw to suppress console</p> <pre><code>import pyHook, pythoncom, sys, logging file_log = 'C:\\Lets_Create_Malware\\log.txt' def OnKeyboardEvent (event): logging.basicConfig(filename=file_log, level=logging.DEBUG, format='%(message)s') chr(event.Ascii) logging.log(10,chr...
0
2016-07-05T21:48:14Z
38,374,420
<p>Please create a .spec file and then add in the EXE section just </p> <blockquote> <p>debug=False</p> </blockquote> <p>The PyInstaller manual explains spec files <a href="https://pythonhosted.org/PyInstaller/spec-files.html" rel="nofollow">here</a>. Then call the pyinstaller with the spec file instead of the scri...
1
2016-07-14T12:37:46Z
[ "python", "console", "popup", "exe", "pyinstaller" ]
Why isn't method formatting Python dictionary key indenting?
38,213,367
<p>For some reason method formatting a dictionary key only begins to indent after specifying a width greater than 4. Any idea why? </p> <pre><code>for i in range(10): print({'{0:&gt;{1}}'.format('test',i):12}, "should be indented", i) </code></pre> <p>Output:</p> <pre><code>{'test': 12} should be indented 0 {'te...
-1
2016-07-05T21:50:09Z
38,213,494
<p>This has nothing to do with dict keys, nor is there anything special about the number 4; it just happens to be the length of your string <code>"test"</code>.</p> <p>With <a href="https://docs.python.org/3/library/string.html#formatstrings" rel="nofollow"><code>{0:&gt;{1}}</code></a> you say that that entire block s...
5
2016-07-05T21:58:57Z
[ "python" ]
Python Grouping attributes within a class
38,213,368
<p>Let's say that I have a class "shoppingCart". I add items to the shopping cart: eggs, milk, cheese, bread, toothbrush, bacon, dish soap, potato chips, and bottled water.</p> <pre><code>class shoppingCart(object): def __init__(self): self.eggs = 12 self.milk = 2 self.cheese = 1 se...
0
2016-07-05T21:50:12Z
38,213,480
<p>You shouldn't do that with only one class. I would create two clases. One would be a cart item, and the other one the shopping cart. For instance:</p> <pre><code>class cartItem(object): def __init__(self, amount=0): self.amount = amount self._is_beverage = False @property def is_beverag...
0
2016-07-05T21:57:59Z
[ "python" ]
No module named '...' python
38,213,405
<p>I have a directory called project set up like this:</p> <p><strong>Project</strong></p> <pre><code>--directory:src-- --directory:testscripts-- --directory:config_files-- RunPCS.py </code></pre> <p>and within src, it is set up as:</p> <p><strong>src</strong> </p> <pre><code>parse_files.py parse_json.py ...
0
2016-07-05T21:52:45Z
38,213,492
<p>for the import statement, use</p> <pre><code>from .src.parse_files import parse_files from .src.parse_json import parse_json </code></pre> <p>in your parse_json.py</p> <pre><code>from .process_xml import process_xml </code></pre>
1
2016-07-05T21:58:49Z
[ "python" ]
Should I use protocol or streams in asyncio?
38,213,409
<p>I'm very new to <code>asyncio</code> and was wondering which API is better than the other in terms of better practice, protocol or streams?</p> <p>To me, <code>protocol(callback based API)</code> seems easier to work with since there are already <code>connection_made</code> and <code>data_received</code> methods pr...
1
2016-07-05T21:52:57Z
38,223,622
<p>The <a href="https://docs.python.org/3/library/asyncio-stream.html#streams-coroutine-based-api" rel="nofollow">stream objects</a> are higher level and provide many useful methods:</p> <ul> <li>Several ways to read data: <a href="https://docs.python.org/3/library/asyncio-stream.html#asyncio.StreamReader.read" rel="n...
1
2016-07-06T12:07:59Z
[ "python", "python-3.x", "coroutine", "python-asyncio" ]
Convert a series of numbers into a string in Python
38,213,425
<p>If I use raw_input, how can I convert a series of numbers such as 24, 45, 60 (It's important to note that the amount of numbers will be different each time) into ONE string?</p>
-1
2016-07-05T21:54:42Z
38,213,568
<p>The question is a bit vague. This takes a list as input and forces into a single string separated by spaces.</p> <pre><code>raw_input = [24, 45, 60] mystr = ' '.join(raw_input) print mystr #24 45 60 </code></pre>
0
2016-07-05T22:03:39Z
[ "python" ]
Convert a series of numbers into a string in Python
38,213,425
<p>If I use raw_input, how can I convert a series of numbers such as 24, 45, 60 (It's important to note that the amount of numbers will be different each time) into ONE string?</p>
-1
2016-07-05T21:54:42Z
38,213,592
<p>The problem is not clearly stated. If you want to concatenate several numbers into one string like:</p> <p>input: 24, 45, 60</p> <p>output: "244560"</p> <p>The following code will meet your requirements.</p> <pre><code>def list2string(input): return "".join([str(n) for n in input]) &gt;&gt;&gt; list2string(...
0
2016-07-05T22:05:55Z
[ "python" ]
How to stop autocomplete and have normal tab with GNU readline library in Python
38,213,429
<p>Right now, I'm running the following code in Python 2.7:</p> <pre><code>import readline as rl rl.parse_and_bind('set editing-mode vi') #allow for arrow keys to be used rl.set_completer() raw_input() </code></pre> <p>According to <a href="https://docs.python.org/2/library/readline.html" rel="nofollow">this</a>, <co...
0
2016-07-05T21:54:55Z
38,276,066
<p>You can use</p> <pre><code>#allow for arrow keys to be used for raw_input. readline.parse_and_bind('set editing-mode vi') #set the tab key to make 4 spaces readline.parse_and_bind("TAB: ' '") </code></pre> <p>For some reason, using <code>readline.parse_and_bind("TAB: '\t'")</code> caused Python to use way too...
0
2016-07-08T22:09:45Z
[ "python", "python-2.7", "libreadline" ]
Compare multiple items in a list at once?
38,213,433
<p>I need to select multiple items from a list and see if they are all the same or not. Something like this:</p> <pre><code> if list1[:3] == 'x': Do Something.... </code></pre> <p>So I need to know if items 0-3 in the list equal the character 'x'. I'm just not sure how to do this.</p>
0
2016-07-05T21:55:08Z
38,213,530
<p>One way to do it at once may be:</p> <pre><code>if list[:3] == 3*['x']: # DO something </code></pre> <p>Hope this helps.</p>
4
2016-07-05T22:01:08Z
[ "python", "python-3.x" ]
Compare multiple items in a list at once?
38,213,433
<p>I need to select multiple items from a list and see if they are all the same or not. Something like this:</p> <pre><code> if list1[:3] == 'x': Do Something.... </code></pre> <p>So I need to know if items 0-3 in the list equal the character 'x'. I'm just not sure how to do this.</p>
0
2016-07-05T21:55:08Z
38,213,618
<p>Use something like this:</p> <pre><code>subArr = list1[:3] if len([i for i in subArr if i == 'x']) == len(subArr): #OK </code></pre>
0
2016-07-05T22:07:57Z
[ "python", "python-3.x" ]
Compare multiple items in a list at once?
38,213,433
<p>I need to select multiple items from a list and see if they are all the same or not. Something like this:</p> <pre><code> if list1[:3] == 'x': Do Something.... </code></pre> <p>So I need to know if items 0-3 in the list equal the character 'x'. I'm just not sure how to do this.</p>
0
2016-07-05T21:55:08Z
38,213,678
<p>The most readable/efficient way seems to be:</p> <pre><code> if all(v == 'x' for v in list[:3]): # do something </code></pre>
1
2016-07-05T22:12:30Z
[ "python", "python-3.x" ]
Compare multiple items in a list at once?
38,213,433
<p>I need to select multiple items from a list and see if they are all the same or not. Something like this:</p> <pre><code> if list1[:3] == 'x': Do Something.... </code></pre> <p>So I need to know if items 0-3 in the list equal the character 'x'. I'm just not sure how to do this.</p>
0
2016-07-05T21:55:08Z
38,213,688
<p>You can also do:</p> <pre><code>if {x} == set(list1[:3]): #do something </code></pre>
0
2016-07-05T22:13:12Z
[ "python", "python-3.x" ]
Creating Users & Sending Password Resets in Django
38,213,486
<p>I apologize if there has been a substantial answer on this already, I have searched for quite a while and can't find any helpful answers.</p> <p>I have a django project that has varying levels of account access. I have a group of 'Managers' and I want to allow them to manage user accounts.</p> <p>I want the Manage...
0
2016-07-05T21:58:19Z
38,215,960
<p>Glancing at the <a href="https://github.com/django/django/blob/1.6.11/django/contrib/auth/forms.py#L236" rel="nofollow">source code</a>, it looks like Django is ignoring the request because the password is blank.</p> <p>Try setting a temporary password (using, say, <code>django.utils.crypto.get_random_string()</cod...
1
2016-07-06T03:33:38Z
[ "python", "django", "django-1.6" ]
Can a dictionary value correspond/be assigned to a function?
38,213,487
<p>I have researched on the internet, and I can't find a clear answer to my question. Can a dictionary value be assigned to a local function? For example:</p> <pre><code>def add(x, y): sum = x + y return sum dictionary = {'add' : add} # Will this value represent the add function? </code></pre> <p>Any suggest...
-3
2016-07-05T21:58:21Z
38,213,528
<p>Yes, the code you posted is correct. To call the function:</p> <pre><code>dictionary['add'](1, 2) </code></pre>
2
2016-07-05T22:01:07Z
[ "python", "dictionary" ]
Python program not running as expected
38,213,595
<p>When I run it, nothing happens, but it doesn't throw any errors, what it should do is prompt the user for the alum numbers to pull from the db, then move these albums from the db to a portable device. Any ideas why it is not running???</p> <pre><code> #!/usr/bin/python import sqlite3 import os import shutil get_...
-2
2016-07-05T22:06:16Z
38,213,893
<p>Two things:</p> <ol> <li>Process albums is a function, so to call it, you need the parentheses. Replace process_albums by process_albums().</li> <li>You have used dbname is process_albums(). You cannot use this, as it is only defined in the scope of the makedatabasename() method. You could either use dbname as a gl...
0
2016-07-05T22:32:10Z
[ "python", "linux", "sqlite3" ]
Get a section of an image, and then the center of that square, without any external libraries?
38,213,607
<p>I'm working on a project that requires me to extract a face:</p> <p><a href="http://i.stack.imgur.com/wTt9Q.png" rel="nofollow"><img src="http://i.stack.imgur.com/wTt9Q.png" alt="enter image description here"></a></p> <p>And I've done so, with dlib. The next step is to extract the keypoints from that region and st...
1
2016-07-05T22:07:13Z
38,239,850
<p>If you can't use numpy slicing, you should fix your code:</p> <p>here is your main error:</p> <pre><code>x = ((a+d)/2) y = ((b+c)/2) </code></pre> <p>that is equal to:</p> <pre><code>x = ((left+bottom)/2) y = ((top+right)/2) </code></pre> <p>one more error is re-declaring variable 'd' that what initially 'detec...
1
2016-07-07T07:31:51Z
[ "python", "opencv", "geometry", "standard-library", "dlib" ]
get points inside boxplot
38,213,610
<p>I am creating a boxplot with matplotlib. How can I get the points inside the box ?</p> <pre><code>import matplotlib.pyplot as plt data = [2,4,5,62,57,3,8,3,96,2,34,43] box=plt.boxplot(data) </code></pre>
0
2016-07-05T22:07:16Z
38,218,168
<p>The <em>points inside the box</em> are the values that lie inside the interquartile range. The 1st and 3rd quartiles can be calculated with <code>np.quartile</code>, and once you know those values you can conditionally sample your data array:</p> <pre><code>import matplotlib.pyplot as plt import numpy as np data =...
0
2016-07-06T07:11:51Z
[ "python", "matplotlib" ]
How do you nest in Django Templates?
38,213,630
<p>I am trying to Migrate a PHP based website into Python with Django as a framework.</p> <p>However I'm having real issues with the template. I can't seem to get my head around how they work in terms of structure.</p> <p>By this I am referring "nesting", using different pages to build a template as done in PHP. Take...
-2
2016-07-05T22:09:10Z
38,213,664
<p>Django has an <a href="https://docs.djangoproject.com/en/1.9/ref/templates/builtins/#include" rel="nofollow"><code>include</code></a> template tag that allows you load other templates (like header and footer) in your current template and render them with the <code>context</code>:</p> <pre><code>{% include "header.h...
0
2016-07-05T22:11:41Z
[ "php", "python", "html", "django" ]
Optimizing Array Element Shifting in Python / Numpy
38,213,662
<p><strong>Problem:</strong></p> <p>After running a line profiling of a data analysis code I have written, I have found that around 70% of the total run time is concentrated in calls to two different array manipulation routines. I would eventually like to analyze data in a real-time fashion, so any optimization here w...
7
2016-07-05T22:11:35Z
38,213,983
<p>Let <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html"><code>NumPy broadcasting</code></a> help you out for a vectorized solution!</p> <pre><code># Store shape of input array s = Trace.shape # Store arrays corresponding to row and column indices I = np.arange(s[0]) J = np.arange(s[1]-1,-1,-1) ...
5
2016-07-05T22:41:25Z
[ "python", "arrays", "numpy", "optimization", "matrix" ]
Running selenium in c9
38,213,684
<p>I am trying to run a python code that uses selenium module. This code ran perfectly with the use of a chromedriver in my PC. I am trying to run it in c9.io. I downloaded the chromedriver 64 bit version and gave permissions as 777 using chmod. Still I can't get it to work</p> <p>However, I get the following error:</...
1
2016-07-05T22:12:55Z
38,235,898
<p>I had the same issue but it was with the 32 bit version. Fixed it using the 64 bit version.</p>
0
2016-07-07T00:28:17Z
[ "python", "selenium", "c9.io" ]
Change git hook credentials in Windows
38,213,691
<p>I am running in Windows and have a git post-receive hook that calls a python 3 script. This Python script does a number of things. One of these is to output the username running the git hook. This username is MACHINENAME$ (where the machine name is MACHINENAME), which I think is the Network Service account, but I co...
1
2016-07-05T22:13:27Z
38,217,644
<p>Since a git hook executes itself in a git bash, check if that affect how the parameters are passed to the windows executable <code>clearfsimport</code> (especially the path)</p> <p>One simple test: wrap your <code>clearfsimport</code> call in a <code>.bat</code> script, and set the source and destination path in th...
0
2016-07-06T06:38:29Z
[ "python", "windows", "git", "clearcase" ]
Can't save image to django model
38,213,767
<p>I try to resize image before save:</p> <pre><code>from PIL import Image class UserAvatarUpdate(views.APIView): serializer_class = UserSerializer def patch(self, *args, **kwargs): instance = ExtUser.objects.get(id=self.request.user.id) instance.avatar = self.request.FILES['file'] ...
1
2016-07-05T22:19:52Z
38,213,877
<p>You can't directly assign a PIL image to an <code>ImageField</code> like so. You need a little workaround:</p> <pre><code>from io import BytesIO from django.core.files.base import ContentFile image = Image.open(filename) image = image.resize(size,Image.ANTIALIAS) image_io = BytesIO() image.save(image_io, format='...
1
2016-07-05T22:30:27Z
[ "python", "django", "python-3.x", "django-models", "pillow" ]
Best way to distribute big, complex Python projects so that they fully install for other users, regardless of operating system?
38,213,861
<p>How to ensure that distributing Python packages with big dependencies, like NumPy and SciPy, automatically get properly installed on users' computers, regardless of their OS?</p> <p>The problem is that many such packages are installed with more or less ease through the main channel of <code>pip</code>, including th...
4
2016-07-05T22:29:03Z
38,213,862
<p>I don't claim this is perfect, but below is what I've found in practice to be really strong: an <code>install.sh</code> script, derived here originally for an artificial intelligence library called <a href="https://github.com/overlap-ai/words2map" rel="nofollow">words2map</a>. The goal was to make sure that users ca...
4
2016-07-05T22:29:03Z
[ "python", "operating-system", "pip", "conda" ]
Best way to distribute big, complex Python projects so that they fully install for other users, regardless of operating system?
38,213,861
<p>How to ensure that distributing Python packages with big dependencies, like NumPy and SciPy, automatically get properly installed on users' computers, regardless of their OS?</p> <p>The problem is that many such packages are installed with more or less ease through the main channel of <code>pip</code>, including th...
4
2016-07-05T22:29:03Z
38,214,381
<p>The problem with legel's suggestion is that you still end up relying on user's environment to deploy your application. </p> <p>In the past I have had similar install scripts which would do all the dirty work to deploy my application, but it still relies on network connectivity to download packages and dependencies....
0
2016-07-05T23:28:46Z
[ "python", "operating-system", "pip", "conda" ]
Renaming files with a pattern
38,213,911
<p>Python beginner here. </p> <p>I have a directory with hundreds of image files named as (in sequence):</p> <p><strong>002_IMG_001, 002_IMG_002, 002_IMG_003, 002_IMG_N</strong> </p> <p>Now, I am trying to rename those images such that the five files in a row have 'N' from 1:5, that is, every consecutive set of five...
0
2016-07-05T22:33:52Z
38,214,347
<p>I think this should work:</p> <pre><code>my_list = ["002_IMG_001", "002_IMG_002", "002_IMG_003", "002_IMG_004", "002_IMG_005", "002_IMG_006", "002_IMG_007", "002_IMG_008", "002_IMG_009", "002_IMG_0010", "002_IMG_011", "002_IMG_012", "002_IMG_013", "002_IMG_014", "002_IMG_015", "002_IMG_016", "0...
0
2016-07-05T23:26:04Z
[ "python", "file-io", "file-rename" ]
Python: cannot import scipy.io even if scipy is installed
38,213,937
<p>I just want to import wavfile from scipy.io.</p> <pre><code>import scipy # this works import scipy.io # this does NOT work from scipy.io import wavfile # does NOT work </code></pre> <p>Yes, I've reinstalled python like 4 times. Yes, I also tried multiple times to install via Anaconda. ...
2
2016-07-05T22:36:25Z
38,233,413
<p>Your scipy install is broken. It should work.</p> <pre><code>In [1]: from scipy.io import wavfile In [2]: wavfile? Type: module String form: &lt;module 'scipy.io.wavfile' from '/home/br/repos/scipy/build/testenv/lib/python2.7/site-packages/scipy/io/wavfile.pyc'&gt; File: /home/br/repos/scipy/build/te...
0
2016-07-06T20:41:06Z
[ "python", "numpy", "matplotlib", "scipy", "anaconda" ]
"System resource exceeded" Error from ODBC MS Access Driver when executing a SELECT query in pyodbc
38,213,938
<p>I have written a python program that uses pyodbc to interact with a Microsoft Access database. The database contains a table with measurements of wells (about 6.3 million).</p> <p>The program's basic work flow is to get a list of chemicals. Then for every chemical it will use a select query to find every well in th...
1
2016-07-05T22:36:26Z
38,278,521
<p>Unfortunately, MS Access' <em>System Resources Exceeded</em> is a somewhat ambiguous message which can pertain to actual CPU resources, network environment, or an inefficient SQL query or VBA module that impairs the engine's performance.</p> <p>However, your SQL can be optimized. Consider replacing the <code>DISTIN...
1
2016-07-09T04:59:25Z
[ "python", "sql", "ms-access", "pyodbc" ]
Mask an array by the index given from other array
38,214,032
<p>I have the following arrays:</p> <pre><code>a = [10, 31, 30, 11, 17, 12, 22, 25, 85, 17, 21, 43] b = [0, 1, 4, 6] </code></pre> <p>I want to mask <code>a</code> based on the index given by array <code>b</code>. That means getting:</p> <pre><code>c = [True, True, False, False, True, False, True, False, False, Fals...
3
2016-07-05T22:47:48Z
38,214,077
<pre><code>res = [False] * len(a) for idx in b: res[idx] = True </code></pre> <p>or</p> <pre><code>[idx in b for idx in range(len(a))] </code></pre>
1
2016-07-05T22:54:14Z
[ "python", "arrays", "numpy", "mask" ]
Mask an array by the index given from other array
38,214,032
<p>I have the following arrays:</p> <pre><code>a = [10, 31, 30, 11, 17, 12, 22, 25, 85, 17, 21, 43] b = [0, 1, 4, 6] </code></pre> <p>I want to mask <code>a</code> based on the index given by array <code>b</code>. That means getting:</p> <pre><code>c = [True, True, False, False, True, False, True, False, False, Fals...
3
2016-07-05T22:47:48Z
38,214,081
<p>Use <code>np.in1d</code> on a new array created with <code>np.arange</code> from the length of <code>a</code>:</p> <pre><code>&gt;&gt;&gt; a = [10, 31, 30, 11, 17, 12, 22, 25, 85, 17, 21, 43] &gt;&gt;&gt; b = [0, 1, 4, 6] &gt;&gt;&gt; a = np.array(a) &gt;&gt;&gt; b = np.array(b) &gt;&gt;&gt; np.in1d(np.arange(len(a...
1
2016-07-05T22:54:39Z
[ "python", "arrays", "numpy", "mask" ]
Mask an array by the index given from other array
38,214,032
<p>I have the following arrays:</p> <pre><code>a = [10, 31, 30, 11, 17, 12, 22, 25, 85, 17, 21, 43] b = [0, 1, 4, 6] </code></pre> <p>I want to mask <code>a</code> based on the index given by array <code>b</code>. That means getting:</p> <pre><code>c = [True, True, False, False, True, False, True, False, False, Fals...
3
2016-07-05T22:47:48Z
38,214,123
<p>It will be something like this:</p> <pre><code>c = [] for i, v in enumerate(a): mask = True if i in b else False c.append(mask) </code></pre>
2
2016-07-05T22:58:02Z
[ "python", "arrays", "numpy", "mask" ]
Mask an array by the index given from other array
38,214,032
<p>I have the following arrays:</p> <pre><code>a = [10, 31, 30, 11, 17, 12, 22, 25, 85, 17, 21, 43] b = [0, 1, 4, 6] </code></pre> <p>I want to mask <code>a</code> based on the index given by array <code>b</code>. That means getting:</p> <pre><code>c = [True, True, False, False, True, False, True, False, False, Fals...
3
2016-07-05T22:47:48Z
38,215,429
<pre><code>In [524]: a=np.array([10, 31, 30, 11, 17, 12, 22, 25, 85, 17, 21, 43]) In [525]: b=np.array([0, 1, 4, 6]) </code></pre> <p>To make a boolean <code>c</code> that is True at the <code>b</code> indices, just use:</p> <pre><code>In [526]: c=np.zeros(a.shape, bool) In [527]: c[b]=True In [528]: c Out[528]: ar...
2
2016-07-06T02:09:29Z
[ "python", "arrays", "numpy", "mask" ]
Bacnet device not identifying pointName
38,214,065
<p>So Below are my configurations for volttron. I have a bacnet compatible VAV attached on which I generated config csv using grab_bacnet. The problem is that the bacnet proxy and as well as scrape all method in bacnet driver is unable to get anything from the device.</p> <p>This is also to note that there is no error...
0
2016-07-05T22:51:56Z
38,214,843
<p>It looks like there is two problems here.</p> <p>First it looks like the device is simply not responding. This can be due to a configuration issue test_bacnet1.config. </p> <p>What was the command line you used to grab the configuration in the first place?</p> <p>Second is that there appears to be a mismatch betw...
1
2016-07-06T00:34:58Z
[ "python", "bacnet", "volttron" ]
Bacnet device not identifying pointName
38,214,065
<p>So Below are my configurations for volttron. I have a bacnet compatible VAV attached on which I generated config csv using grab_bacnet. The problem is that the bacnet proxy and as well as scrape all method in bacnet driver is unable to get anything from the device.</p> <p>This is also to note that there is no error...
0
2016-07-05T22:51:56Z
38,231,543
<p>Thanks Kyle. Our hardware configuration uses a BACnet router (ID 570009) and a VAV controller (ID 990037). With grab config, we've got to have both register points files, with the designated Volttron Point Names. </p> <p>These are the grab_config out-test columns for the VAV controller csv file (As Priyank mention...
0
2016-07-06T18:45:46Z
[ "python", "bacnet", "volttron" ]
python JSON to dict check if single or multiple children
38,214,224
<p>I am using python2.7 and receive dynamically a JSON string that I need to parse. </p> <p>The resulting dict looks as follows"</p> <p><code>{ u'queueId': u'channel.presence' u'name': u'presence.message' u'timestamp': 1467756404358 u'webhookId': u'U3P3Xw' u'serial': u'e7da73f9...
0
2016-07-05T23:10:29Z
38,214,248
<p>You can use <a href="https://docs.python.org/2/library/functions.html#isinstance" rel="nofollow"><code>isinstance()</code></a> to determine if the item is a list or not:</p> <pre><code>presence = ji['data']['presence'] if isinstance(presence, list): # ... </code></pre> <p>Though, if I understand you correctly,...
1
2016-07-05T23:13:17Z
[ "python", "json", "dictionary" ]
How is the following code in Python in C#?
38,214,296
<p>How is the following code in Python in C#?</p> <p>I need to get the hash generated by this code to send to <a href="http://en.thesubdb.com/api/" rel="nofollow">http://en.thesubdb.com/api/</a> to get a subititle, but my code is in C #.</p> <pre><code>def get_hash(name): readsize = 64 * 1024 with open(name, ...
-4
2016-07-05T23:19:32Z
38,215,426
<pre><code>public static string GetHash( string caminho ) { const int bytesToRead = 64 * 1024; byte[] buffer = new byte[bytesToRead * 2]; MD5 md5 = new MD5CryptoServiceProvider( ); using( var md52 = MD5.Create( ) ) { using( var stream = new FileStream( caminho, FileMode.Open,...
0
2016-07-06T02:09:21Z
[ "c#", "python", "hash" ]
How do I parse (potentially unknown) key/value pairs from a list of strings with default values?
38,214,322
<p>I have a string column in a Pandas DataFrame that contains database settings and I want to turn the key/value pairs into new columns in the DataFrame, filling in any missing values with <code>True</code>.</p> <p>Here's what one of the strings looks like:</p> <pre><code>Status=ONLINE, Updateability=READ_WRITE, User...
3
2016-07-05T23:22:25Z
38,214,387
<p>You could simplify using <em>str.partition</em>,no need for any regex, just split the string :</p> <pre><code>s = "Status=ONLINE, Updateability=READ_WRITE, UserAccess=MULTI_USER, Recovery=SIMPLE, Version=706, Collation=SQL_Latin1_General_CP1_CI_AS, SQLSortOrder=52, IsAutoCreateStatistics, IsAutoUpdateStatistics, I...
5
2016-07-05T23:29:40Z
[ "python" ]
How do I parse (potentially unknown) key/value pairs from a list of strings with default values?
38,214,322
<p>I have a string column in a Pandas DataFrame that contains database settings and I want to turn the key/value pairs into new columns in the DataFrame, filling in any missing values with <code>True</code>.</p> <p>Here's what one of the strings looks like:</p> <pre><code>Status=ONLINE, Updateability=READ_WRITE, User...
3
2016-07-05T23:22:25Z
38,214,443
<p>If you know that is how the string will be, you can do the following:</p> <pre><code>your_string = 'Status=ONLINE, Updateability=READ_WRITE, ThisValueWillBeTrue' your_list = your_string.split(sep=', ') your_dict = {i.split(sep='=')[0] : i.split(sep='=')[1] if len(i.split(sep='=')) &gt; 1 else True for i in your_lis...
-2
2016-07-05T23:36:24Z
[ "python" ]
How do I parse (potentially unknown) key/value pairs from a list of strings with default values?
38,214,322
<p>I have a string column in a Pandas DataFrame that contains database settings and I want to turn the key/value pairs into new columns in the DataFrame, filling in any missing values with <code>True</code>.</p> <p>Here's what one of the strings looks like:</p> <pre><code>Status=ONLINE, Updateability=READ_WRITE, User...
3
2016-07-05T23:22:25Z
38,214,719
<p>Building up on Padraic Cunninghams Answer I came up with this solution. Depending on the formatting constraints of the input, this solution with a regex can be more or less robust than the split/strip solution.</p> <pre><code>import pandas import re def repl(s): for sub in re.findall('[\w=]+', s): k, _...
1
2016-07-06T00:13:25Z
[ "python" ]
Comparing value with neighbor elements in numpy
38,214,416
<p>Let's say I have a numpy array</p> <pre><code> a b c A = i j k u v w </code></pre> <p>I want to compare the value central element with some of its eight neighbor elements (along the axis or along the diagonal). Is there any faster way except the nested for loop (it's too slow for big matrix)?</p> <p>To be ...
2
2016-07-05T23:32:56Z
38,214,996
<p>I used numpy's:</p> <ul> <li><code>concatenate</code> to pad with zeroes</li> <li><code>dstack</code> and <code>roll</code> to align correctly</li> </ul> <p>Apply <code>custom_roll</code> twice along different dimensions and subtract original.</p> <pre><code>import numpy as np def custom_roll(a, axis=0): n =...
1
2016-07-06T01:00:27Z
[ "python", "numpy", "scipy" ]
Comparing value with neighbor elements in numpy
38,214,416
<p>Let's say I have a numpy array</p> <pre><code> a b c A = i j k u v w </code></pre> <p>I want to compare the value central element with some of its eight neighbor elements (along the axis or along the diagonal). Is there any faster way except the nested for loop (it's too slow for big matrix)?</p> <p>To be ...
2
2016-07-05T23:32:56Z
38,237,277
<p>Your operation contains lots of conditionals, so the most efficient way to do it in the general case (any kind of conditionals, any kind of operations) is using loops. This could be done efficiently using numba or cython. In special cases, you can implement it using higher level functions in numpy/scipy. I'll show a...
0
2016-07-07T03:50:16Z
[ "python", "numpy", "scipy" ]
load Python Pickle (.pkl) file
38,214,420
<p>I am trying to load .pkl files that are in the same directory where my .py file is located. The following is my code: </p> <pre><code>import os def load_var(var_name): fid = open(os.path.join((var_name, '.pkl'))) data = pickle.load(fid) fid.close() return data def main(): data = load_var('myfi...
0
2016-07-05T23:33:41Z
38,214,472
<p>The input to <code>os.path.join</code> should not be a tuple. That is, the command should read:</p> <pre><code>fid = open(os.path.join(var_name, '.pkl')) </code></pre>
0
2016-07-05T23:39:23Z
[ "python", "file", "pickle" ]
load Python Pickle (.pkl) file
38,214,420
<p>I am trying to load .pkl files that are in the same directory where my .py file is located. The following is my code: </p> <pre><code>import os def load_var(var_name): fid = open(os.path.join((var_name, '.pkl'))) data = pickle.load(fid) fid.close() return data def main(): data = load_var('myfi...
0
2016-07-05T23:33:41Z
38,214,499
<p>c. leather is correct. Remove the extra brackets (). Also note that you are using os.path.join() on what seems to be filename and extension? </p> <p>The output of that would be var_name/.pkl, not sure if that is what you are expecting.</p> <pre><code>&gt;&gt;&gt; filename = "mytestfile" &gt;&gt;&gt; mypath = os.pa...
0
2016-07-05T23:43:00Z
[ "python", "file", "pickle" ]
SQLAlchemy counting all rows, I want specific rows
38,214,446
<p>In words, I'm trying to achieve this goal:</p> <p>"Get 5 comments where comment.post_id == self.context.id and sort those by the highest number of Comment_Vote.vote_type == 'like' "</p> <p>Currently the models are:</p> <pre><code>vote_enum = ENUM('like', 'dislike', name='vote_enum', create_type=False) class User...
1
2016-07-05T23:37:03Z
38,224,807
<p>This could be a nice place to use a <a href="https://www.postgresql.org/docs/9.3/static/queries-table-expressions.html#QUERIES-LATERAL" rel="nofollow">lateral subquery</a>. It is the "foreach" of SQL, which is to say that a lateral subquery can reference columns of preceding FROM items. Postgresql supports lateral f...
2
2016-07-06T13:06:16Z
[ "python", "postgresql", "sqlalchemy" ]
Calculate z_score for a column grouped by another column
38,214,459
<p>Suppose I have a DataFrame with columns <code>person_id</code> and <code>mean_act</code>, where every row is a numerical value for a specific person. I want to calculate the zscore for all the values at a person level. That is, I want a new column <code>mean_act_person_zscore</code> that is computed as the zscore of...
2
2016-07-05T23:37:41Z
38,214,615
<p>Should be straight forward:</p> <pre><code>df['mean_act_person_zscore'] = df.groupby('person_id').mean_act.transform(lambda x: (x - x.mean()) / x.std()) </code></pre>
2
2016-07-05T23:57:53Z
[ "python", "numpy", "pandas", "scipy", "statistics" ]
How to mock the return value of class method imported from another class in Python?
38,214,515
<p>I have these files:</p> <pre><code>/foo.py /foo2.py /test_food.py </code></pre> <p>in foo.py, I have this:</p> <pre><code>from foo2 import Foo2 class Foo(object): def GetFoo2(self): f = Foo2() return f.Get() </code></pre> <p>and in foo2.py, I have:</p> <pre><code>class Foo2(object): ...
1
2016-07-05T23:45:05Z
38,214,757
<p>Whenever you import using <code>from</code>, you can patch that module's namespace. Here is an example for your <code>test_foo_ok</code> function:</p> <pre><code>import os, sys, json, pytest from mock import * from foo import Foo def test_foo_ok(monkeypatch): monkeypatch.setattr("foo.Foo2.Get", lambda x:"abc")...
0
2016-07-06T00:18:59Z
[ "python", "mocking", "py.test", "monkeypatching" ]
Can't get Python class code to work
38,214,520
<p>I'm new to Python. Anyway, I was trying to make a 21 questions game, but my code won't work.</p> <p>The error is: <code>Name 'plux' is not defined.</code></p> <p>Here is the code:</p> <pre><code>from random import randint class Game(object): num = randint(1, 3) def plux(x): x += 1 return...
1
2016-07-05T23:45:28Z
38,214,683
<p>When you call the function <code>plux</code> in the line <code>apple = plux(apple)</code>, add a <code>self.</code> in front of the function call. In Python, <code>self.</code> is used as a reference to the object itself that is used within the class scope (any place inside of the <code>Game</code> class). In every ...
0
2016-07-06T00:06:01Z
[ "python" ]
Can't get Python class code to work
38,214,520
<p>I'm new to Python. Anyway, I was trying to make a 21 questions game, but my code won't work.</p> <p>The error is: <code>Name 'plux' is not defined.</code></p> <p>Here is the code:</p> <pre><code>from random import randint class Game(object): num = randint(1, 3) def plux(x): x += 1 return...
1
2016-07-05T23:45:28Z
38,214,792
<p>The class should look like this (missing self):</p> <pre><code>from random import randint class Game(object): def __init__(self): self.num = randint(1, 3) self.x=0 def plux(self): self.x += 1 def minu(self): self.x -= 1 def iff(sel...
0
2016-07-06T00:27:19Z
[ "python" ]
Program not working as expected
38,214,558
<p>I'm trying to run an example program for a web crawler <a href="http://www.netinstructions.com/how-to-make-a-web-crawler-in-under-50-lines-of-python-code/" rel="nofollow">from netinstructions.com</a> but it is not working. I run the program using:</p> <pre><code>spider("http://www.netinstructions.com/", "python", 5...
0
2016-07-05T23:50:03Z
38,214,678
<p><code>response.getheader('Content-Type')</code> returns <code>text/html; charset=utf-8</code> which is not equal to <code>text/html</code> so you never get any links at all. You can see if it is contained in the string:</p> <pre><code>def getLinks(self, url): self.links = [] # Remember the base URL which wi...
1
2016-07-06T00:05:27Z
[ "python" ]
Calculate avg in subquery in SQLAlchemy
38,214,596
<pre><code>points = Session.query(TeamMatchStats) \ .join(TeamMatchStats.match) \ .join(Match.league) \ .filter(League.season == self.season) \ .filter(TeamMatchStats.team == team) \ .filter(Match.date &lt;= date).limit(7).subquery() points = Session.query(func.avg(points)) </code></pre> <p>What's...
0
2016-07-05T23:55:35Z
38,214,774
<p><code>avg</code> must be used with a column. A subquery in SQLAlchemy is a core selectable, so you must use <code>.c</code> to access the columns. Here I assume <code>TeamMatchStats</code> has a points column:</p> <pre><code>points = Session.query(func.avg(points.c.points)) </code></pre>
2
2016-07-06T00:23:52Z
[ "python", "sqlalchemy", "subquery", "average" ]
Python - Bs4 regex matching results into []
38,214,681
<p>I used regextester101 to confirm that my regex is not incorrect as it does find a match for one of the following ids in the HTML page which is: pj_8c1bde71686c6c05</p> <pre><code>Page im trying to scrape: http://www.indeed.ca/help-desk-jobs-in-ON ID im using as a test from the html file: pj_8c1bde71686c6c0...
1
2016-07-06T00:05:38Z
38,214,770
<p>You need to use the <code>id</code> argument if you want regex to be applied to the <code>id</code> attribute. Also, you need to use a "raw" string and fix your regular expression:</p> <pre><code>bs4.find_all('div', id=re.compile(r'pj_\w+')) </code></pre> <p>Here <code>pj_\w+</code> would match <code>pj</code>, fo...
2
2016-07-06T00:22:10Z
[ "python", "regex", "beautifulsoup", "bs4" ]
Increasing vertices in psychopy to create progress bar
38,214,689
<p>I am trying to create a progress bar for an fMRI task, so that when a participant answers correctly, the progress bar moves up exponentially based on the trial amount/questions left. I have figured out how to make the bar move up only to a specified value (as shown below) but I cannot seem to get it to move up ever...
0
2016-07-06T00:06:33Z
38,218,839
<p>Here's a solution. Read the comments in the code below to learn why I've changed a few things here and there. I've answered your question as if this was a pure code problem first. However, it seems that you may be working through a Builder code component so there's a Builder version below.</p> <h1>Coder version</...
1
2016-07-06T07:51:27Z
[ "python", "psychopy" ]
Interning immutable objects
38,214,721
<p>I have a program with an object of the form</p> <pre><code>class MyObj(object): def __init__(self, a, b): self.__a = a self.__b = b self.cache = very_expensive_computation(a, b) </code></pre> <p>where <code>a,b</code> are immutable and the space of possible parameters <code>a,b</code> i...
3
2016-07-06T00:13:40Z
38,214,755
<p>I'd memoize the <code>very_expensive_computation</code> storing the results in an LRU cache to guarantee an upper bound on the amount of memory used:</p> <pre><code>_very_expensive_computation_cache = RecentlyUsedContainer(100) def cached_very_expensive_computation(a, b): if (a, b) not in _very_expensive_comput...
4
2016-07-06T00:18:40Z
[ "python", "python-3.x" ]
Interning immutable objects
38,214,721
<p>I have a program with an object of the form</p> <pre><code>class MyObj(object): def __init__(self, a, b): self.__a = a self.__b = b self.cache = very_expensive_computation(a, b) </code></pre> <p>where <code>a,b</code> are immutable and the space of possible parameters <code>a,b</code> i...
3
2016-07-06T00:13:40Z
38,214,833
<p>You can also accomplish this with class and instance variables:</p> <pre><code>class BaseMyObj(object): result_store = {} class MyObj(BaseMyObj): def __init__(self, a, b): self.__a = a self.__b = b try: self.cache = BaseMyObj.result_store[(a,b)] except KeyError: ...
2
2016-07-06T00:33:42Z
[ "python", "python-3.x" ]