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 do Luigi parameters work?
39,020,591
<p>So I have two tasks (let's say TaskA and TaskB). I want both tasks to run hourly, but TaskB requires TaskA. TaskB does not have any parameters, but TaskA has two parameters for the day and the hour. If I run TaskB on the command line, would I need to pass it arguments?</p>
0
2016-08-18T14:18:01Z
39,028,995
<p>Well if TaskB requires TaskA but TaskB doesn't accept any parameters, then it probably requires TaskA for current date and time. If this assumption is true, then it's enough to run TaskB @hourly in cron without any parameters, and define it's requires() method to yield TaskA with current date and time.</p> <p>On th...
1
2016-08-18T23:28:05Z
[ "python", "luigi" ]
Error when resample dataframe with python
39,020,617
<p>I create a dataframe </p> <pre><code>df5 = pd.read_csv('C:/Users/Demonstrator/Downloads/Listeequipement.csv',delimiter=';', parse_dates=[0], infer_datetime_format = True) df5['TIMESTAMP'] = pd.to_datetime(df5['TIMESTAMP'], '%d/%m/%y %H:%M') df5['date'] = df5['TIMESTAMP'].dt.date df5['time'] = df5['TIMESTAMP'].dt.ti...
1
2016-08-18T14:19:12Z
39,020,717
<p>remove <code>pd.to_datetime</code> and try <code>df.set_index</code> directly:</p> <pre><code>*df5.index = pd.to_datetime(df5.index)* # Delete this one df5 = df5.set_index('TIMESTAMP') df5 = df5.resample('1d').mean() </code></pre>
2
2016-08-18T14:23:44Z
[ "python", "pandas" ]
How to refactor this to avoid a circular dependency?
39,020,659
<p>I have the following setup:</p> <pre><code># generator.py from node import Node class Generator(object): @staticmethod def generate(self, node): return [Node(), Node(), Node()] # node.py from generator import Generator class Node(object): def generate_child_nodes(self): self.child_nodes = Genera...
0
2016-08-18T14:21:03Z
39,020,710
<p>Like this:</p> <pre><code># generator.py class Generator(object): @staticmethod def generate(self, node): from node import Node return [Node(), Node(), Node()] # node.py from generator import Generator class Node(object): def generate_child_nodes(self): self.child_nodes = Generator.generate...
0
2016-08-18T14:23:32Z
[ "python" ]
How to refactor this to avoid a circular dependency?
39,020,659
<p>I have the following setup:</p> <pre><code># generator.py from node import Node class Generator(object): @staticmethod def generate(self, node): return [Node(), Node(), Node()] # node.py from generator import Generator class Node(object): def generate_child_nodes(self): self.child_nodes = Genera...
0
2016-08-18T14:21:03Z
39,020,948
<p>generator.py</p> <pre><code>def generate(n): for a in range(3): yield n() </code></pre> <p>node.py</p> <pre><code>from generator import generate class Node: def __init__(self): self.id_ = id(self) for n in generate(Node): print(n.id_) </code></pre>
0
2016-08-18T14:33:19Z
[ "python" ]
issue with recursive file search in python3
39,020,746
<p>I was making a function that recursively searches directories for files with a particular suffixes.</p> <blockquote> <p>TypeError: slice indices must be integers or None or have an index method</p> </blockquote> <p>pointing to this line:</p> <blockquote> <p>if path.endswith('.',sf)==True: l.append(path)</p> <...
0
2016-08-18T14:24:47Z
39,029,228
<p>Take a look at the documentation for <code>str.endswith</code>:</p> <pre><code>&gt;&gt;&gt; help(str.endswith) Help on method_descriptor: endswith(...) S.endswith(suffix[, start[, end]]) -&gt; bool Return True if S ends with the specified suffix, False otherwise. With optional start, test S beginning ...
0
2016-08-18T23:59:02Z
[ "python", "file-processing" ]
Decrease spacing between equal signs using latex "eqnarray"-command in matplotlib?
39,020,795
<p>I want to align the equal signs in matplotlib. Thus, I'm using the eqnarray environment in matplotlib:</p> <pre><code>import matplotlib.pyplot as plt from matplotlib import rc rc('text', usetex=True) rc('font', size = 7) fig = plt.figure(figsize=(3,2)) ax = fig.add_subplot(111) ax.text(0.5,0.5 ,r'\...
1
2016-08-18T14:27:01Z
39,047,736
<p>You need to load the amsmath package in order to use 'align'. Problems with the white space in 'eqnarray' are discussed here: <a href="https://github.com/matplotlib/matplotlib/issues/4954" rel="nofollow">https://github.com/matplotlib/matplotlib/issues/4954</a>. At least in matplotlib 1.2.1 the problem is not resolve...
1
2016-08-19T21:11:15Z
[ "python", "matplotlib", "latex", "spacing" ]
TCP/IP header bad hdr length 40 - too long
39,020,798
<p>I am programming in Python a <code>TCP RST</code> packet using raw sockets. To do so, I write 1 in the <code>RST</code> flag and 0 on the rest, put the windows field to 0 and the urgent field to 0. Then I exchange source and destination port. After that, I recalculate the packet size and create the <code>IP</code> h...
1
2016-08-18T14:27:15Z
39,022,333
<p>The problem is in the TCP header. The <code>data offset</code> field (that's what it's called in the RFC but it's often called <code>header length</code> too), you have set to 10 (the first nibble of 0xa0 at offset 0x20 in your packet dump). That is the number of 32-bit words in the TCP header -- or the offset of th...
1
2016-08-18T15:38:57Z
[ "python", "sockets" ]
Why my PyArrayObject* data truncated?
39,020,916
<p>Why do i get truncated array inside my C function?</p> <p>In C:</p> <pre><code>#include &lt;Python.h&gt; #include &lt;arrayobject.h&gt; PyObject *edge(PyObject *self, PyObject *args) { int *ptr; unsigned char *charPtr; PyArrayObject *arr; PyObject *back; int ctr = 0; int size = 500 * 500; ...
-1
2016-08-18T14:32:05Z
39,022,911
<p><code>strlen</code> counts as far as the first 0 in your data (it's designed for null terminated text strings). Also, if the first 0 it encounters is <em>after</em> your data has finished then it'll return a number that's too big meaning you might try to write to data you don't own.</p> <p>To work out the size of t...
2
2016-08-18T16:08:02Z
[ "python", "c", "numpy" ]
Removing lines in a textfile that doesn't have \n
39,020,962
<p>Hi I have a document which I linked <a href="https://drive.google.com/open?id=0B2Kz5NTvWjJueUJwQ0NMdDFvdE0" rel="nofollow">here</a> that has line breaks. But those line breaks were created not by '/n' as I can't seem to get rid of them when I use <code>strip()</code> or even <code>line[:-2]</code>. I'm wondering h...
0
2016-08-18T14:33:46Z
39,021,056
<p>Maybe split with <code>\r\n</code> ?</p> <pre><code>&gt;&gt;&gt; file = open("1128.txt") &gt;&gt;&gt; required_stuff = file.read().split('\r\n') &gt;&gt;&gt; print required_stuff[:10] ['VVIL', '', '1076', '', 'VVIN', '', ' ', '', 'WILSTACH WILLIAM P. &amp; CO. (Wgflliam P.', "TVz'Zsz\xe2\x80\x98ac7z Q\xc2\xbb C/mrl...
1
2016-08-18T14:37:55Z
[ "python", "parsing", "text" ]
Removing lines in a textfile that doesn't have \n
39,020,962
<p>Hi I have a document which I linked <a href="https://drive.google.com/open?id=0B2Kz5NTvWjJueUJwQ0NMdDFvdE0" rel="nofollow">here</a> that has line breaks. But those line breaks were created not by '/n' as I can't seem to get rid of them when I use <code>strip()</code> or even <code>line[:-2]</code>. I'm wondering h...
0
2016-08-18T14:33:46Z
39,021,104
<p>Use the <code>strip()</code> method of <code>str</code> strings. Without arguments it strips leading and trailing spaces of all kind.</p>
0
2016-08-18T14:39:41Z
[ "python", "parsing", "text" ]
Removing lines in a textfile that doesn't have \n
39,020,962
<p>Hi I have a document which I linked <a href="https://drive.google.com/open?id=0B2Kz5NTvWjJueUJwQ0NMdDFvdE0" rel="nofollow">here</a> that has line breaks. But those line breaks were created not by '/n' as I can't seem to get rid of them when I use <code>strip()</code> or even <code>line[:-2]</code>. I'm wondering h...
0
2016-08-18T14:33:46Z
39,021,362
<p>It looks to me like each "record" of your file is delimited by two line breaks, where "line break" refers to DOS-style line endings, that is, a carriage return (<code>'\r'</code>) followed by a line feed (<code>'\n'</code>). Hence we should first split the byte stream on <code>'\r\n\r\n'</code> to get one element pe...
1
2016-08-18T14:52:45Z
[ "python", "parsing", "text" ]
BeautifulSoup: Delete a widget
39,021,114
<p>I have a <code>&lt;twitterwidget&gt;</code> on a <a href="https://www.wired.com/2016/08/turbulence-jetblue-flight-429-injuries/" rel="nofollow">page</a> which needs to be removed (don't need text in tweets). I tried</p> <pre><code>for script in soup(["script", "style"]): script.extract() </code></pre> ...
1
2016-08-18T14:39:53Z
39,022,215
<p>Just extract the <em>twitterwidget</em> element itself and it will remove it completely including all its descendants:</p> <pre><code>from bs4 import BeautifulSoup html = """&lt;div&gt;foobar&lt;/div&gt; &lt;twitterwidget class="twitter-tweet twitter-tweet-rendered" id="twitter-widget-0" data-tweet-id="76396105849...
1
2016-08-18T15:33:09Z
[ "python", "web-scraping", "beautifulsoup" ]
How install FreeBSD port with ansible and module portinstall?
39,021,119
<p>I need build port with something as in shell:</p> <blockquote> <p>cd /usr/ports/www/nginx/ &amp;&amp; make HTTP_GEOIP=YES BATCH=yes</p> </blockquote> <p>I can find <a href="http://docs.ansible.com/ansible/portinstall_module.html" rel="nofollow">any</a> document, how run this with <a href="https://github.com/ansi...
0
2016-08-18T14:39:58Z
39,023,642
<p>Seems like this operation is not implemented in the <a href="http://docs.ansible.com/ansible/portinstall_module.html" rel="nofollow">port_install module</a> The module is part of the <a href="http://docs.ansible.com/ansible/modules_extra.html" rel="nofollow">ansible-module-extra repository</a> which means:</p> <blo...
0
2016-08-18T16:52:51Z
[ "python", "ansible", "freebsd" ]
How install FreeBSD port with ansible and module portinstall?
39,021,119
<p>I need build port with something as in shell:</p> <blockquote> <p>cd /usr/ports/www/nginx/ &amp;&amp; make HTTP_GEOIP=YES BATCH=yes</p> </blockquote> <p>I can find <a href="http://docs.ansible.com/ansible/portinstall_module.html" rel="nofollow">any</a> document, how run this with <a href="https://github.com/ansi...
0
2016-08-18T14:39:58Z
39,062,567
<p>I'd propose to keep local file of customized build options and copy it to the host before portinstall.</p> <pre><code>- name: Copy customized build options copy: src="{{role_path}}/files/nginx-build-options" dest="/var/db/ports/www_nginx/options" - name: Install nginx from the port portinstall: name=ng...
0
2016-08-21T09:02:46Z
[ "python", "ansible", "freebsd" ]
How install FreeBSD port with ansible and module portinstall?
39,021,119
<p>I need build port with something as in shell:</p> <blockquote> <p>cd /usr/ports/www/nginx/ &amp;&amp; make HTTP_GEOIP=YES BATCH=yes</p> </blockquote> <p>I can find <a href="http://docs.ansible.com/ansible/portinstall_module.html" rel="nofollow">any</a> document, how run this with <a href="https://github.com/ansi...
0
2016-08-18T14:39:58Z
39,994,458
<p>I'd like to add. Unfortunately, the proposed workaround is not idempotent.</p> <p><code> - name: Build Nginx with geoip. command: make HTTP_GEOIP=YES BATCH=yes args: chdir: /usr/ports/www/nginx/ </code> This means, that it will be always reported as "changed".</p>
1
2016-10-12T08:56:26Z
[ "python", "ansible", "freebsd" ]
Trying to determine if a specific behavior is allowed in wxPython text
39,021,144
<p>I am trying to determine if something is possible. I haven't written any code for this specifically yet. </p> <p>Using wxPython I would like to set up a text box (possibly a staticText) with primarily un-editable text. However I need certain parts, individual words, to be editable similar to PDF document with added...
1
2016-08-18T14:41:07Z
39,021,238
<p>That's a nice idea, but wx' text boxes are either entirely read only, or editable.</p> <p>I think the way to go for it is to query your position inside the text box for each cursor movement, and toggle the text box state readonly/editable according to you current position, current selection, etc..</p> <p>It looks ...
0
2016-08-18T14:45:47Z
[ "python", "xml", "text", "wx" ]
Django template, send two arguments to template tag?
39,021,159
<p>Can anyone tell me if its possible to send multiple variables from field names to a template tag?</p> <p>this question <a href="http://stackoverflow.com/questions/420703/how-do-i-add-multiple-arguments-to-my-custom-template-filter-in-a-django-templat">How do I add multiple arguments to my custom template filter in ...
0
2016-08-18T14:41:56Z
39,025,419
<p>From my point of view it looks easier to use a simple tag instead of a template filter so you can call it without needing to send a string.</p> <p><a href="https://docs.djangoproject.com/en/1.10/howto/custom-template-tags/#simple-tags" rel="nofollow">https://docs.djangoproject.com/en/1.10/howto/custom-template-tags...
1
2016-08-18T18:44:17Z
[ "python", "django", "templates" ]
Python subprocess pwd inconsistent when file structure includes alias
39,021,173
<p>When I run the following script</p> <pre><code>#!/usr/bin/env python import subprocess print(subprocess.check_output(["pwd"])) </code></pre> <p>the result is</p> <blockquote> <p>/scratch1/name/Dropbox (NAM)/docs/research/Y2/results/s8</p> </blockquote> <p>whilst from my Ubuntu terminal, the command</p> <pre><...
0
2016-08-18T14:43:02Z
39,021,597
<p>TL;DR - Use <a href="https://docs.python.org/2/library/os.html#os.getcwd" rel="nofollow"><code>os.getcwd()</code></a></p> <hr> <p>You could use <a href="https://docs.python.org/2/library/os.path.html#os.path.realpath" rel="nofollow"><code>os.path.realpath</code></a> to turn a path containing symlinks into the phys...
0
2016-08-18T15:03:49Z
[ "python", "shell", "subprocess", "alias", "pwd" ]
Getting first word after comma in a string with varying length in Python
39,021,202
<p>I have a Variable like this:</p> <pre><code>**Name** Heikkinen, Miss. Laina Futrelle, Mrs. Jacques Heath (Lily May Peel) Allen, Mr. William Henry ... </code></pre> <p>I want to extract the first word after comma.</p> <p>This works for me, but it takes 2 dataframe steps:</p> <pre><code>train_df1=train_df['Name']....
0
2016-08-18T14:44:07Z
39,021,288
<p>You can use a regex to get this.</p> <pre><code>import re s="Heikkinen, Miss. Laina" re.findall(r'(?&lt;=,\s)[a-z]+',s,re.I) </code></pre> <p>If the format of the string is consistent (word followed by a <code>,</code> followed by a space followed by space separated words), use</p> <pre><code>[i for i in s.split(...
1
2016-08-18T14:48:37Z
[ "python", "split" ]
Getting first word after comma in a string with varying length in Python
39,021,202
<p>I have a Variable like this:</p> <pre><code>**Name** Heikkinen, Miss. Laina Futrelle, Mrs. Jacques Heath (Lily May Peel) Allen, Mr. William Henry ... </code></pre> <p>I want to extract the first word after comma.</p> <p>This works for me, but it takes 2 dataframe steps:</p> <pre><code>train_df1=train_df['Name']....
0
2016-08-18T14:44:07Z
39,021,477
<p>Using <code>str.partition</code> and <code>str.split</code>.</p> <pre><code>s = 'Heikkinen, Miss. Laina' s.partition(',')[-1].split()[0] # 'Miss.' </code></pre>
0
2016-08-18T14:58:16Z
[ "python", "split" ]
Getting first word after comma in a string with varying length in Python
39,021,202
<p>I have a Variable like this:</p> <pre><code>**Name** Heikkinen, Miss. Laina Futrelle, Mrs. Jacques Heath (Lily May Peel) Allen, Mr. William Henry ... </code></pre> <p>I want to extract the first word after comma.</p> <p>This works for me, but it takes 2 dataframe steps:</p> <pre><code>train_df1=train_df['Name']....
0
2016-08-18T14:44:07Z
39,021,599
<p>Just to add in a one liner assuming that your string is separated by newline characters and the first line is a header of some kind:</p> <pre><code>salutations = [x.split(", ")[1].split(".")[0] for x in string.split("\n")[1:]] </code></pre> <p>Just if you don't want to do the regex solution</p>
0
2016-08-18T15:03:51Z
[ "python", "split" ]
Getting first word after comma in a string with varying length in Python
39,021,202
<p>I have a Variable like this:</p> <pre><code>**Name** Heikkinen, Miss. Laina Futrelle, Mrs. Jacques Heath (Lily May Peel) Allen, Mr. William Henry ... </code></pre> <p>I want to extract the first word after comma.</p> <p>This works for me, but it takes 2 dataframe steps:</p> <pre><code>train_df1=train_df['Name']....
0
2016-08-18T14:44:07Z
39,021,659
<p>i = str.index(",") newStr = str[i:]</p>
0
2016-08-18T15:06:25Z
[ "python", "split" ]
frequency response for a repeating 1-2-1 filter
39,021,206
<p>I'm trying to estimate the effect of applying a simple 1-2-1 filter for multiple times, and determined the residual scales. In specific, I'm trying to reproduce this plot:</p> <p><a href="http://i.stack.imgur.com/dunww.png" rel="nofollow">from Small et al., 2013</a></p> <p>I used the scipy.signal.freqz as below</p...
0
2016-08-18T14:44:10Z
39,031,070
<p>It turned out that I was not wrong. By plotting the absolute value of the transfer function, and dividing the normalized frequeny by 2pi, I got the exact same plots, and applying mutilpe time of filter is exactly mutiplying the frequency response to itself for multiple times. </p> <pre><code>filt = np.array([0.25,0...
0
2016-08-19T04:21:58Z
[ "python", "scipy", "signal-processing" ]
Importing from parent directory in sub folder's file using __init__?
39,021,295
<p>if I have a directory like this</p> <pre><code>dir_one/ main.py __init__.py dir_two/ sub.py __init__.py </code></pre> <p>both my <strong>init</strong>.py files are currently empty. In my sub.py file, I attempt to import a class from main.py: e.g.</p> <pre><code>#File:sub.py from main i...
0
2016-08-18T14:48:58Z
39,021,680
<p>In your file <code>sub.py</code> you could do something like</p> <pre><code>import os wd = os.getcwd() # save current working directory os.chdir('path/to/dir_one') # change to directory containing main.py from main import items # import your stuff os.chdir(wd) # change back to directory containing su...
0
2016-08-18T15:07:20Z
[ "python", "import", "directory" ]
Importing from parent directory in sub folder's file using __init__?
39,021,295
<p>if I have a directory like this</p> <pre><code>dir_one/ main.py __init__.py dir_two/ sub.py __init__.py </code></pre> <p>both my <strong>init</strong>.py files are currently empty. In my sub.py file, I attempt to import a class from main.py: e.g.</p> <pre><code>#File:sub.py from main i...
0
2016-08-18T14:48:58Z
39,042,228
<p>You have a few options here.</p> <p>Your best option is to keep packages separate from scripts that <em>use</em> the package. Have a look at <a href="http://stackoverflow.com/questions/774824/explain-python-entry-points"><code>entry_points</code></a> for setuptools. You point setuptools to a function in your pack...
0
2016-08-19T15:01:35Z
[ "python", "import", "directory" ]
why pip install module in /usr/local/lib/python3.4/dist-packages
39,021,331
<p>I want to install <code>easydict</code> module for python2.7 and I use the following command:</p> <pre><code>sudo pip install easydict </code></pre> <p>and I find the easydict module is installed in the python3 dir:</p> <pre><code>Downloading/unpacking easydict Downloading easydict-1.6.zip Running setup.py (p...
0
2016-08-18T14:51:22Z
39,022,094
<p>It depends on your system path. If system path has path of pip binary or python binary of 3.x prior to the path of 2.x versions. Then 3.x takes preference over 2.x</p> <p>Please re-arrange your system path to have 2.x paths before 3.x paths</p>
0
2016-08-18T15:27:58Z
[ "python" ]
How do I make a colour plot with undefined regions?
39,021,353
<p>Say I have a function like</p> <pre><code>def coulomb(x,y): r = sqrt(x**2 + y**2) return 1/r if r &gt; 1 else None </code></pre> <p>How could I best plot this in a colour plot so every <code>None</code> value simply gets rendered as e.g. white, and only the actual number values assigned to the colour scale...
3
2016-08-18T14:52:14Z
39,021,544
<p>Just use masked arrays:</p> <pre><code>from numpy import ma vs_ma = ma.masked_where(vs &gt; 1, vs) plt.colorbar(plt.pcolor(xs, ys, vs_ma, vmin=0, vmax=1)) </code></pre> <p><a href="http://i.stack.imgur.com/H0uA6.png" rel="nofollow"><img src="http://i.stack.imgur.com/H0uA6.png" alt="enter image description here"></...
4
2016-08-18T15:01:09Z
[ "python", "matplotlib" ]
How do I make a colour plot with undefined regions?
39,021,353
<p>Say I have a function like</p> <pre><code>def coulomb(x,y): r = sqrt(x**2 + y**2) return 1/r if r &gt; 1 else None </code></pre> <p>How could I best plot this in a colour plot so every <code>None</code> value simply gets rendered as e.g. white, and only the actual number values assigned to the colour scale...
3
2016-08-18T14:52:14Z
39,021,732
<p>Interesting. I don't have something I'm really pleased with, but it kind of works.</p> <p>First, you didn't use <code>coulomb</code> to produce nans:</p> <pre><code>vs = np.vectorize(coulomb)(xs, ys) </code></pre> <p>Ok, and then I take the minimum value of the non-nan values, and assign a below the minimum value...
1
2016-08-18T15:09:51Z
[ "python", "matplotlib" ]
How do I make a colour plot with undefined regions?
39,021,353
<p>Say I have a function like</p> <pre><code>def coulomb(x,y): r = sqrt(x**2 + y**2) return 1/r if r &gt; 1 else None </code></pre> <p>How could I best plot this in a colour plot so every <code>None</code> value simply gets rendered as e.g. white, and only the actual number values assigned to the colour scale...
3
2016-08-18T14:52:14Z
39,022,205
<p>I combined <a href="http://stackoverflow.com/a/39021544/745903">Tim Fuchs'</a> and <a href="http://stackoverflow.com/a/39021732/745903">Israel Unterman's</a> suggestions to one that actually uses a function and properly masks away the <code>None</code> values:</p> <pre><code>from numpy import * import matplotlib.py...
1
2016-08-18T15:32:49Z
[ "python", "matplotlib" ]
PyCharm 2016: How to display result without print command (like console)?
39,021,380
<p>I have a Python command:</p> <pre><code>(2.5).as_integer_ratio() </code></pre> <p>I want to see result:</p> <pre><code>(5, 2) </code></pre> <p>like in the command line console, but I don't want use print command inside PyCharm.</p> <pre><code>a = (2.5).as_integer_ratio() print(a) // Result: // (5, 2) </code></...
1
2016-08-18T14:53:33Z
39,021,425
<p>Use the "Python Console" (at the bottom of the screen):</p> <pre><code>&gt;&gt;&gt; (2.5).as_integer_ratio() (5, 2) </code></pre>
0
2016-08-18T14:55:54Z
[ "python", "python-3.x", "pycharm" ]
PyCharm 2016: How to display result without print command (like console)?
39,021,380
<p>I have a Python command:</p> <pre><code>(2.5).as_integer_ratio() </code></pre> <p>I want to see result:</p> <pre><code>(5, 2) </code></pre> <p>like in the command line console, but I don't want use print command inside PyCharm.</p> <pre><code>a = (2.5).as_integer_ratio() print(a) // Result: // (5, 2) </code></...
1
2016-08-18T14:53:33Z
39,021,824
<p><strong>Select all</strong> or select code block, then right click, choose <strong>Execute selection in Console</strong></p> <p>Specific on Mac OS (El Captain):</p> <p>Press <kbd>command</kbd>+<kbd>A</kbd>, then <kbd>option</kbd>+<kbd>shift</kbd>+<kbd>E</kbd>, you will see result at the bottom of PyCharm.</p> <p>...
1
2016-08-18T15:14:52Z
[ "python", "python-3.x", "pycharm" ]
Referencing base class attributes when using multiple inheritance
39,021,422
<pre><code>class Shape: def __init__(self,center,name): self.__name = name self.center = center def getName(self): return self.__name def __add__(self,otherShape): return Shape(name = self.__name, center = self.center + otherShape.center) class Size: def __init__(self,surface,magnitude): sel...
0
2016-08-18T14:55:52Z
39,021,843
<p>Outside the class itself, private names are mangled. See <a href="https://docs.python.org/2/tutorial/classes.html#private-variables-and-class-local-references" rel="nofollow"><em>Private Variables and Class-local References</em></a>.</p> <p>You can work around it by using the mangled name in your code. In other wor...
1
2016-08-18T15:15:30Z
[ "python", "attributes", "multiple-inheritance" ]
Learn Python the hard way ex43
39,021,484
<p>I'm sorry that this question has been asked, and answered multiple times. I've checked out loads of them, with the exact problem and seen their answers but they either don't work for me or are too jargon heavy for my simple mind to understand. Here's my code ;</p> <pre><code>from sys import exit from random import ...
-4
2016-08-18T14:58:32Z
39,021,725
<p>The <code>get</code> method of a dictionary returns <code>None</code> for non-existent keys:</p> <pre><code>a = {'hello': 'world'} print(a.get('hello')) # -&gt; world print(a.get('test')) # -&gt; None </code></pre> <p>You assume that each scene's <code>enter</code> method returns the name of the next scene. Some...
1
2016-08-18T15:09:37Z
[ "python" ]
Suffix search - Python
39,021,703
<p>Here's a the problem, provided a list of strings and a document find the shortest substring that contains all the strings in the list.</p> <p>Thus for,</p> <pre><code>document = 'many google employees can program can google employees because google is a technology company that writes program' searchTerms = ['g...
0
2016-08-18T15:08:38Z
39,022,471
<p>Well, brute force is <code>O(n³)</code>, so why not:</p> <pre><code>from itertools import product def find_shortest(doc, terms): doc = document.split() substrings = ( doc[i:j] for i, j in product(range(0, len(doc)), range(0, len(doc))) if all(search_term in doc[i:j] for search_term...
1
2016-08-18T15:45:16Z
[ "python", "string", "algorithm", "search" ]
Suffix search - Python
39,021,703
<p>Here's a the problem, provided a list of strings and a document find the shortest substring that contains all the strings in the list.</p> <p>Thus for,</p> <pre><code>document = 'many google employees can program can google employees because google is a technology company that writes program' searchTerms = ['g...
0
2016-08-18T15:08:38Z
39,022,640
<p>You can break this into two parts. First, finding the shortest substring that matches some property. We'll pretend we already have a function that tests for the property:</p> <pre><code>def find_shortest_ss(document, some_property): # First level of looping gradually increases substring length for x in rang...
3
2016-08-18T15:53:29Z
[ "python", "string", "algorithm", "search" ]
Suffix search - Python
39,021,703
<p>Here's a the problem, provided a list of strings and a document find the shortest substring that contains all the strings in the list.</p> <p>Thus for,</p> <pre><code>document = 'many google employees can program can google employees because google is a technology company that writes program' searchTerms = ['g...
0
2016-08-18T15:08:38Z
39,023,138
<p>Instead of brute forcing all possible sub-strings, I brute forced all possible matching word positions... It should be a bit faster..</p> <pre><code>import numpy as np from itertools import product document = 'many google employees can program can google employees because google is a technology company that write...
0
2016-08-18T16:21:27Z
[ "python", "string", "algorithm", "search" ]
Can't split django views into subfolders
39,021,754
<p>I'm following the directions from the first answer here:</p> <p><a href="http://stackoverflow.com/questions/1921771/django-split-views-py-in-several-files">Django: split views.py in several files</a></p> <p>I created a 'views' folder in my app and moved my views.py file inside and renamed it to viewsa.py. I also c...
0
2016-08-18T15:11:16Z
39,021,878
<p>Use relative import, in your <code>__init__.py</code>:</p> <pre><code>from .viewsa import * </code></pre> <p>(notice the dot in <code>.viewsa</code>)</p>
0
2016-08-18T15:17:18Z
[ "python", "django" ]
ImportError: No module named SOAPpy
39,021,776
<p>Traceback (most recent call last):</p> <pre><code>File "naturalClient.py", line 9, in &lt;module&gt; from SOAPpy import SOAPProxy ImportError: No module named SOAPpy </code></pre> <p>I get that when i make </p> <pre><code>from SOAPpy import SOAPProxy </code></pre> <p>in python. I use ubuntu 14.04</p>
1
2016-08-18T15:12:08Z
39,021,851
<p>You've probably not installed SOAPpy - that's why you also won't be able to <code>import SOAPpy</code> also</p> <p>Follow <a href="https://pypi.python.org/pypi/SOAPpy#soappy-simple-to-use-soap-library-for-python" rel="nofollow">the official instruction</a></p>
0
2016-08-18T15:15:44Z
[ "python", "python-2.7", "ubuntu-14.04" ]
Client/Server interactions using the Telegram.org API
39,021,814
<p>I'd like to understand the sequence of events when sending a method to the telegram server.</p> <p>For example, if I send the <code>get_future_salts</code> method I am expecting from the server a response of type <code>FutureSalts</code>, but what I receive is a type of <code>MessageContainer</code> (which I'm havi...
1
2016-08-18T15:14:17Z
39,022,320
<p>No, not always. </p> <p>The server however usually packs multiple messages into containers. </p> <p>I would advise that you decode all the data returned from the server. </p> <p>You then have a full view /log of all that is being returned, then you can decide on what needs to be replied to.</p>
1
2016-08-18T15:38:35Z
[ "python", "api", "telegram" ]
Using PyWinAuto to control a currently running application
39,021,888
<p>Using the following code I can find that the currently running window I want to connect is named "Trade Monitor" how do i successfull connect to it? Using the app.start_ method does not work.</p> <pre><code>from pywinauto import application app=application.Application app.findwindows #prints all windows running on ...
0
2016-08-18T15:17:37Z
39,022,894
<p>Just use <code>app = Application().connect(title='Trade Monitor')</code>. More detailed info is <a href="http://pywinauto.github.io/docs/HowTo.html#how-to-specify-an-usable-application-instance" rel="nofollow">in the docs here</a>.</p>
0
2016-08-18T16:07:00Z
[ "python", "windows", "pywinauto", "com-object" ]
Can't get "print" output in colsole with selenium + python
39,021,932
<p>The problem is, I can't see my print in console, although I should!</p> <pre><code>def test_123(app): wd = app.wd app.open_page("page_adress") time.sleep(3) element = wd.find_element_by_xpath("locator").text print(element) </code></pre> <p>String from my app file:</p> <pre><code>wd = webdriver.Chrome() </cod...
0
2016-08-18T15:20:10Z
39,022,228
<p>Is there a space in the actual print call in your code or is that a typo? I know in python 3.X with Selenium I've only ever used print as follows:</p> <p><code>print(element)</code></p> <p>Notice there is no space between the print command and the parenthesis.</p> <p><strong>Updating</strong></p> <p>Ok so now t...
0
2016-08-18T15:33:49Z
[ "python", "selenium", "automated-tests" ]
Data Augmentation using GPU in Theano
39,022,010
<p>I am new in Theano and Deep Learning, I am running my experiments in Theano but I would like to reduce the time I spend per epoch by doing data augmentation directly using the GPU. </p> <p>Unfortunately I can not use PyCuda, so I would like to know if is possible to do basic Data Augmentation using Theano. For exam...
0
2016-08-18T15:24:07Z
39,022,612
<p>If the data augmentation is part of your computation graph, and can be executed on GPU, it will naturally be executed on the GPU. So the question narrows down to "is it possible to do common data augmentation tasks using Theano tensor operations on the GPU".</p> <p>If the transformations you want to apply are just ...
0
2016-08-18T15:51:59Z
[ "python", "numpy", "deep-learning", "theano", "theano-cuda" ]
Appending a dictionary containing a list to another dictionary in python
39,022,016
<p>I've got the following dictionary, as you can see the list of bids made is an item in the dictionary at the same level as the actual job.</p> <p>What I'd like to be able to do is append the bids:[] key pair to the job:{} dictionary so that I can then allow a user to give a job ID to the program and it will output a...
-2
2016-08-18T15:24:24Z
39,022,593
<p>Maybe like this, if <code>d</code> is your original dictionary:</p> <pre><code>jobs[d['job']['jobID']] = d['job'] jobs[d['job']['jobID']]['bids'] = d['bids'] </code></pre> <p>Now you can search for all applicants for a job with a given <code>JobID</code>:</p> <pre><code>applicants = [bid['Name'] for bid in jobs[J...
0
2016-08-18T15:51:21Z
[ "python", "arrays", "list", "dictionary" ]
Address of last value in 1d NumPy array
39,022,027
<p>I have a 1d array with zeros scattered throughout. Would like to create a second array which contains the position of the last zero, like so:</p> <pre><code>&gt;&gt;&gt; a = np.array([1, 0, 3, 2, 0, 3, 5, 8, 0, 7, 12]) &gt;&gt;&gt; foo(a) [0, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3] </code></pre> <p>Is there a built-in NumPy...
3
2016-08-18T15:24:58Z
39,022,135
<pre><code>&gt;&gt;&gt; (a == 0).cumsum() array([0, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3]) </code></pre>
8
2016-08-18T15:29:43Z
[ "python", "arrays", "numpy" ]
Restrict nosetests coverage to only the tests that were run
39,022,185
<p>Is there a way to have nosetests restrict the coverage information to only the tests that were run?</p> <p>I know about the <code>cover-package</code> flag, but it would be nicer if you didn't have to specify the package.</p> <p>This would be especially useful when running a a single unit test class that lives in ...
1
2016-08-18T15:32:13Z
39,025,314
<p>Unfortunately I do not know of a way in nosetests to perform this action. I actually ended up uninstalling nosetests and using just coverage.py because it seems like nosetests and coverage don't play nicely together. I know for a fact you can specify down to individual test methods what you want to run. I'm not s...
0
2016-08-18T18:38:31Z
[ "python", "testing", "code-coverage", "nose" ]
Python Fabric stops automating commands on Cisco devices
39,022,202
<p>I run my Fab file on over 100 devices. It goes through every device without issue, saving the output locally. However, every time it gets to a Cisco device, it will type the command in, but will not, essentially hit "ENTER". I have to manually hit "ENTER", then type "exit". It will then go onto the next command for ...
0
2016-08-18T15:32:42Z
39,044,902
<p>We need to see the code :) to be able to help out.</p> <p>Sometimes you need to add extra "CR" Carriage Return (Hitting enter) when working with Cisco routers : file.write("\r"), you'll find a lot of posts about that.</p>
0
2016-08-19T17:40:42Z
[ "python", "fabric", "cisco" ]
Elegant way to convert dictreader to a dictionary of dictionaries
39,022,211
<p>I am doing this:</p> <pre><code>headers = ['name', 'accum', 'hi', 'active', 'first', 'last', 'max', 'dirty'] filename = "C:\\Users\\bcrafton\\Desktop\\se0sh0cb0_perf.vec" with open("C:\\Users\\bcrafton\\Desktop\\se0sh0cb0_perf.vec") as csvfile: for line in csvfile: if all(header in line for header in ...
1
2016-08-18T15:33:04Z
39,023,860
<p>Even though you've left out some essential details, I went ahead and made a few assumptions resulting in this:</p> <pre><code>table = {} with open("C:\\Users\\bcrafton\\Desktop\\se0sh0cb0_perf.vec") as csvfile: for line in csvfile: if all(header in line for header in headers): for row in cs...
1
2016-08-18T17:07:04Z
[ "python", "dictionary", "file-io" ]
Python datetime to int
39,022,222
<p>I'm returning a datetime object that I wish to convert to int. For example:</p> <pre><code>print var, type(var) 5 day, 0:00:00 &lt;type 'datetime.timedelta'&gt; </code></pre> <p>How to return <code>5</code> as int?</p>
0
2016-08-18T15:33:40Z
39,022,260
<p>In your example you should do <code>var.days</code></p>
2
2016-08-18T15:35:22Z
[ "python" ]
Use a variable from one function within another function with Python
39,022,264
<p>I have a program that downloads video files Here it is in full, don't worry its a short program.</p> <pre><code>import pafy def download(): url = raw_input('Please enter the path to the video\n') video = pafy.new(url) vid_title = video.title best = video.getbest() streams = video.streams pr...
0
2016-08-18T15:35:37Z
39,022,857
<p>Split a big function into smaller ones is a good habit but a more urgent problem is that you should use a main loop and make your functions return instead of chaining them like that. </p> <p>Right now download() -> another_download() -> download() -> another_download() -> download() -> ..., so if the user wants to ...
0
2016-08-18T16:04:42Z
[ "python", "variables" ]
Use a variable from one function within another function with Python
39,022,264
<p>I have a program that downloads video files Here it is in full, don't worry its a short program.</p> <pre><code>import pafy def download(): url = raw_input('Please enter the path to the video\n') video = pafy.new(url) vid_title = video.title best = video.getbest() streams = video.streams pr...
0
2016-08-18T15:35:37Z
39,022,865
<p>There are a couple options for you here. I will try and lay them out best I can.</p> <p>Option 1: Assuming you are calling <code>download()</code> first, you can have <code>url()</code> return what you need and store that in a variable in the <code>download()</code> method:</p> <pre><code>def url(): url = raw...
0
2016-08-18T16:05:18Z
[ "python", "variables" ]
Why can't I apply pandas.DatetimeIndex to multiple columns?
39,022,272
<p>I am trying to drop the time portion on several pandas columns using the following code:</p> <pre><code>group_df['submitted_on'] = pd.DatetimeIndex(group_df['submitted_on']).to_period('d') group_df['resolved_on'] = pd.DatetimeIndex(group_df['resolved_on']).to_period('d') </code></pre> <p>This works fine for the fi...
2
2016-08-18T15:36:08Z
39,022,690
<p>Use <code>pd.to_datetime</code> instead of <code>pd.DatetimeIndex</code></p> <pre><code>group_df['submitted_on'] = pd.to_datetime(group_df['submitted_on'], 'coerce').dt.to_period('d') group_df['resolved_on'] = pd.to_datetime(group_df['resolved_on'], 'coerce').dt.to_period('d') group_df </code></pre> <p><a href="h...
3
2016-08-18T15:56:16Z
[ "python", "pandas", "datetimeindex" ]
Django query, average count distinct
39,022,273
<p>I have a <code>Donation</code> model defined as:</p> <pre><code>Donation project = models.ForeignKey(Project) user = models.CharField() </code></pre> <p>Each user can donate multiple time to any project, so in db I can have the following:</p> <pre><code> Donation ------------------- project | user ------...
3
2016-08-18T15:36:09Z
39,022,802
<p>You don't need to sum values for average, you can just count distinct values and divide by number of distinct users. Also <code>order_by</code> is redundant since we need only counts.</p> <pre><code>distinct_pairs_count = Donation.objects.values('user', 'project').distinct().count() distinct_users_count = Donation...
3
2016-08-18T16:01:17Z
[ "python", "django", "postgresql", "django-models", "django-queryset" ]
Updating a list of dicts filled by SQLAlchemy causes “object is not subscriptable” error
39,022,458
<p>My Flask-Restful Web-server has a list of dicts called <code>mashrecipies</code>. </p> <pre><code>mashrecipies = [ { 'id': 1, 'name': 'Kölsch', 'description': 'Top fermented ale from Köln' }, { 'id': 2, 'name': 'IPA', 'description': 'Classic British Imp...
0
2016-08-18T15:44:50Z
39,022,804
<p>Based on the error text, I believe that the type of object you store in mashrecipe (of type Mash) is not subscriptable. That is, it does not have the function that python interpreter calls when you use [] on an instance. For example, arrays and lists are subscriptable and do have this function.</p> <p>To make an ob...
1
2016-08-18T16:01:31Z
[ "python", "dictionary", "sqlalchemy" ]
Pandas, subtract values based on value of another column
39,022,527
<p>In Pandas, I'm trying to figure out how to generate a column that is the difference between the time of the current row and time of the last row in which the value of another column is True:</p> <p>So given the dataframe:</p> <pre><code>df = pd.DataFrame({'Time':[5,10,15,20,25,30,35,40,45,50], 'Event_O...
0
2016-08-18T15:48:01Z
39,022,814
<p>Using <code>df.Event_Occured.cumsum()</code> gives you distinct groups to <code>groupby</code>. Then applying a function per group that subtracts the first member's value from every member gets you what you want.</p> <pre><code>df['Time_since_last'] = \ df.groupby(df.Event_Occured.cumsum()).Time.apply(lambda x...
3
2016-08-18T16:02:01Z
[ "python", "pandas" ]
Pandas, subtract values based on value of another column
39,022,527
<p>In Pandas, I'm trying to figure out how to generate a column that is the difference between the time of the current row and time of the last row in which the value of another column is True:</p> <p>So given the dataframe:</p> <pre><code>df = pd.DataFrame({'Time':[5,10,15,20,25,30,35,40,45,50], 'Event_O...
0
2016-08-18T15:48:01Z
39,023,141
<p>Here's an alternative that fills the values corresponding to Falses with the last valid observation:</p> <pre><code>df['Time'] - df.loc[df['Event_Occured'], 'Time'].reindex(df.index).ffill() Out: 0 0.0 1 5.0 2 10.0 3 0.0 4 0.0 5 5.0 6 10.0 7 0.0 8 5.0 9 10.0 Name: Time, dtype: ...
1
2016-08-18T16:21:38Z
[ "python", "pandas" ]
How to make an object move through an array of objects on keypress?
39,022,584
<p>Here is all of my code: </p> <pre><code>import random as random import pygame as pygame pygame.init() # initialize clock = pygame.time.Clock() # framerate limit Screen = pygame.display.set_mode([1000, 1000]) # Create screen object and Window Size Done = False MapSize = 25 TileWidth = 20 TileHeight = 20 TileMa...
1
2016-08-18T15:50:59Z
39,036,923
<p>Thanks for undeleting your question so I could post an answer. Sorry it took so long for me to get back to you on this — hopefully it's not too late to be helpful.</p> <p>Below is a heavily revised (but working) version of the code in your question. One of the things that slowed me down was that you weren't follo...
1
2016-08-19T10:38:16Z
[ "python", "arrays", "python-3.x", "oop", "pygame" ]
Spreading values on a bar chart with plotly
39,022,595
<p>I've got this list of numbers:</p> <pre><code>[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.06973765202658326, 0.0759476951525558, 0.09813542688910697, 0.10382657209692146, 0.11627906976744186, 0.12999675008124797, 0.15083990401097017, 0.15699535052231145, 0.1582487142291969, 0.16269605108256...
1
2016-08-18T15:51:29Z
39,025,329
<p>I believe you can simply use: (within the <code>layout = ( )</code>)</p> <pre><code>xaxis = dict(tickvals = [ 0, 0.1, 2, 30, 40, 50 ]) </code></pre> <p>Or something of the sort, to get the varied definition in your x-axis you are looking for.</p> <p>I am not too familiar with plotly, but this seems to me like it ...
1
2016-08-18T18:39:10Z
[ "python", "python-2.7", "charts", "bar-chart", "plotly" ]
Provide temporary PYTHONPATH on the commandline?
39,022,629
<p>I'm thinking of something like</p> <p><code>python3 my_script.py --pythonpath /path/to/some/necessary/modules</code></p> <p>Is there something like this? I know (I think) that Pycharm temporarily modifies <code>PYTHONPATH</code> when you use it to execute scripts; how does Pycharm do it?</p> <h2>Reasons I want to...
1
2016-08-18T15:53:07Z
39,022,669
<p>You can specify the python path in an environment variable like so:</p> <pre><code>PYTHONPATH=/path/to/some/necessary/modules python3 my_script.py </code></pre>
3
2016-08-18T15:55:17Z
[ "python", "pycharm", "pythonpath" ]
Provide temporary PYTHONPATH on the commandline?
39,022,629
<p>I'm thinking of something like</p> <p><code>python3 my_script.py --pythonpath /path/to/some/necessary/modules</code></p> <p>Is there something like this? I know (I think) that Pycharm temporarily modifies <code>PYTHONPATH</code> when you use it to execute scripts; how does Pycharm do it?</p> <h2>Reasons I want to...
1
2016-08-18T15:53:07Z
39,022,921
<p>Not sure how much effort you want to put into this temporary python path thing but you could always use a python virtual environment for running scripts or whatever you need.</p>
0
2016-08-18T16:08:35Z
[ "python", "pycharm", "pythonpath" ]
index column undefined after resampling a dataframe
39,022,648
<p>I created a dataframe df5 :</p> <pre><code>df5 = pd.read_csv('C:/Users/Demonstrator/Downloads/Listeequipement.csv',delimiter=';', parse_dates=[0], infer_datetime_format = True) df5['TIMESTAMP'] = pd.to_datetime(df5['TIMESTAMP'], '%d/%m/%y %H:%M') df5['date'] = df5['TIMESTAMP'].dt.date df5['time'] = df5['TIMESTAMP']...
1
2016-08-18T15:53:45Z
39,022,893
<p>You can keep the column in the dataframe even after you assign it as the index like this:</p> <pre><code>df5 = df5.set_index('TIMESTAMP', drop=False) </code></pre>
0
2016-08-18T16:06:57Z
[ "python", "pandas", "numpy" ]
Python, Theano - ValueError: Input dimension mis-match
39,022,757
<p>I have built a DNN in Theano based on the mnist.py example in Lasagne. I am trying to train a neural network made by a single hidden layer first, defined as</p> <pre><code>def build_first_auto(input_var=None): l_input=lasagne.layers.InputLayer(shape=(None, 1, 48, 1), input_var=input_var) l_hidden1=lasagne....
1
2016-08-18T15:58:42Z
39,136,694
<p>For your network, the output is 256-dim. Since you are using binary cross-entropy loss function, I suppose you want to classify samples into 2 classes. You need a output layer with num_units=2 and softmax</p> <pre><code>def build_first_auto(input_var=None): l_input=lasagne.layers.InputLayer(shape=(None, 1, 48, ...
0
2016-08-25T04:26:21Z
[ "python", "machine-learning", "neural-network", "theano", "lasagne" ]
how to install xgboost easily on windows
39,022,782
<p>i have been struggling with xgboost installation , i did many things but i can see <a href="https://www.kaggle.com/c/liberty-mutual-group-property-inspection-prediction/forums/t/16120/how-to-xgboost-in-python-3-4-3-anaconda-2-2-0-64-bit/90416#post90416" rel="nofollow">this</a> might work . I downloaded the file <a h...
0
2016-08-18T16:00:23Z
39,023,278
<p>from the <a href="http://xgboost.readthedocs.io/en/latest/build.html" rel="nofollow">documentation</a>:</p> <pre><code>import os os.environ['PATH'] = os.environ['PATH'] + ';C:\\Program Files\\mingw-w64\\x86_64-5.3.0-posix-seh-rt_v4-rev0\\mingw64\\bin' </code></pre>
0
2016-08-18T16:30:33Z
[ "python", "xgboost" ]
Lasagne: neural Network Image(character) classification. Selection of size output_num_units
39,022,810
<p>I am performing classification with the help of neural network used in danielnouri's blog post. The total size of the training data is 6300 samples. The data is 20*20 sized character pictures. I am unable to figure out how to select the size of output_num_units. Total number of unique classes are 63. Shape of xtra...
0
2016-08-18T16:01:52Z
39,187,514
<p>I suspect your classes aren't encoded as integers 0-62, in which case you can pass <code>use_label_encoder=True</code> to <code>NeuralNet</code> to have it do the encoding automatically.</p>
0
2016-08-28T02:30:07Z
[ "python", "theano", "lasagne" ]
Updating values in a list from a Tkinter entry box - Python
39,022,852
<p>I am trying to update the values in a list from values that are entered into an entry box created in TKinter. In my example the user enters the real name of the people in a list. Their real name will replace the 'x' in the example_list. </p> <p>I have specified the variable as global in the method but the change on...
1
2016-08-18T16:04:16Z
39,027,755
<p>Thanks to Wayne Werner who directed me towards the tksimpledialog, the solution to the problem is here. </p> <pre><code>from Tkinter import * import tkSimpleDialog example_list = [['Jimmy Bob','x','78'],[" Bobby Jim",'x','45'] ,["Sammy Jim Bob",'x','67'] ] root = Tk() root.geometry("400x400") Label(root, text = "...
0
2016-08-18T21:25:53Z
[ "python", "python-2.7", "tkinter" ]
Format a mathematical expression from user input to python
39,022,897
<p>I want to be able convert the input of a mathematical expression from a user to the python format for math expressions. For example if the user input is: </p> <blockquote> <p>3x^2+5</p> </blockquote> <p>I want to be able to convert that into </p> <blockquote> <p>3*x**2+5</p> </blockquote> <p>so that I can us...
0
2016-08-18T16:07:09Z
39,023,114
<p>You can use simple string formatting to accomplish this.</p> <pre><code>import re expression = "3x^2+5" expression = expression.replace("^", "**") expression = re.sub(r"(\d+)([a-z])", r"\1*\2", expression) </code></pre> <p>For more advanced parsing and symbolic mathematics in general, check out <a href="http://s...
1
2016-08-18T16:19:59Z
[ "python", "parsing", "expression", "mathematical-expressions" ]
pandas dataframe groupby and return nth row unless nth row doesn't exist
39,022,943
<p>I have a pandas dataframe like so:</p> <pre><code> date id person latitude longitude 0 2016-07-11 1 rob 41.395279 2.162126 1 2016-07-11 1 harry 51.485146 0.041339 2 2016-07-11 1 susan ...
3
2016-08-18T16:09:48Z
39,023,062
<p>One way is to use <code>apply</code> and pick up the row according to the number of rows for each group:</p> <pre><code>df.groupby(['date', 'id']).apply(lambda g: g.iloc[1,:] if g.shape[0] &gt;= 2 else g.iloc[0,:]).reset_index(drop = True) # date id person latitude longitude #0 2016-07-11 1 harry...
3
2016-08-18T16:16:57Z
[ "python", "pandas", "dataframe" ]
pandas dataframe groupby and return nth row unless nth row doesn't exist
39,022,943
<p>I have a pandas dataframe like so:</p> <pre><code> date id person latitude longitude 0 2016-07-11 1 rob 41.395279 2.162126 1 2016-07-11 1 harry 51.485146 0.041339 2 2016-07-11 1 susan ...
3
2016-08-18T16:09:48Z
39,023,346
<p>Similar to unutbu's approach to <a href="http://stackoverflow.com/q/38957036/2285236">this question</a>, you can take the first two (if you have one, head(2) will return only 1) and drop the duplicates keeping the last (2nd) occurrence:</p> <pre><code>df.groupby(['date', 'id']).head(2).drop_duplicates(['date', 'id'...
3
2016-08-18T16:34:44Z
[ "python", "pandas", "dataframe" ]
double backslash (\\) in file name while opening
39,023,045
<pre><code>path = r'C:\Myfolder\data\today' for root, directories, filenames in os.walk(path): for filename in filenames: fname = os.path.join(root,filename) if os.path.isfile(fname) and fname[-4:] == '.log': if fname not in rows1: print fname fname=fname.r...
-1
2016-08-18T16:16:02Z
39,023,763
<p>Besides, there isn't really an error, you should not use replace to strip off a known prefix, use string-slicing instead and use the full filename to open the file:</p> <pre><code>path = r'C:\Myfolder\data\today' for root, directories, filenames in os.walk(path): for filename in filenames: fullname = os...
-1
2016-08-18T17:00:57Z
[ "python", "file" ]
SFrames: Converting str to int or float
39,023,094
<p>I am starting to learn SFrames data structure lately. I wonder if anyone experienced the problem of converting a "str" column to "float" or "int" column. In R, I could easily accomplish the task by as.numeric() or as.integer().</p> <p>How could I do that in SFrames (python)?</p> <p>Thanks,</p>
0
2016-08-18T16:18:43Z
39,060,965
<p>I've found this approach works.</p> <pre><code>sf['column_name'] = sf['column_name'].astype(float) sf['column_name'] = sf['column_name'].astype(str) </code></pre>
0
2016-08-21T04:59:12Z
[ "python", "graphlab" ]
Python functional abstraction
39,023,133
<p><img src="http://i.stack.imgur.com/xWWTI.png" alt="enter image description here"></p> <p>Hi, guys, im very new to python. I was tasked to do such a question but I have no idea what went wrong with what I've written down. Can any1 please enlighten me</p>
-6
2016-08-18T16:21:11Z
39,023,209
<p>Your call to the greet function is indented. It should not be indented (the last line)</p>
-1
2016-08-18T16:25:58Z
[ "python", "python-3.x" ]
Python functional abstraction
39,023,133
<p><img src="http://i.stack.imgur.com/xWWTI.png" alt="enter image description here"></p> <p>Hi, guys, im very new to python. I was tasked to do such a question but I have no idea what went wrong with what I've written down. Can any1 please enlighten me</p>
-6
2016-08-18T16:21:11Z
39,023,345
<p>Try this.</p> <pre><code>def greet(name, language): if language=="English": greet="Nice to meet you" else: greet="unknown language" return greet+ " " + name greet("Ben", "English") </code></pre> <p>I'm sure you can fill in the rest. Pay attention to the indentation(the number of space...
0
2016-08-18T16:34:40Z
[ "python", "python-3.x" ]
PyQt4 GUI Box Layout Fixed Width
39,023,221
<p>Is there a way to set a fixed width of a <code>QHBoxLayout</code>?</p> <p>For example, when I have two small widgets in it that take up little space and I don't want the two to split over the entire screen width when I full screen the app. The widgets already have their widths set to their <code>minimumSizeHint()</...
0
2016-08-18T16:26:34Z
39,023,363
<p>Admission: I don't use PyQT, but I use Qt in C++. I believe it would work the same.</p> <p>The trick here, is to as you run QHBoxLayout::addWidget(), you define a stretch factor (greater than zero) to the widgets you want to stretch. You define a zero-stretch factor (the default) to the ones you want to stay small....
0
2016-08-18T16:35:27Z
[ "python", "layout", "pyqt4", "spacing" ]
PyQt4 GUI Box Layout Fixed Width
39,023,221
<p>Is there a way to set a fixed width of a <code>QHBoxLayout</code>?</p> <p>For example, when I have two small widgets in it that take up little space and I don't want the two to split over the entire screen width when I full screen the app. The widgets already have their widths set to their <code>minimumSizeHint()</...
0
2016-08-18T16:26:34Z
39,030,693
<p>Just add a stretchable space to the end of the layout:</p> <pre><code> hbox_layout.addStretch() </code></pre> <p>Or if you want the widgets on the right:</p> <pre><code> hbox_layout.insertStretch(0) </code></pre>
0
2016-08-19T03:32:26Z
[ "python", "layout", "pyqt4", "spacing" ]
How to load a code source modified package in Python?
39,023,270
<p>I have downloaded from github a package (scikit-lean) and put the code source in repository folder (Windows 7 64-bit).</p> <p>After modifying the code source, how can I load the package into the IPython notebook for testing ?</p> <ol> <li><p>Should I copy paste the modified in sites-packages folder ?<br> (what abo...
0
2016-08-18T16:30:01Z
39,031,052
<p>If the code is in a file called file.py, you should just be able to do <code>import file</code> (if you're not in the right folder, just run <code>cd folder</code> in IPython first.)</p>
0
2016-08-19T04:19:22Z
[ "python", "scikit-learn", "ipython" ]
cleanest way to call one function on a list of items
39,023,423
<p>In python 2, I used <code>map</code> to apply a function to several items, for instance, to remove all items matching a pattern:</p> <pre><code>map(os.remove,glob.glob("*.pyc")) </code></pre> <p>Of course I ignore the return code of <code>os.remove</code>, I just want all files to be deleted. It created a temp ins...
2
2016-08-18T16:39:07Z
39,023,594
<p>The change from <code>map()</code> (and many other functions from 2.7 to 3.x) returning a generator instead of a list is a memory saving technique. For most cases, there is no performance penalty to writing out the loop more formally (it may even be preferred for readability).</p> <p>I would provide an example, but...
1
2016-08-18T16:49:26Z
[ "python", "python-3.x", "iterator" ]
Rewriting code to generate all numbers containing consecutive primes starting at two, less than a given number
39,023,459
<p>I have been trying to solve <a href="https://projecteuler.net/problem=293" rel="nofollow">this</a> project euler problem, and have found a correct solution. My code however is terrible. I use several nested loops that I wish to make into some nicer functions or such. The following is the first three sections of the ...
0
2016-08-18T16:40:48Z
39,024,084
<p>this works to find the correct number of primes &lt; 100. You'll need to change 100 to a variable and change numPrimes to actually set the prime value but it works:</p> <pre><code>int i; int j; int numPrimes = 0; for (i = 3; i &lt; 100; i++) { for (j = 2; j &lt; (i-1); j++) { if ((i % j) == 0) { ...
0
2016-08-18T17:21:52Z
[ "python", "math" ]
Rewriting code to generate all numbers containing consecutive primes starting at two, less than a given number
39,023,459
<p>I have been trying to solve <a href="https://projecteuler.net/problem=293" rel="nofollow">this</a> project euler problem, and have found a correct solution. My code however is terrible. I use several nested loops that I wish to make into some nicer functions or such. The following is the first three sections of the ...
0
2016-08-18T16:40:48Z
39,037,345
<p>Ok so I figured this one out, by doing the nested loops recursively as a generator. Below is a MUCH nicer code that yields the same answer.</p> <pre><code>def loop(n,depth): if depth==0: num1=1 while num1&lt;n/2: num1*=pr[0] yield num1 else: for i in loop(n,de...
0
2016-08-19T10:58:16Z
[ "python", "math" ]
python nested list comprehension and text formating
39,023,504
<p>I am having some difficulty trying to format data extracted from a dictionary, which will be used to compose an email. I am trying to use list comprehension to a) minimize the amount of code sent to the email function and b) to remove the outer brackets on my dictionary values and insert a newline;</p> <p>Code:</p>...
0
2016-08-18T16:43:19Z
39,023,571
<p>using the string representation of a list is not a good idea, but if you really need to do, use a for-loop to print the sublists:</p> <pre><code>for site_id, ap_list in test_dict.iteritems(): alert_header = ['aname', 'cname', 'status'] print(site_id) print(alert_header) for ap in ap_list: pr...
0
2016-08-18T16:48:07Z
[ "python", "list", "string-formatting", "list-comprehension" ]
python nested list comprehension and text formating
39,023,504
<p>I am having some difficulty trying to format data extracted from a dictionary, which will be used to compose an email. I am trying to use list comprehension to a) minimize the amount of code sent to the email function and b) to remove the outer brackets on my dictionary values and insert a newline;</p> <p>Code:</p>...
0
2016-08-18T16:43:19Z
39,024,133
<p>To get a single string to send:</p> <pre><code>test_dict = {'A': [['ap11', 'ct1', 'status a'], ['ap2', 'ct2', 'status b'], ['ap11', 'ct1', 'status a']], 'B': [['ap33', 'ct3', 'status b']]} alert_header = str(['aname', 'cname', 'status']) for site_id, v in test_di...
0
2016-08-18T17:25:03Z
[ "python", "list", "string-formatting", "list-comprehension" ]
Pandas: merge dataframes and create new conditional columns
39,023,511
<p>I have two large pandas dataframes (with millions of rows) that contain two columns, a group identifier and an id. I'm trying to create a combined dataframe that contains the group, id, plus a column with a 1 if the id was in the first dataframe, else a 0 and a column with a 1 if the id was in the second dataframe, ...
1
2016-08-18T16:43:39Z
39,023,626
<p>You can create two columns for each of the data frame with one before merging and fill na with zero after merging:</p> <pre><code>df_a['a'] = 1 df_b['b'] = 1 pd.merge(df_a, df_b, how = 'outer', on = ['group', 'id']).fillna(0) # group id a b # 0 A 11.0 1.0 1.0 # 1 A 12.0 1.0 0.0 # 2 A 13.0 ...
3
2016-08-18T16:51:32Z
[ "python", "pandas", "merge" ]
Python broken on upgrade from Ubuntu 12.04 to 14.04
39,023,582
<p>Hi I am trying to update Ubuntu 12.04 LTS to 14.04 LTS via "do-release-upgrade" but still got:</p> <pre><code>2016-08-18 18:40:08,938 INFO apt version: '0.8.16~exp12ubuntu10.27' 2016-08-18 18:40:08,938 INFO python version: '2.7.12 (default, Jul 18 2016, 14:59:49) [GCC 4.6.3]' 2016-08-18 18:40:08,939 INFO release-u...
-1
2016-08-18T16:48:39Z
39,028,534
<p>I already "fixed" this issue by killing sshd directly, hardly reinstalled python2.7.12 by compiling from source. </p> <p>Got some python errors on end of upgrade... After upgrading everything seems to be fine.</p>
0
2016-08-18T22:35:38Z
[ "python", "ubuntu" ]
How to geographically filter entries in PySpark?
39,023,583
<p>I have a dataset of locations in Lat/Lon format of users in a time period and I would like to filter the entries using GIS functions. For example, finding entries inside a polygon (ST_Contains from the GIS world) and using an <a href="http://www.gadm.org/country" rel="nofollow">ESRI geodatabase</a> file to add a co...
0
2016-08-18T16:48:42Z
39,027,464
<p>You can use any python library with Spark, no need for the library to be Spark specific. Some GIS python libraries recommended by some random search are at <a href="http://spatialdemography.org/essential-python-geospatial-libraries/" rel="nofollow">http://spatialdemography.org/essential-python-geospatial-libraries/<...
1
2016-08-18T21:02:32Z
[ "python", "hadoop", "apache-spark", "pyspark", "hdinsight" ]
on windows, where does python's socket.getfqdn() pull from?
39,023,588
<p>on Windows, does anyone know the ultimate source of the data that is returned by socket.getfqdn()? I have a system where I expect the FQDN to be "foo.bar.baz.example.com", and getfqdn() is returning ".snafu.example.com"</p>
0
2016-08-18T16:49:03Z
39,023,716
<p><code>socket.getfqdn()</code> calls either</p> <ul> <li><a href="https://msdn.microsoft.com/de-de/library/windows/desktop/ms738527(v=vs.85).aspx" rel="nofollow"><code>gethostname()</code></a></li> <li>or resolves the name using <a href="https://msdn.microsoft.com/de-de/library/windows/desktop/ms738521(v=vs.85).aspx...
2
2016-08-18T16:58:02Z
[ "python" ]
For Loop for excel data table in python
39,023,616
<p>All,</p> <p>I have a csv file that lists stocks and their data. Column J in the Csv file shows their volume. I am trying to use the below code to sort the data into a list with stocks that have a volume higher than 1,000,000. However, when it prints the FirstList, it shows all stocks, including ones under the 1,...
-1
2016-08-18T16:50:41Z
39,023,800
<p>This what you're going for?</p> <pre><code>FirstList = [] for i in range(5, 2000, 1): value = int(sheet.cell(row=i, column=9).value) if value &gt; 1000000: FirstList.append(value) print FirstList </code></pre>
1
2016-08-18T17:03:27Z
[ "python", "csv", "for-loop", "openpyxl" ]
What does pip install . (dot) mean?
39,023,758
<p>I have a shell script which last line is following:</p> <p><code>pip install .</code></p> <p>What does it do?</p> <p>When we run <code>pip install package-name</code>, it will install specified package. Similarly when we run <code>pip install -r requirements.txt</code> it install all the packages specified in <co...
7
2016-08-18T17:00:45Z
39,023,773
<p>"Install the project found in the current directory".</p> <p>This is just a specific case of <code>pip install /path/to-source/tree</code>.</p> <hr> <p>To quote the <A HREF="https://pip.pypa.io/en/stable/reference/pip_install/#usage" rel="nofollow">the <code>pip install</code> documentation</A> describing this us...
4
2016-08-18T17:01:29Z
[ "python", "pip" ]
What's wrong with my CGBitmapContext?
39,023,856
<p>I having trouble creating a valid CGBitmapContext in python. It's just returning null values, which then causes everything else to complain about the lack of definition and python crashes. I've tried setting the memory allocation to None, which means it's supposed to sort itself out, but that doesn't work either. An...
0
2016-08-18T17:06:46Z
39,033,920
<p>The output suggested that I turn on some extra logging:</p> <pre><code>os.environ["CG_CONTEXT_SHOW_BACKTRACE"] = '1' os.environ["CGBITMAP_CONTEXT_LOG_ERRORS"] = '1' </code></pre> <p>This then gave me the following information, which is seemingly lacking from Apple's own documentation:</p> <pre><code>CGBitmapConte...
0
2016-08-19T07:58:39Z
[ "python", "osx", "core-graphics" ]
Finding words from a text document and removing the corresponding rows in dataframe - python
39,023,921
<p>I am having a table with 87 million rows and 5 columns. I have a separate file too, with around 3500 words. I want to check for the words in .txt file and check for that word in 4 columns of the table for each row. If that word is present in any of the columns, then I want to remove those rows. This would help me to...
2
2016-08-18T17:11:18Z
39,024,032
<p>You can use <code>apply</code> method to check by row and create a vector indicating whether the row contains anything in the <code>bad_words</code> using the <code>isin</code> method and then subset the original data frame based on the logic vector returned:</p> <pre><code>data[~data.apply(lambda row: row.isin(bad...
1
2016-08-18T17:18:37Z
[ "python", "string", "pandas", "data-cleaning" ]
Finding words from a text document and removing the corresponding rows in dataframe - python
39,023,921
<p>I am having a table with 87 million rows and 5 columns. I have a separate file too, with around 3500 words. I want to check for the words in .txt file and check for that word in 4 columns of the table for each row. If that word is present in any of the columns, then I want to remove those rows. This would help me to...
2
2016-08-18T17:11:18Z
39,024,230
<p>I altered your example because <code>word1</code> is technically in <code>word11</code> and <code>word12</code> and I don't think that's what you meant.</p> <h3>Setup</h3> <pre><code>from StringIO import StringIO import pandas as pd text_bad_words = """ words 0 _word1_ 1 _word3_ 2 _word5_...
1
2016-08-18T17:30:31Z
[ "python", "string", "pandas", "data-cleaning" ]
Message Box or Progess Bar While Running Program
39,023,966
<p>I've been creating a program for myself and my company recently wants to use it. However the end-users have no python experience so I'm making a GUI for them using EasyGUI. All they have to do is click a shortcut on their desktop (I'm using pythonw.exe so no box shows up). The Process takes roughly 10 seconds to run...
0
2016-08-18T17:13:57Z
39,028,953
<p>I've written a little demo for you. Don't know if it's exactly what you wanted... The code uses threading to update the progressbar while doing other stuff.</p> <pre><code>import time import threading try: import Tkinter as tkinter import ttk except ImportError: import tkinter from tkinter import tt...
0
2016-08-18T23:22:19Z
[ "python", "user-interface", "popup", "progress-bar", "easygui" ]
Can't get Hello World to work on Heroku
39,024,044
<p>I have my basic program</p> <pre><code> def test(): print("Hello World") test() </code></pre> <p>along with a Procfile.</p> <pre><code> web: python test.py </code></pre> <p>When I use a one-off dyno in the command line, I get exactly what I expect. However, when I open the app in my Heroku dash...
0
2016-08-18T17:19:37Z
39,024,825
<p>Heroku is a web hosting service; your code needs to start a web server that binds to port 80. Just running a script that terminates immediately won't do that.</p>
1
2016-08-18T18:07:57Z
[ "python", "python-2.7", "heroku" ]
lndexError: list index out of range
39,024,108
<p>I need to generate a string from random letters given in list take_from. The first time the function was executed it generated a phrase but all my following tries prompted an error "list index out of range". I can`t understand this error in my case and I tried while loop instead of for loop but it did not work eithe...
2
2016-08-18T17:23:22Z
39,024,161
<p>In Python, lists are indexed with integers ranging from 0 to 1 less than the length of the list. E.g., a list with 10 items in it would have indexes from 0 to 9. </p> <p>Your call to <code>randint()</code> attempts to get indexes from zero to the full length of the list, which will cause this exception. Change it t...
3
2016-08-18T17:26:47Z
[ "python", "list", "range" ]
lndexError: list index out of range
39,024,108
<p>I need to generate a string from random letters given in list take_from. The first time the function was executed it generated a phrase but all my following tries prompted an error "list index out of range". I can`t understand this error in my case and I tried while loop instead of for loop but it did not work eithe...
2
2016-08-18T17:23:22Z
39,024,176
<p>From the <a href="https://docs.python.org/3/library/random.html#random.randint" rel="nofollow">docs</a> </p> <blockquote> <p>random.randint(a, b)<br> Return a random integer N such that a &lt;= N &lt;= b. Alias for randrange(a, b+1). </p> </blockquote> <p>Therefore you can get values from 0 to <code>len(t...
4
2016-08-18T17:27:18Z
[ "python", "list", "range" ]
lndexError: list index out of range
39,024,108
<p>I need to generate a string from random letters given in list take_from. The first time the function was executed it generated a phrase but all my following tries prompted an error "list index out of range". I can`t understand this error in my case and I tried while loop instead of for loop but it did not work eithe...
2
2016-08-18T17:23:22Z
39,024,181
<p>You should change your loop to say:</p> <pre><code>for i in range(0, len(take_from)): </code></pre> <p>You are currently experiencing an off-by-one error because you only have 27 elements in your list, not 28.</p>
0
2016-08-18T17:27:40Z
[ "python", "list", "range" ]
lndexError: list index out of range
39,024,108
<p>I need to generate a string from random letters given in list take_from. The first time the function was executed it generated a phrase but all my following tries prompted an error "list index out of range". I can`t understand this error in my case and I tried while loop instead of for loop but it did not work eithe...
2
2016-08-18T17:23:22Z
39,024,202
<p>You could try something like this instead</p> <pre><code>from string import ascii_lowercase import random def make_a_phrase(): return ''.join(random.choice(ascii_lowercase + ' ') for i in range(28)) </code></pre>
0
2016-08-18T17:29:13Z
[ "python", "list", "range" ]
lndexError: list index out of range
39,024,108
<p>I need to generate a string from random letters given in list take_from. The first time the function was executed it generated a phrase but all my following tries prompted an error "list index out of range". I can`t understand this error in my case and I tried while loop instead of for loop but it did not work eithe...
2
2016-08-18T17:23:22Z
39,024,207
<p>The reason this happens, is because the <code>len</code> returns the length, but the last index is always the length - 1 (since indices start from 0).</p> <p>So eventually, the random integer that comes up is the length, and of course, there is no element at that number.</p> <p>Here is a simple example:</p> <pre>...
1
2016-08-18T17:29:30Z
[ "python", "list", "range" ]
D-lib object detector training
39,024,165
<p>I am trying to train an object detector using D-lib. I selected close to 100 images for training. I am using the Python environment. As per documentation, I used the Imglab tool to draw the bounding boxes across the images. Every image is almost 4000*3000 pixels in size. And then placed the generated XML file into m...
1
2016-08-18T17:26:55Z
39,024,492
<p>The testing XML file gives images and object annotations to be used to check the accuracy of your object detection. The file can be generated using imglab as with the training XML. It should contain data that is similar to, but not identical to, your training dataset.</p> <p>The <code>Killed</code> message is due...
1
2016-08-18T17:45:44Z
[ "python", "conv-neural-network", "dlib", "dlib-python" ]
Create Numpy array without enumerating array
39,024,320
<p>Starting with this:</p> <pre><code>x = range(30,60,2)[::-1]; x = np.asarray(x); x array([58, 56, 54, 52, 50, 48, 46, 44, 42, 40, 38, 36, 34, 32, 30]) </code></pre> <p>Create an array like this: (Notice, first item repeats) But if I can get this faster without the first item repeating, I can <code>np.hstack</code...
1
2016-08-18T17:35:20Z
39,024,845
<p>I got about an order of magnitude faster by avoiding <code>_stack()</code> and only using floats...</p> <p>edit: added @Divakar's post to time trial...</p> <pre><code>import numpy as np from time import time t = time() for _ in range(1000): #1000 iterations of my soln. width = 3 x = np.array(range(58,28,...
3
2016-08-18T18:09:12Z
[ "python", "arrays", "numpy" ]
Create Numpy array without enumerating array
39,024,320
<p>Starting with this:</p> <pre><code>x = range(30,60,2)[::-1]; x = np.asarray(x); x array([58, 56, 54, 52, 50, 48, 46, 44, 42, 40, 38, 36, 34, 32, 30]) </code></pre> <p>Create an array like this: (Notice, first item repeats) But if I can get this faster without the first item repeating, I can <code>np.hstack</code...
1
2016-08-18T17:35:20Z
39,024,887
<p>I suggest to contruct an initial matrix with equal columns and then use <code>np.roll()</code> to rotate them:</p> <pre><code>import numpy as np import timeit as ti import numpy.matlib x = range(30,60,2)[::-1]; x = np.asarray(x); def sol1(): # Your solution, for comparison arr = np.empty((0,5), int) ...
2
2016-08-18T18:12:14Z
[ "python", "arrays", "numpy" ]
Create Numpy array without enumerating array
39,024,320
<p>Starting with this:</p> <pre><code>x = range(30,60,2)[::-1]; x = np.asarray(x); x array([58, 56, 54, 52, 50, 48, 46, 44, 42, 40, 38, 36, 34, 32, 30]) </code></pre> <p>Create an array like this: (Notice, first item repeats) But if I can get this faster without the first item repeating, I can <code>np.hstack</code...
1
2016-08-18T17:35:20Z
39,024,908
<p><strong>Approach #1</strong></p> <p>Here's a vectorized approach using <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow"><code>NumPy broadcasting</code></a> -</p> <pre><code>N = 4 # width factor x_ext = np.concatenate((x,[None]*(N-1))) arr2D = x_ext[np.arange(N) + np.arange(x_e...
5
2016-08-18T18:13:49Z
[ "python", "arrays", "numpy" ]
Create Numpy array without enumerating array
39,024,320
<p>Starting with this:</p> <pre><code>x = range(30,60,2)[::-1]; x = np.asarray(x); x array([58, 56, 54, 52, 50, 48, 46, 44, 42, 40, 38, 36, 34, 32, 30]) </code></pre> <p>Create an array like this: (Notice, first item repeats) But if I can get this faster without the first item repeating, I can <code>np.hstack</code...
1
2016-08-18T17:35:20Z
39,026,471
<p>Starting with Divaker's padded <code>x</code></p> <pre><code>N = 4 # width factor x_ext = np.concatenate((x,[None]*(N-1))) </code></pre> <p>Since we aren't doing math on it, padding with None (which makes an object array) or <code>np.nan</code> (which makes a float) shouldn't make much difference.</p> <p>The colu...
3
2016-08-18T19:52:06Z
[ "python", "arrays", "numpy" ]