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 the other hand, if TaskB requires TaskA at some specific point in time, it should have <a href="http://luigi.readthedocs.io/en/stable/api/luigi.parameter.html#luigi.parameter.DateHourParameter" rel="nofollow">DateHourParameter()</a> itself (which is by the way preferred way to parametrize task with date and time - unless you need more precision, then take a look at <a href="http://luigi.readthedocs.io/en/stable/api/luigi.parameter.html#luigi.parameter.DateMinuteParameter" rel="nofollow">DateMinuteParameter()</a> or <a href="http://luigi.readthedocs.io/en/stable/api/luigi.parameter.html#luigi.parameter.DateSecondParameter" rel="nofollow">DateSecondParameter()</a> over two parameters one for date, another for time) and then yield requirement for TaskA with own parameter's value.</p>
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.time date_debut = pd.to_datetime('2015-08-01 23:10:00') date_fin = pd.to_datetime('2015-10-01 00:00:00') df5 = df5[(df5['TIMESTAMP'] &gt;= date_debut) &amp; (df5['TIMESTAMP'] &lt; date_fin)] df5.info() &lt;class 'pandas.core.frame.DataFrame'&gt; Int64Index: 8645 entries, 145 to 8789 Data columns (total 9 columns): TIMESTAMP 8645 non-null datetime64[ns] ACT_TIME_AERATEUR_1_F1 8645 non-null float64 ACT_TIME_AERATEUR_1_F3 8645 non-null float64 ACT_TIME_AERATEUR_1_F5 8645 non-null float64 ACT_TIME_AERATEUR_1_F6 8645 non-null float64 ACT_TIME_AERATEUR_1_F7 8645 non-null float64 ACT_TIME_AERATEUR_1_F8 8645 non-null float64 date 8645 non-null object time 8645 non-null object dtypes: datetime64[ns](1), float64(6), object(2) memory usage: 675.4+ KB </code></pre> <p>I try to resample it per day like this : </p> <pre><code>df5.index = pd.to_datetime(df5.index) df5 = df5.set_index('TIMESTAMP') df5 = df5.resample('1d').mean() </code></pre> <p>But I get a problem : </p> <blockquote> <pre><code>KeyError Traceback (most recent call last) C:\Users\Demonstrator\Anaconda3\lib\site-packages\pandas\indexes\base.py </code></pre> <p>in get_loc(self, key, method, tolerance) 1944 try: -> 1945 return self._engine.get_loc(key) 1946 except KeyError:</p> <pre><code>pandas\index.pyx in pandas.index.IndexEngine.get_loc (pandas\index.c:4154)() pandas\index.pyx in pandas.index.IndexEngine.get_loc (pandas\index.c:4018)() pandas\hashtable.pyx in pandas.hashtable.PyObjectHashTable.get_item </code></pre> <p>(pandas\hashtable.c:12368)()</p> <pre><code>pandas\hashtable.pyx in pandas.hashtable.PyObjectHashTable.get_item </code></pre> <p>(pandas\hashtable.c:12322)()</p> <pre><code>KeyError: 'TIMESTAMP' During handling of the above exception, another exception occurred: KeyError Traceback (most recent call last) &lt;ipython-input-109-bf3238788c3e&gt; in &lt;module&gt;() 1 df5.index = pd.to_datetime(df5.index) ----&gt; 2 df5 = df5.set_index('TIMESTAMP') 3 df5 = df5.resample('1d').mean() C:\Users\Demonstrator\Anaconda3\lib\site-packages\pandas\core\frame.py </code></pre> <p>in set_index(self, keys, drop, append, inplace, verify_integrity) 2835 names.append(None) 2836 else: -> 2837 level = frame[col]._values 2838 names.append(col) 2839 if drop:</p> <pre><code>C:\Users\Demonstrator\Anaconda3\lib\site-packages\pandas\core\frame.py </code></pre> <p>in <strong>getitem</strong>(self, key) 1995 return self._getitem_multilevel(key) 1996 else: -> 1997 return self._getitem_column(key) 1998 1999 def _getitem_column(self, key):</p> <pre><code>C:\Users\Demonstrator\Anaconda3\lib\site-packages\pandas\core\frame.py </code></pre> <p>in _getitem_column(self, key) 2002 # get column 2003 if self.columns.is_unique: -> 2004 return self._get_item_cache(key) 2005 2006 # duplicate columns &amp; possible reduce dimensionality</p> <pre><code>C:\Users\Demonstrator\Anaconda3\lib\site-packages\pandas\core\generic.py </code></pre> <p>in _get_item_cache(self, item) 1348 res = cache.get(item) 1349 if res is None: -> 1350 values = self._data.get(item) 1351 res = self._box_item_values(item, values) 1352 cache[item] = res</p> <pre><code>C:\Users\Demonstrator\Anaconda3\lib\site-packages\pandas\core\internals.py </code></pre> <p>in get(self, item, fastpath) 3288 3289 if not isnull(item): -> 3290 loc = self.items.get_loc(item) 3291 else: 3292 indexer = np.arange(len(self.items))[isnull(self.items)]</p> <pre><code>C:\Users\Demonstrator\Anaconda3\lib\site-packages\pandas\indexes\base.py </code></pre> <p>in get_loc(self, key, method, tolerance) 1945 return self._engine.get_loc(key) 1946 except KeyError: -> 1947 return self._engine.get_loc(self._maybe_cast_indexer(key)) 1948 1949 indexer = self.get_indexer([key], method=method, tolerance=tolerance)</p> <pre><code>pandas\index.pyx in pandas.index.IndexEngine.get_loc (pandas\index.c:4154)() pandas\index.pyx in pandas.index.IndexEngine.get_loc (pandas\index.c:4018)() pandas\hashtable.pyx in pandas.hashtable.PyObjectHashTable.get_item </code></pre> <p>(pandas\hashtable.c:12368)()</p> <pre><code>pandas\hashtable.pyx in pandas.hashtable.PyObjectHashTable.get_item </code></pre> <p>(pandas\hashtable.c:12322)()</p> <pre><code>KeyError: 'TIMESTAMP' </code></pre> </blockquote> <p>Any idea please to help me to resolve this problem?</p> <p>Kind regards</p>
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 = Generator.generate(self) </code></pre> <p>This over-simplified setup is causing a circular dependency issue. </p> <p>I generally want the ability of a class to create instances of itself (ex. for mimic-ing a parent child relationship) using a different module (generator.py in this case). </p>
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(self) </code></pre>
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 = Generator.generate(self) </code></pre> <p>This over-simplified setup is causing a circular dependency issue. </p> <p>I generally want the ability of a class to create instances of itself (ex. for mimic-ing a parent child relationship) using a different module (generator.py in this case). </p>
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> </blockquote> <p>.endswith() returns a boolean and is used to test Strings, why the hell is it giving me issues about non-integers?</p> <p>also I decided to just print everything and throw in a try/except statement if a file is not a directory or a file(cause that happend pretty quickly into the first run). it ran fine for a minute or two then started spitting out the except clause</p> <blockquote> <p>something went wrong with /sys/bus/cpu/devices/cpu0/node0/cpu0/node0/cpu0/node0/cpu0/node0/cpu0/node0/cpu0/node0/cpu0/node0/cpu0/node0/cpu0/node0/cpu0/node0/cpu0/node0/cpu0/node0/cpu0/node0/cpu1/node0/cpu0/node0/cpu1/subsystem/devices/cpu0/node0/cpu0/subsystem/devices/cpu0/subsystem/devices/cpu0/subsystem something went wrong with /sys/bus/cpu/devices/cpu0/node0/cpu0/node0/cpu0/node0/cpu0/node0/cpu0/node0/cpu0/node0/cpu0/node0/cpu0/node0/cpu0/node0/cpu0/node0/cpu0/node0/cpu0/node0/cpu0/node0/cpu1/node0/cpu0/node0/cpu1/subsystem/devices/cpu0/node0/cpu0/subsystem/devices/cpu0/subsystem/devices/cpu0 something went wrong with /sys/bus/cpu/devices/cpu0/node0/cpu0/node0/cpu0/node0/cpu0/node0/cpu0/node0/cpu0/node0/cpu0/node0/cpu0/node0/cpu0/node0/cpu0/node0/cpu0/node0/cpu0/node0/cpu0/node0/cpu1/node0/cpu0/node0/cpu1/subsystem/devices/cpu0/node0/cpu0/subsystem/devices/cpu0/subsystem/devices/cpu1/cache/power</p> </blockquote> <p>well I just Ctrl-Z’d went back into ipython3 and tried again, which immediately brought up the same message, even though the specified directory was / . why did it start back at this same area?</p> <p>edit: code </p> <pre><code>def recursive_search(dr, sf): """searches every potential path from parent directory for files with the matching suffix""" l=[]#for all the good little scripts and files with the right last name for name in os.listdir(dr):#for every item in directory path=os.path.join(dr, name)#path is now path/to/item if os.path.isfile(path): if path.endswith('.',sf)==True: l.append(path) else: #try: recursive_search(path, sf) #except: #print ('something went wrong with ', path) </code></pre> <p>if it comes out looking weird I'm having some trouble with the formatting.</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 at that position. With optional end, stop comparing S at that position. suffix can also be a tuple of strings to try. </code></pre> <p>So calling <code>"path".endswith('.',"py")</code> checks the string <code>path</code> if it ends with <code>"."</code> starting it's check from the indice <code>"py"</code>, however <code>"py"</code> is not a valid indice, hence the error.</p> <p>To check if the string ends with <code>".py"</code> you need to add the strings together instead of passing it as another argument:</p> <pre><code>path.endswith("."+sf) </code></pre>
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'\begin{eqnarray*}' +\ r'M &amp;=&amp; 0.95' + '\\\\' +\ r'\xi &amp;=&amp; 0.5' + '\\\\' +\ r'\mu &amp;=&amp; 0.1' + '\\\\' +\ r'a/b &amp;=&amp; 0' + '\\\\' +\ r'\delta_{99}/L &amp;=&amp; 0' +\ r'\end{eqnarray*}', verticalalignment='center', horizontalalignment='center') plt.savefig('output.pdf') plt.show() </code></pre> <p>The result looks like this: <a href="http://i.stack.imgur.com/5dxsQ.png" rel="nofollow"><img src="http://i.stack.imgur.com/5dxsQ.png" alt="enter image description here"></a></p> <p>How can I decrease the spacing in the vicinity of the equal signs?</p>
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 resolved I guess.</p> <p>This should give the same result:</p> <pre><code>#!/usr/bin/python import matplotlib.pyplot as plt preamble = { 'text.usetex' : True, 'font.size' : 7, 'text.latex.preamble': [ r'\usepackage{amsmath}', ], } plt.rcParams.update(preamble) fig = plt.figure(figsize=(3.,2.)) ax = fig.add_subplot(111) ax.text(0.5,0.5 ,r'\begin{align*}' +\ r'M &amp;= 0.95 \\' +\ r'\xi &amp;= 0.5 \\' +\ r'\mu &amp;= 0.1 \\' +\ r'a/b &amp;= 0 \\' +\ r'\delta_{99}/L &amp;= 0 ' +\ r'\end{align*}', verticalalignment='center', horizontalalignment='center') plt.savefig('output.pdf') plt.show() </code></pre> <p><a href="http://i.stack.imgur.com/ugDmL.png" rel="nofollow"><img src="http://i.stack.imgur.com/ugDmL.png" alt="enter image description here"></a></p>
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> header, now with the correct total length IP field.</p> <p>The pacekts seems fine but this is what I see in tcpdump:</p> <pre><code>IP host-11-0-0-10.http &gt; host-11-0-0-9.37516: Flags [R] [bad hdr length 40 - too long, &gt; 20] 0x0000: 4500 0028 9ffc 4000 4006 84ad 0b00 000a 0x0010: 0b00 0009 0050 928c 554c 31d8 0000 0000 0x0020: a004 0000 f9b3 0000 </code></pre> <p>As far as I see, the IP length is correct (0028 ==> 40 bytes ==> 20 bytes IP and 20 bytes TCP). It is as if it believes the whole header is IP or TCP but I cannot understand why.</p>
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 the TCP payload. In this case it should be 5 (20 bytes).</p> <p>40 is too long because the IP header already specified the total length of the packet, hence there are only 20 bytes left after the IP header.</p>
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; if (!PyArg_ParseTuple(args, "O", &amp;arr)) return NULL; charPtr = (char*)arr-&gt;data; printf("\n strlen of charPtr is ---&gt; %d \n", strlen(arr-&gt;data)); // ---&gt;&gt; 25313 printf("\n strlen of charPtr is ---&gt; %d \n", strlen(charPtr)); //---&gt;&gt; also 25313 back = Py_BuildValue("s", "Nice"); return back; } </code></pre> <p>In Python:</p> <pre><code>import ImageProc import cv2 import numpy import matplotlib.pyplot as plt img = cv2.imread("C:/Users/srlatch/Documents/Visual Studio 2015/Projects/PythonImage/andrew.jpg", cv2.IMREAD_GRAYSCALE) np = cv2.resize(img, (500,500)) for i in np: for k in i: count += 1 print("Size before passing to edge " + str(count) ) // ---&gt;&gt; 250000 result = ImageProc.edge(np) cv2.imshow("image", np) cv2.waitKey() </code></pre> <p>When I tried this with differently sized image I get the same result (9/10 of data is removed). </p>
-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 the pyarrayobject you need to use <code>arr-&gt;nd</code> to work out the number of dimensions then <code>arr-&gt;dimensions</code> (an array) to work out how big each dimension is. You should also use <code>arr-&gt;descr</code> to work out what data type your array is rather than just testing it as char.</p>
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 how can I remove some of the line breaks--mainly the lines that run over the page like:</p> <pre><code>Wimer John, gauger &amp; cooper, 232 N Broad, h 1511 Callowhill </code></pre> <p>If it helps any, this is pytessaract OCR text. </p> <p>Thanks,</p> <p>Cameron</p>
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/mrles Scott), saddlery hardware,"] &gt;&gt;&gt; file.close() </code></pre>
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 how can I remove some of the line breaks--mainly the lines that run over the page like:</p> <pre><code>Wimer John, gauger &amp; cooper, 232 N Broad, h 1511 Callowhill </code></pre> <p>If it helps any, this is pytessaract OCR text. </p> <p>Thanks,</p> <p>Cameron</p>
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 how can I remove some of the line breaks--mainly the lines that run over the page like:</p> <pre><code>Wimer John, gauger &amp; cooper, 232 N Broad, h 1511 Callowhill </code></pre> <p>If it helps any, this is pytessaract OCR text. </p> <p>Thanks,</p> <p>Cameron</p>
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 per record.</p> <p>Then, we can deal with the unwanted line breaks (necessarily unpaired) that are embedded within records by replacing them with <code>replace()</code>. It looks to me like some occurrences of one-off embedded line breaks are preceded by a dash, and so it may be desirable to replace <code>'-\r\n'</code> with the empty string to rejoin hyphen-wrapped pieces of text, but after that, we should replace any remaining unpaired line breaks with a single space.</p> <p>Hence we have:</p> <pre><code>import re; file = open('1128.txt'); lines = re.split('\r\n\r\n',file.read()); lines = map(lambda x: x.replace('-\s*\r\n','').replace('\r\n',' '),lines); for e in lines: print e; ## VVIL ## 1076 ## VVIN ## ## WILSTACH WILLIAM P. &amp; CO. (Wgflliam P. TVz'Zsz‘ac7z Q» C/mrles Scott), saddlery hardware, 38 N 3d ## Wilston John (c), nightwork, 917 S 9th ## Wilt Abraham, carter, 915 Coates ## Wilt Abraham, gentleman, 416 N 3d ## Wilt Alpheus, sash 3: doors, 425 N Front, h 1114 Columbia av ## Wilt Charles, blacksmith, N 40th 11 Lancaster av ## Wilt Charles, flour &amp; feed store, 1306 South ## Wilt Conrad, butcher, stall 33 Kater Market, h N W Wharton &amp; Church ## Wilt George, carter, 1135 Brown ## Wilt George A., despatcher, Reading av &amp; Richmond, h 1114 E Columbia av ## Wilt Henry, tinsmith, 888 N 2d, h 1007 Olive ## Wilt Jacob, cloak manuf., 230 Crown ## Wilt Jacob, shoemaker, 819 St John ## Wilt Jacob J., shipjoiner, 1037 Sarah ## Wilt James A., dealer in fancy goods, 230 Crown ## Wilt James G., machinist, Innes ab Allen ## Wilt John F., clerk, 528 N 2d, h 1114 Columbia av ## Wilt Joseph, chandler, 2327 Coates ## Wilt Joseph L., sheetiron worker, Lancaster av, ## Wilt Paul, heaters, 425 York av ## Wilt William, laborer, r 2325 Coates ## Wilt William, livery stable, 914 Brown, h 10th 13 Brown ## Wilt William, contractor, 719 N 10th ## Wilt William, laborer, Gordon n Cedar ## Wiltbank Daffy, washerw., 3 Price’s ct ## Wiltbank Elizabeth, widow John, 1105 Arch ## Wiltbank Elizabeth M., widow, 1521 Locust ## Wiltbank Samuel P. , broker, 1807 Delancey pl ## Wiltbank W. White, 1521 Locust ## Wiltberger A., druggist, 233 N 2d, h 329 N 5th ## Wiltberger D. S., com. mer., 220 Chestnut, h 329 N 5th _ ## Wiltberger Harry A., accountant, Market n 40th ## Wiltberger I. P.. clerk, 309 Branch ## Wiltberger Jacob H., hardware, 225 N 2d, h 711 Wallace ## Wiltberger Richard, tavern, 119 Callowhill ## Wiltberger Theodore M., Market n 40th ## Wiltberger Theodore P., clerk, Market n 40th ## \Vilter George, weaver, S E Dauphin &amp; Amber ## Wilthew Charlton, puddler, 1368 Beach ## VVimer Albert, clerk, 1224 S 6th ## Wimer Annie M., dressmaker, 34 N 8th ## Wimer Augustus, beamer, 13 Cresson, Myk ## Wimer Daniel C., carver, 1402 Mervine ## Wimer Elizabeth B., dry goods, 1511 Callowhill ## Wimer Hannah, wid. Thomas, 1041 Buttonwood ## Wimer John, gauger &amp; cooper, 232 N Broad, h 1511 Callowhill ## Wimer John A., sexton, 210 Bache ## \Vimer John C., cooper, 34 N 8th ## W'imer Joseph, collector, 1224 S 6th ## Wimer Margaret, widow Andrew, 720 S 3d ## \Vimer Wesley P., cooper, 1511 Callowhill ## Wimer William W., bookkeeper P R R 13th &amp; Market, h 1805 Callowhill ## Wimley George H., ship chandler, 512 &amp; 514 S Del av, h 244 Crown ## Wimley John, shoemaker, r 303 Brown ## Wimley William, baker, 244 Crown ## \Vimpfheimer Augustus, salesman, 400 Callowhill ## Wimpfheimer Caroline, widow Abraham, hair dresses &amp; silk nets, 402 N 2d ## Wimpfheimer David, manuf. vinegar,_431 N 3d ## W'impfheimer Jacob, leather, 318 New ## Wimpfheimer Jacob &amp; Co. (Jacob lVi-mpflzeimcr), importer, 400 Callowhill ## Wimpfheimer Joseph, jeweller, 310 N 3d ## Wimpfheimer Maxwell, bookkeeper, 431 N 3d, h 469 N 4th ## Wims Mary S., widow George, Dauphin E Carroll ## Winans Elihu M., tinsmith, 2044 Ridge av ## Winans George, painter, 2044 Ridge av ## Winans Randolph, printer, 2044 Ridge av ## Winberg William H., gentleman, 1428 Marshall ## Winberger Charles, fringes, 120 Coates ## WINCH ALDEN, newspaper ag’t, 320 Chestnut, h Arch ab 13th ## Winch C., spike ma.nuf., Beach ab Warren ## Winchell William E., sailmaker, 7 Grover ## Winchester Augustus, gents’ furnishing goods, 706 Chestnut, h 734 S 9th ## Winchester &amp; C0. (Augustus Wizzcizestcr .5, Wm. S. Marti72.), gents’ fur-’g store, 706 Chestnut ## Winchester James, weaver, Hope bel Putnam ## Winchester John, carpenter, Ridge av, Rox ## Winchester John, weaver, 1612 Philip ## Winchester John, weaver, 135 Thompson ## Winchester John, grocer, 301 Thompson ## Winchester Margaret, wid Robert, 324 Dean ## Winchester Robert, machinist, 135 Thompson ## W'inchester Samuel, merchant, 236 Market, h 258 S 10th ## Winchester William, weaver, 135 Thompson ## Winchester William W., bookkeeper, 307 Branch, h 2101 Oxford ## Windel Hannah, teacher, N 41st 11 Market ## Vllinder Ernest, carpenter, 1124 Sophia ## Winder Frederick, tailor, 1157 Passyunk rd ## Winder Harman, hotel, 926 N Front ## Winder John, driver, Daniel pl ## Winder John B., gentleman, Herman, Gtn ## Winder Joseph, hotel, 76 Frankford ## Winder Robert, carman, 906 N 12th ## Winder Sebastian, shoemaker, Ne1son’s ct ## Winder W. H., mer. 314-}; Walnut, h 415 S 15th ## Winderly Charles, shoemaker, York n Trenton av ## Winderoth Wyant, shoemaker, Champion pl ## Winderstein Frederick, shoemaker, r 1213 Apple ## Windevender David, shipjoiner, 1021 Ross ## Windish Frederick, tailor, 1129 Charlotte ## Vllindle Benjamin, file manuf. r 70 N 2d ## Windle George, salesm. 633 Market, h 1210 S 10th ## Windle William, superintendent, 1210 S 10th ## Windlerwin Julius, bootfitter, 1225 N 2d ## Windles Richard, carpenter, Oxford n Hedge ## Windner John, brickmaker, 138 Diamond ## Windorf Christian, dealer, r 832 Carpenter ## Windorf Frank, dealer, r 832 Carpenter ## Windrim James H., architect, 1518 Sansom ## Winebaker Wilhelmina, wid Charles, 320 Willow ## Wineberg Samuel, beef butcher, stalls 10 cl: 30 Girard av Market, h 944 St John ## Winebrener (K: Co. (Harry C. Wiiwbrevzer @Freclerick L. Pleis), coal dealers 3d &amp; Thompson ## Winebrener David S., hardware, 49 N 3d, h 1627 Vine ## Winebrener David, merchant, 241 S 18th ## Winebrener Harry C., coal dealer, 3d 6: Thompson, h 241 S 18th ## Wineburg John H., tanner, 535 N Front ## Winegar Francis, cabinetmaker, 117 W'alnut, h 235 Shippen ## Winegardener John, barkeeper, 9th cl: Arch, h 5th &amp; Master ## Winegar-dner Adam, laborer, r Hope 11 Canal ## Winegar-dner Andreas, tailor, 1723 N 3d ## Winegartner Anton, gentleman, 1409 Randolph ## Winehold Benjamin, driver, 1214 S 4th ## Winemore John IL, salesman, 16 S 2d, h 1110 S 2d ## Winfiller Andreas, butcher, 1410 Franklin ## Winfield Charles, shipjoiner, 120 China ## Window Shades and Curtain Goods, \‘Vholcsalc and Retail; </code></pre>
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> <p>But it doesn't help, the text from tweets is still there. Also I tried deleting separate <code>p</code> with tweets:</p> <pre><code>for s in soup('p'): try: if s["lang"]=="en": s.extract() except: pass </code></pre> <p>But it's only a partial solution - some rubbish from <code>twitterwidget</code> still remains there.. How would I get rid of that widget once and for all?</p>
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="763961058490933248" style="position: static; visibility: visible; display: block; transform: rotate(0deg); max-width: 100%; width: 500px; min-width: 220px; margin-top: 10px; margin-bottom: 10px;"&gt;&lt;/twitterwidget&gt;""" soup = BeautifulSoup(html) soup.find("twitterwidget").extract() print(soup) </code></pre> <p>Output:</p> <pre><code>&lt;html&gt;&lt;body&gt;&lt;div&gt;foobar&lt;/div&gt; &lt;/body&gt;&lt;/html&gt; </code></pre>
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/ansible/ansible-modules-extras/blob/devel/packaging/os/portinstall.py" rel="nofollow">ansible module portinstall</a> =(</p>
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> <blockquote> <p>These modules are currently shipped with Ansible, but might be shipped separately in the future. They are also mostly maintained by the community. Non-core modules are still fully usable, but may receive slightly lower response rates for issues and pull requests.</p> </blockquote> <p>As BSD is (sadly) not very popular, chances that someone will implement the functionality is not very high.</p> <p>But it is possible to work around these limitations by using the <code>command</code> module like this:</p> <pre><code>- name: Build Nginx with geoip. command: make HTTP_GEOIP=YES BATCH=yes args: chdir: /usr/ports/www/nginx/ </code></pre> <p>I would recommend to write another task to check the state / version of the port installed on the system and add a <code>when</code> clause to the task otherwise Ansible would rebuild the port on every run.</p>
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/ansible/ansible-modules-extras/blob/devel/packaging/os/portinstall.py" rel="nofollow">ansible module portinstall</a> =(</p>
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=nginx state=present </code></pre>
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/ansible/ansible-modules-extras/blob/devel/packaging/os/portinstall.py" rel="nofollow">ansible module portinstall</a> =(</p>
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 text boxes. </p> <p>The ultimate goal is to visually display an XML file and allow a user to directly edit only element text and nothing else in-situ. I have a couple of other ways of doing this but they are very much sub-optimal. </p> <p>Thanks for any input/direction/help.</p>
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 like a tough task, though... :-)</p>
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 a django template?</a> is almost there, but i dont know how to send my two field names as a string.</p> <p>my template:</p> <pre><code> &lt;th&gt;{{ item.cost_per_month|remaining_cost:item.install_date + ',' + item.contract_length }}&lt;/th&gt; </code></pre> <p>the above didnt work</p> <p>my template tags:</p> <pre><code>@register.filter('contract_remainder') def contract_remainder(install_date, contract_term): months = 0 now = datetime.now().date() end_date = install_date + relativedelta(years=contract_term) while True: mdays = monthrange(now.year, now.month)[1] now += timedelta(days=mdays) if now &lt;= end_date: months += 1 else: break return months @register.filter('remaining_cost') def remaining_cost(cost_per_month, remainder_vars): dates = remainder_vars.split(',') cost = contract_remainder(dates[0], dates[1]) * cost_per_month return cost </code></pre>
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/#simple-tags</a></p> <p>Your template would be just :</p> <pre><code>&lt;th&gt;{% remaining_cost item.cost_per_month item.install_date item.comtract_length&lt;th&gt; %} </code></pre> <p>and the template tag would be:</p> <pre><code>@register.simple_tag def remaining_cost(cost_per_month, install_date, contract_length): cost = contract_remainder(install_date, contract_length) * cost_per_month return cost </code></pre>
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><code>pwd </code></pre> <p>yields</p> <blockquote> <p>/quake/home/name/docs/research/Y2/results/s8</p> </blockquote> <p>which is an alias to the first path. Why are they inconsistent?</p>
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 physical path, resolving any symlinks:</p> <pre><code>~/src/stackoverflow $ mkdir targetdir ~/src/stackoverflow $ ln -s targetdir symlink ~/src/stackoverflow $ cd symlink ~/src/stackoverflow/symlink $ ~/src/stackoverflow/symlink $ python &gt;&gt;&gt; import os &gt;&gt;&gt; import subprocess &gt;&gt;&gt; import shlex &gt;&gt;&gt; &gt;&gt;&gt; path = subprocess.check_output('pwd').strip() &gt;&gt;&gt; path '/Users/lukasgraf/src/stackoverflow/symlink' &gt;&gt;&gt; os.path.realpath(path) '/Users/lukasgraf/src/stackoverflow/targetdir' </code></pre> <hr> <p>There is also the <code>-P</code> option to the <code>pwd</code> command that enforces this.</p> <p>From the <code>pwd</code> man page (on OS X):</p> <blockquote> <p>The pwd utility writes the absolute pathname of the current working directory to the standard output.</p> <p>Some shells may provide a builtin pwd command which is similar or identical to this utility. Consult the builtin(1) manual page.</p> <pre><code> The options are as follows: -L Display the logical current working directory. -P Display the physical current working directory (all symbolic links resolved). If no options are specified, the -L option is assumed. </code></pre> </blockquote> <p>So this would work too:</p> <pre><code>&gt;&gt;&gt; subprocess.check_output(shlex.split('pwd -P')) '/Users/lukasgraf/src/stackoverflow/targetdir\n' &gt;&gt;&gt; </code></pre> <hr> <p>However, the best option is to use <a href="https://docs.python.org/2/library/os.html#os.getcwd" rel="nofollow"><code>os.getcwd()</code></a> from the Python standard library:</p> <pre><code>&gt;&gt;&gt; os.getcwd() '/Users/lukasgraf/src/stackoverflow/targetdir' </code></pre> <p>It's not explicitly documented, but it seems to already resolve symlinks for you. In any case, you will want to avoid shelling out (using <code>subprocess</code>) for something that the standard library already provides for you, like getting the current working directory.</p>
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'].str.split(',',expand=True) train_df2=train_df1[1].str.split(' ',expand=True)[1] </code></pre> <p>train_df contains the variable 'Name'</p>
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] </code></pre>
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'].str.split(',',expand=True) train_df2=train_df1[1].str.split(' ',expand=True)[1] </code></pre> <p>train_df contains the variable 'Name'</p>
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'].str.split(',',expand=True) train_df2=train_df1[1].str.split(' ',expand=True)[1] </code></pre> <p>train_df contains the variable 'Name'</p>
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'].str.split(',',expand=True) train_df2=train_df1[1].str.split(' ',expand=True)[1] </code></pre> <p>train_df contains the variable 'Name'</p>
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> <pre><code>filt = np.array([0.25,0.5,0.25]) w, h=signal.freqz(filt) </code></pre> <p>And I thought that for a repeating filter, I just need to multiply h by itself for many times (since it's in frequency domain, and filtering is just convolution.)</p> <p>However, I cannot get the same plot as they did in the paper. I have three major questions,</p> <ol> <li><p>I thought the 1-2-1 filter is just the triangle filter, is there other way to check its response in frequency domain?</p></li> <li><p>How to check its frequency response for a repeating 1-2-1 filter in python? Isn't it just h times itself for multiple times?</p></li> <li><p>I have hard time understanding the w(normalized frequency) unit in the freqz output. Could some one explain to me how to convert to wavenumber as in the plot?</p></li> </ol> <p>Thank you.</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.5,0.25]) w, h=signal.freqz(filt) plt.plot(w/(2*pi), abs(h**400), label='400 pass') </code></pre> <p><a href="http://i.stack.imgur.com/JKqRU.png" rel="nofollow">Comparison between frequency response of repeating 1-2-1 filter</a></p>
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 import items </code></pre> <p>Which didn't work. I also tried</p> <pre><code>#File:sub.py from dir_one.main import items </code></pre> <p>which also didn't work.</p> <p>Is there a way to import the <code>main.py</code> file from <code>sub.py</code>? Do I need to edit the <code>__init__.py</code> given that it is empty?</p>
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 sub.py </code></pre> <p>before using your items form main.</p> <p>Edit: In your specific case <code>'path/to/dir_one'</code> would simply be one directory upwards, i.e. <code>'..'</code></p>
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 import items </code></pre> <p>Which didn't work. I also tried</p> <pre><code>#File:sub.py from dir_one.main import items </code></pre> <p>which also didn't work.</p> <p>Is there a way to import the <code>main.py</code> file from <code>sub.py</code>? Do I need to edit the <code>__init__.py</code> given that it is empty?</p>
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 package and it creates a script to call it. Nifty...</p> <p>In playing around with this, I've set up the following package structure:</p> <pre><code>test_dir + __init__.py + main.py + sub1 --+ __init__.py --+ script.py + sub2 --+ __init__.py --+ module.py </code></pre> <p>and I've made sure that <code>test_dir</code> is accessible via <code>PYTHONPATH</code>.</p> <p>The scripts are all super simple (just printing some stuff):</p> <pre><code># main.py def func_in_main(): print("Hello from main.py!") # module.py def run_func(): print("Hello from script in sub2.py!") # script.py from ..sub2 import module from .. import main def entry_point(): module.run_func() main.func_in_main() if __name__ == '__main__': entry_point() </code></pre> <p>Now, what happens if I try to run this directly?</p> <pre><code>$ python test_package/test_dir/sub1/script.py Traceback (most recent call last): File "test_package/test_dir/sub1/script.py", line 2, in &lt;module&gt; from ..sub2 import module ValueError: Attempted relative import in non-package </code></pre> <p>Hmm ... Bummer (this is the case that I was trying to describe in the comments on your original question). This happens regardless of my current working directory by the way ... However, from anywhere on my filesystem, I <em>can</em> run this using the <code>-m</code> flag<sup>1</sup>:</p> <pre><code>$ python -m test_dir.sub1.script Hello from script in sub2.py! Hello from main.py! </code></pre> <p>Horray! We only need to specify the module path and then we're golden (remember, <code>test_dir</code> <strong>MUST</strong> be reachable via your PYTHONPATH for this to work). Ok, but what if we really want to call the script instead of using the module path? If this is the case, we can modify the <code>__package__</code> variable before we do any importing:</p> <pre><code># script.py (updated) if __name__ == '__main__' and __package__ is None: __package__ = 'test_dir.sub1' import test_dir # needed to suppress SystemError -- I'm not sure why... from .. import main from ..sub2 import module def entry_point(): module.run_func() main.func_in_main() if __name__ == '__main__': entry_point() </code></pre> <p>Now lets try to run this thing directly again:</p> <pre><code>$ python test_package/test_dir/sub1/script.py test_package/test_dir/sub1/script.py:4: RuntimeWarning: Parent module 'test_dir.sub1' not found while handling absolute import import test_dir Hello from script in sub2.py! Hello from main.py! </code></pre> <p>We still get a <code>RuntimeWarning</code>, but it runs Ok. For more details, have a look at <a href="https://www.python.org/dev/peps/pep-0366/" rel="nofollow">PEP-0366</a>.</p> <p><sup><sup>1</sup>In general, I've run most of these from outside the package (one level above <code>test_dir</code>), but the examples work if I run it from <em>inside</em> the package as well. with <code>-m</code> you always specify the full path to the module (<code>test_dir.sub1.script</code>), without it, you just specify the relative or absolute path to the file)</sup></p>
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 (path:/tmp/pip-build-hdy25apc/easydict/setup.py) egg_info for package easydict Installing collected packages: easydict Running setup.py install for easydict Could not find .egg-info directory in install record for easydict Successfully installed easydict Cleaning up... sudo pip install easydict Requirement already satisfied (use --upgrade to upgrade): easydict in /usr/local/lib/python3.4/dist-packages Cleaning up... </code></pre> <p>Why does this happen? Thank you very much.</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? Like,</p> <pre><code>fig = plt.figure() xs, ys = meshgrid(linspace(-5, 5, n), linspace(-5, 5, n)) vs = 1/sqrt(xs**2 + ys**2) ax = fig.add_subplot(1, 1, 1, aspect='equal') fig.colorbar(ax.pcolor(xs,ys,vs, vmin=0, vmax=1)) </code></pre> <p><a href="http://i.stack.imgur.com/1lqLh.png" rel="nofollow"><img src="http://i.stack.imgur.com/1lqLh.png" alt="The function plot without the excluded domain."></a></p> <p>but with the center area blank instead of deep-red.</p> <p><a href="http://i.stack.imgur.com/LXJTb.png" rel="nofollow"><img src="http://i.stack.imgur.com/LXJTb.png" alt="Center erased"></a></p>
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"></a></p> <p>matplotlib has a more complicated example <a href="http://matplotlib.org/examples/pylab_examples/image_masked.html" rel="nofollow">image_masked.py</a> where you can select the color for masked zones. To convert between an ordinary array and a masked array you can use one of the <a href="http://docs.scipy.org/doc/numpy/reference/maskedarray.generic.html#constructing-masked-arrays" rel="nofollow">numpy.ma.masked_*</a> functions </p>
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? Like,</p> <pre><code>fig = plt.figure() xs, ys = meshgrid(linspace(-5, 5, n), linspace(-5, 5, n)) vs = 1/sqrt(xs**2 + ys**2) ax = fig.add_subplot(1, 1, 1, aspect='equal') fig.colorbar(ax.pcolor(xs,ys,vs, vmin=0, vmax=1)) </code></pre> <p><a href="http://i.stack.imgur.com/1lqLh.png" rel="nofollow"><img src="http://i.stack.imgur.com/1lqLh.png" alt="The function plot without the excluded domain."></a></p> <p>but with the center area blank instead of deep-red.</p> <p><a href="http://i.stack.imgur.com/LXJTb.png" rel="nofollow"><img src="http://i.stack.imgur.com/LXJTb.png" alt="Center erased"></a></p>
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 to the nan ones:</p> <pre><code>vs[np.isnan(vs)] = np.min(vs[~np.isnan(vs)]) - 1 </code></pre> <p>Using a cmap other than than the defult, like 'hot' really shows the hole in the middle.</p>
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? Like,</p> <pre><code>fig = plt.figure() xs, ys = meshgrid(linspace(-5, 5, n), linspace(-5, 5, n)) vs = 1/sqrt(xs**2 + ys**2) ax = fig.add_subplot(1, 1, 1, aspect='equal') fig.colorbar(ax.pcolor(xs,ys,vs, vmin=0, vmax=1)) </code></pre> <p><a href="http://i.stack.imgur.com/1lqLh.png" rel="nofollow"><img src="http://i.stack.imgur.com/1lqLh.png" alt="The function plot without the excluded domain."></a></p> <p>but with the center area blank instead of deep-red.</p> <p><a href="http://i.stack.imgur.com/LXJTb.png" rel="nofollow"><img src="http://i.stack.imgur.com/LXJTb.png" alt="Center erased"></a></p>
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.pyplot as plt n = 100 fig = plt.figure() xs, ys = meshgrid(linspace(-5, 5, n), linspace(-5, 5, n)) vs = vectorize(coulomb) (xs, ys) vs = ma.masked_where(isnan(vs), vs) ax = fig.add_subplot(1, 1, 1, aspect='equal') fig.colorbar(ax.pcolor(xs,ys,vs, vmin=0, vmax=1)) </code></pre>
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></pre> <p>How do I do this?</p>
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></pre> <p>How do I do this?</p>
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><a href="http://i.stack.imgur.com/ZWSGQ.png" rel="nofollow"><img src="http://i.stack.imgur.com/ZWSGQ.png" alt="enter image description here"></a></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): self.surface = surface self.magnitude = magnitude def __eq__(self, otherSize): try: a = self.magnitude == otherSize.magnitude and self.surface == otherSize.surface except: print('Wrong type of atributes') return a class Dreieck(Size,Shape): def __init__(self,center,name,surface,magnitude,a,b,c): Shape.__init__(self,center,name) Size.__init__(self,surface,magnitude) Dreieck.a = a Dreieck.b = b Dreieck.c = c def pitagoras(self): if self.a+self.b==self.c and self.a**2 + self.b**2 == self.c**2: return True else: return False def __add__(self,otherDreieck): return Dreieck(self.center, self.__name, self.surface, self.magnitude,self.a+otherDreieck.a, self.b+otherDreieck.b, self.c+otherDreieck.b) </code></pre> <p>I am doing a simple example of multiple inheritance in Python, and I can't find why by adding two objects of class <code>Dreieck</code> I get an <code>AttributeError 'Dreieck' object has no attribute 'name'</code>. I suppose it is because the <code>name</code> attribute is private, but I thought I was inheriting it here:</p> <pre><code>Shape.__init__(self,center,name) </code></pre>
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 words try referencing it as <code>self._Shape__name</code>.</p>
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 randint class Scene(object): def enter(self): print("Scene not configured") exit(1) class Engine(object): def __init__(self, scene_map): self.scene_map = scene_map def play(self): current_scene = self.scene_map.opening_scene() last_scene = self.scene_map.next_scene('finished') while current_scene != last_scene: next_scene_name = current_scene.enter() current_scene = self.scene_map.next_scene(next_scene_name) class Death(Scene): quips = [ "Your dead", "rekt", "super rekt"] def enter(self): print(Death.quips[randint(0, len(self.quips)-1)]) exit(1) class Corridor(Scene): def enter(self): print("\nYou've a gun and stuff, what will you do? Shoot/Leg it") action = input("\n&gt;&gt; ") if action == "Shoot": print("\nYou killed someone, good stuff") print("You get into the armory.") return 'laser_weapon_armory' elif action == "Leg it": print("\nYou get shot before you get away.") return 'death' else: print("\nThat was not an option") return 'central_corridor' class LaserWeaponArmory(Scene): def enter(Self): print("\nRight, you're in the armory.") print("There's a lock on the next door. \nEnter 3 digits to unlock") code = "%d%d%d" % (randint(1,9), randint(1,9), randint(1,9)) guess = input("\n &gt;&gt; ") guesses = 0 while guess != code and guesses &lt; 10: print("\nDENIED") guesses += 1 guess = input("\n &gt;&gt; ") if guess == code: print("\nDoor opens.") print("You enter the bridge.") return 'the_bridge' else: print("\nDoor remains locked. You get killed") Death() class TheBridge(Scene): def enter(Self): print("\nYou're in the bridge.") print("There's a bomb. What do you do?") print("Defuse/Run away") action = input("\n &gt;&gt; ") if action == 'Defuse': print("\nYou failed, bomb goes off") return 'death' elif action == 'Run away': print("\nYou get in the escape pod bay.") return 'escape_pod' else: print("\nThat was not an option.") Death() class EscapePod(Scene): def enter(self): print("\nThere's 5 pods, which do you take?") good_pod = randint(1.5) pod = input("\n&gt;&gt;Pod #") if int(pod) != good_pod: print("\nThis pod is fucked.") Death() else: print("\nYurt, the pod works. You're out of here kid.") return 'finished' class Finished(Scene): def enter(self): print("\nGame over. Go away.") return 'finished' class Map(object): scenes = { 'central_corridor': Corridor(), 'laser_weapon_armory': LaserWeaponArmory(), 'the_bridge': TheBridge(), 'escape_pod': EscapePod(), 'finished': Finished(), } def __init__(self, start_scene): self.start_scene = start_scene print("start_scene in __init__", self.start_scene) def next_scene(self, scene_name): val = Map.scenes.get(scene_name) return val def opening_scene(self): return self.next_scene(self.start_scene) a_map = Map('central_corridor') a_game = Engine(a_map) a_game.play() </code></pre> <p>Error;</p> <pre><code>Traceback (most recent call last): File "C:\Python\Shtuff\game.py", line 143, in &lt;module&gt; a_game.play() File "C:\Python\Shtuff\game.py", line 20, in play next_scene_name = current_scene.enter() AttributeError: 'NoneType' object has no attribute 'enter' </code></pre> <p>I'm very new to Python, mostly understand Classes and all that though. As far as I can see this is exactly like the code in LPTHW. Two of the answers I've seen for this exact problem I have in my code so can't see where I'm going wrong. Could it be something got to do with me using Python3 and LPTHW all about Python 2.XX?</p>
-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 of these methods return <code>'death'</code> (see <code>Corridor</code> and <code>TheBridge</code>, for example). Then this return value is used as a key for <code>Map.scenes</code>. But there's no <code>'death'</code> key there, so it's returning <code>None</code>.</p> <hr> <p>By the way, <code>self</code> and <code>Self</code> are quite different, but you're using both and expecting them to do the same thing. </p>
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 = ['google', 'program', 'can'] </code></pre> <p>output will be,</p> <pre><code>can google employees because google is a technology company that writes program </code></pre> <p>Here's my approach, Split the document into suffix tree, check for all strings in each suffix return the one of the shortest length,</p> <p>Here's my code</p> <pre><code>def snippetSearch(document, searchTerms): doc = document.split() suffix_array = create_suffix_array(doc) current = None current_len = sys.maxsize for suffix in suffix_array: if check_for_terms_in_array(suffix, searchTerms): if len(suffix) &lt; current_len: current_len = len(suffix) current = suffix return ' '.join(map(str, current)) def create_suffix_array(document): suffix_array = [] for i in range(len(document)): sub = document[i:] suffix_array.append(sub) return suffix_array def check_for_terms_in_array(arr, terms): for term in terms: if term not in arr: return False return True </code></pre> <p>This is an online submission and it's not passing one test case. I have no idea what the test case is though. My question is, is there anything logically incorrect with the code. Also is there a more efficient way of doing this.</p>
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 in search_terms) ) shortest = doc for candidate in substrings: if len(candidate) &lt; len(shortest): shortest = candidate return shortest. document = 'many google employees can program can google employees because google is a technology company that writes program' search_terms = ['google', 'program', 'can'] print find_shortest(document, search_terms) &gt;&gt;&gt;&gt; ['program', 'can', 'google'] </code></pre> <p>You can probably do this a lot faster, though. For example, any relevant substring can only end with one of the keywords</p>
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 = ['google', 'program', 'can'] </code></pre> <p>output will be,</p> <pre><code>can google employees because google is a technology company that writes program </code></pre> <p>Here's my approach, Split the document into suffix tree, check for all strings in each suffix return the one of the shortest length,</p> <p>Here's my code</p> <pre><code>def snippetSearch(document, searchTerms): doc = document.split() suffix_array = create_suffix_array(doc) current = None current_len = sys.maxsize for suffix in suffix_array: if check_for_terms_in_array(suffix, searchTerms): if len(suffix) &lt; current_len: current_len = len(suffix) current = suffix return ' '.join(map(str, current)) def create_suffix_array(document): suffix_array = [] for i in range(len(document)): sub = document[i:] suffix_array.append(sub) return suffix_array def check_for_terms_in_array(arr, terms): for term in terms: if term not in arr: return False return True </code></pre> <p>This is an online submission and it's not passing one test case. I have no idea what the test case is though. My question is, is there anything logically incorrect with the code. Also is there a more efficient way of doing this.</p>
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 range(len(document)): # Second level of looping tests current length at valid positions for y in range(max(len(document), len(document)-x)): if some_property(document[y:x+y]): return document[y:x+y] # How to handle the case of no match is undefined raise ValueError('No matching value found') </code></pre> <p>Now the property we want to test for itself:</p> <pre><code>def contains_all_terms(terms): return (lambda s: all(term in s for term in terms)) </code></pre> <p>This <code>lambda</code> expression takes some terms and will return a function which, when evaluated on a string, returns true if and only if all the terms are in the string. This is basically a more terse version of a nested function definition which you could write like this:</p> <pre><code>def contains_all_terms(terms): def string_contains_them(s): return all(term in s for term in terms) return string_contains_them </code></pre> <p>So we're actually just returning the handle of the function we create dynamically inside of our <code>contains_all_terms</code> function</p> <p>To piece this together we do like so:</p> <pre><code>&gt;&gt;&gt; find_shortest_ss(document, contains_all_terms(searchTerms)) 'program can google' </code></pre> <p>Some efficiency advantages which this code has:</p> <ol> <li><p>The <code>any</code> builtin function has short-circuit evaluation, meaning that it will return <code>False</code> as soon as it finds a non-contained substring</p></li> <li><p>It starts by checking all the shortest substrings, then proceeds to increase substring length one extra character length at a time. If it ever finds a satisfying substring it will exit and return that value. So you can guarantee the returned value will never be longer than necessary. It won't even be doing any operations on substrings longer than necessary.</p></li> <li><p>8 lines of code, not bad I think</p></li> </ol>
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 = ['google', 'program', 'can'] </code></pre> <p>output will be,</p> <pre><code>can google employees because google is a technology company that writes program </code></pre> <p>Here's my approach, Split the document into suffix tree, check for all strings in each suffix return the one of the shortest length,</p> <p>Here's my code</p> <pre><code>def snippetSearch(document, searchTerms): doc = document.split() suffix_array = create_suffix_array(doc) current = None current_len = sys.maxsize for suffix in suffix_array: if check_for_terms_in_array(suffix, searchTerms): if len(suffix) &lt; current_len: current_len = len(suffix) current = suffix return ' '.join(map(str, current)) def create_suffix_array(document): suffix_array = [] for i in range(len(document)): sub = document[i:] suffix_array.append(sub) return suffix_array def check_for_terms_in_array(arr, terms): for term in terms: if term not in arr: return False return True </code></pre> <p>This is an online submission and it's not passing one test case. I have no idea what the test case is though. My question is, is there anything logically incorrect with the code. Also is there a more efficient way of doing this.</p>
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 writes program' searchTerms = ['google', 'program'] word_lists = [] for word in searchTerms: word_positions = [] start = 0 #starting index of str.find() while 1: start = document.find(word, start, -1) if start == -1: #no more instances break word_positions.append([start, start+len(word)]) #beginning and ending index of search term start += 1 #increment starting search postion word_lists.append(word_positions) #add all search term positions to list of all search terms minLen = len(document) lower = 0 upper = len(document) for p in product(*word_lists): #unpack word_lists into word_positions indexes = np.array(p).flatten() #take all indices into flat list lowerI = np.min(indexes) upperI = np.max(indexes) indexRange = upperI - lowerI #determine length of substring if indexRange &lt; minLen: minLen = indexRange lower = lowerI upper = upperI print document[lower:upper] </code></pre>
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 created an <strong>init</strong>.py file in the 'views' folder.</p> <p>My folder structure:</p> <pre><code>myproject/ myproject/ ... ... myapp/ __init__.py urls.py views/ __init__.py viewsa.py </code></pre> <p>The first problem is in myapp/views/<strong>init</strong>.py I tried to do this:</p> <pre><code>from viewsa import * </code></pre> <p>and I get an "unresolved reference viewsa" error</p> <p>I <em>can</em> however do this in the same file instead (in other words, it doesn't throw an error):</p> <pre><code>from . import viewsa </code></pre> <p>But I can't find any way to import these sub directory views into myapp/urls.py even following the directions in the link above. What am I doing wrong?</p>
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 having trouble parsing, but that is a separate issue).</p> <p>If I ignore the <code>MessageContainer</code> object and simply request the next response from the server I receive the expected <code>FutureSalts</code> object.</p> <p>Will there always be a <code>MessageContainer</code> object returned for each method called? If so, do I need to parse and process these <code>MessageContainer</code> objects?</p>
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 machine app.window("Trade Monitor") #error </code></pre>
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() </code></pre> <p>My test runs successful. And one more thing! If after my print command I'm putting some string which leads my test to the crash, I can see print with all other crash information.</p>
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 that I've got my head on right (sorry for the idiot first response), let's take a look at the problem. First things first, when using Selenium and python, I always create a driver object to pass my handle around like so:</p> <p><code>driver = webdriver.Chrome()</code></p> <p>Secondly, if you happen to know the ID of the element, you can use <code>driver.find_element_by_id('locator')</code>. It's a bit more explicit in my opinion if you care to use it. The big thing though is the first point where you create a driver object. Try giving that a shot and let me know if it's still not working. :-)</p>
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 example Translation or Rotation in images, meanwhile I am using scipy functions in CPU using Numpy but it is quite slow. </p>
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 translations, you can just use <a href="http://deeplearning.net/software/theano/library/tensor/basic.html#theano.tensor.roll" rel="nofollow"><code>theano.tensor.roll</code></a> followed by some masking. If you want the rotations as well, take a look at <a href="https://github.com/skaae/transformer_network/blob/master/transformerlayer.py" rel="nofollow">this implementation of spatial transformer network</a>. In particular take a look at the <code>_transform</code> function, it takes as an input a matrix theta that has a 2x3 transformation (left 2x2 is rotation, and right 1x2 is translation) one per sample and the actual samples, and applies the rotation and translation to those samples. I didn't confirm that what it does is optimized for the GPU (i.e. it could be that the bottleneck of that function is executed on the CPU, which will make it not appropriate for your use case), but it's a good starting point.</p>
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 list of applicant names.</p> <p>Here's what the dictionary looks like, and unfortunately I don't have any control over how it's created initially.</p> <pre><code>{u'bids': [{u'applicantId': 221, u'Name': u'name name', u'bidID': 2}, {u'applicantId': 356, u'Name': u'name name', u'bidID': 5}, {u'applicantId': 240, u'Name': u'name name', u'bidID': 9}], u'job': {u'address': u'6 something St', u'bids': None, u'budget': 30.0, u'jobID': 10}} </code></pre> <p>So I'd like a user to give me the JobID and it will output a list of the names of the people who applied. </p> <p>Any help here? </p>
-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[JobID]['bids']] </code></pre>
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 function or broadcasting trick to do this without using a for loop or other iterator?</p>
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 a file with multiple unit test classes.</p>
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 sure if that's exactly what you are looking for but I beat my head against a brick wall for days trying to get nosetests to cooperate with no luck. Maybe it would save some effort to switch and run <code>coverage.py</code> directly instead?</p>
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 that device, and I have to do the same thing again until it moves onto the next non Cisco device. I have no idea how to get around this. My output looks like the following:</p> <pre><code> [xxx.xxx.xxx.xxx] Executing task 'execute_commands' [xxx.xxx.xxx.xxx] run: show running-config ntp [xxx.xxx.xxx.xxx] out: Type help or '?' for a list of available commands. [xxx.xxx.xxx.xxx] out: [xxx.xxx.xxx.xxx] out: user12345# show running-config ntp </code></pre> <p>I think it may have something to do with the "Type help or '?' for a list of available commands." portion of it. That is standard on cisco devices after the banner...</p>
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 headers): reader = csv.DictReader(csvfile, fieldnames=headers) break </code></pre> <p>which works great. </p> <p>But I would rather not have to keep the file open in order to use my data. Is there elegant way, that will just put my data in RAM rather than needing the file to be open?</p> <p>Ideally I would like to be able to just close the file, and then be able to access my data doing something like this</p> <pre><code>table['name']['address'] </code></pre>
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 csv.DictReader(csvfile, fieldnames=headers): name_row = table.get(row['name'], {}) name_row[row['name']] = row['address'] </code></pre>
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 print(vid_title) for stream in streams: print(stream) print'Resolution: ',best.resolution,'\nExtension : ', best.extension user_choice = raw_input("Do you want to download this video\ny or n\n") if user_choice == 'y': print'Your video will downloaded soon' filename = best.download(filepath = '/home/mark/new_projects') another_download() elif user_choice =='n': print'You have chosen not to download a video' another_download() def another_download(): another_choice = raw_input('Would you like to download another video\ny or n\n') if another_choice == 'y': download() else: print'Thank for using my program' download() </code></pre> <p>I would like to break it down into smaller functions. I have tried to do this:</p> <pre><code>def url(): 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 print(vid_title) for stream in streams: print(stream) print'Resolution: ',best.resolution,'\nExtension : ', best.extension def download(): user_choice = raw_input("Do you want to download this video\ny or n\n") if user_choice == 'y': print'Your video will downloaded soon' filename = best.download(filepath = '/home/mark/new_projects') another_download() elif user_choice =='n': print'You have chosen not to download a video' another_download() </code></pre> <p>But when I try this I get an error telling me that best has not been declared. I don't want to declare best as a global variable. Is there a way of using a variable from one function inside another function?</p>
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 download n vids you'll have n * 2 - 1 functions hanging around until the last one finish. </p> <p>Incidentally return solves your problem :</p> <pre><code>def url(): ... return best def download(): best = url() ... </code></pre>
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 print(vid_title) for stream in streams: print(stream) print'Resolution: ',best.resolution,'\nExtension : ', best.extension user_choice = raw_input("Do you want to download this video\ny or n\n") if user_choice == 'y': print'Your video will downloaded soon' filename = best.download(filepath = '/home/mark/new_projects') another_download() elif user_choice =='n': print'You have chosen not to download a video' another_download() def another_download(): another_choice = raw_input('Would you like to download another video\ny or n\n') if another_choice == 'y': download() else: print'Thank for using my program' download() </code></pre> <p>I would like to break it down into smaller functions. I have tried to do this:</p> <pre><code>def url(): 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 print(vid_title) for stream in streams: print(stream) print'Resolution: ',best.resolution,'\nExtension : ', best.extension def download(): user_choice = raw_input("Do you want to download this video\ny or n\n") if user_choice == 'y': print'Your video will downloaded soon' filename = best.download(filepath = '/home/mark/new_projects') another_download() elif user_choice =='n': print'You have chosen not to download a video' another_download() </code></pre> <p>But when I try this I get an error telling me that best has not been declared. I don't want to declare best as a global variable. Is there a way of using a variable from one function inside another function?</p>
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_input('Please enter the path to the video\n') video = pafy.new(url) vid_title = video.title best = video.getbest() streams = video.streams print(vid_title) for stream in streams: print(stream) print'Resolution: ',best.resolution,'\nExtension : ', best.extension return best def download(): user_choice = raw_input("Do you want to download this video\ny or n\n") if user_choice == 'y': best = url() print'Your video will downloaded soon' filename = best.download(filepath = '/home/mark/new_projects') another_download() elif user_choice =='n': print'You have chosen not to download a video' another_download() </code></pre> <p>Option 2: You could use global variables, though I don't know the ramifications of using them in this case:</p> <pre><code>best = None def url(): global best 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 print(vid_title) for stream in streams: print(stream) print'Resolution: ',best.resolution,'\nExtension : ', best.extension def download(): global best user_choice = raw_input("Do you want to download this video\ny or n\n") if user_choice == 'y': print'Your video will downloaded soon' filename = best.download(filepath = '/home/mark/new_projects') another_download() elif user_choice =='n': print'You have chosen not to download a video' another_download() </code></pre> <p>I think either of these solutions will give you what you want, but I would recommend the first in this specific case as it doesn't seem like a complex program.</p>
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 first column but I can't seem to figure out why I cant apply it ti multiple columns.</p> <p>I am getting the following error attempting to execute the second line:</p> <pre><code> File "C:/Users/anshanno/PycharmProjects/RETIvizScript/RetiViz.py", line 271, in join_groups group_df['resolved_on'] = pd.DatetimeIndex(group_df['resolved_on']).to_period('d') File "C:\Python27\lib\site-packages\pandas\util\decorators.py", line 91, in wrapper return func(*args, **kwargs) File "C:\Python27\lib\site-packages\pandas\tseries\index.py", line 349, in __new__ values, freq=freq, dayfirst=dayfirst, yearfirst=yearfirst) File "pandas\tslib.pyx", line 2347, in pandas.tslib.parse_str_array_to_datetime (pandas\tslib.c:42450) ValueError </code></pre> <p>Since the ValueError isn't telling me anything, I tried <code>errors='coerce'</code> without any luck - I still get the same undescriptive error.</p> <pre><code>group_df['resolved_on'] = pd.DatetimeIndex(group_df['resolved_on'], errors='coerce').to_period('d') </code></pre> <p>Edit (Sample Data):</p> <pre><code>"identifier","status","submitted_on","resolved_on","closed_on","duplicate_on","junked_on","unproducible_on","verified_on" "xx1","D","2004-07-28 07:00:00.0","null","null","2004-08-26 07:00:00.0","null","null","null" "xx2","N","2010-03-02 03:00:16.0","null","null","null","null","null","null" "xx3","U","2005-10-26 14:20:20.0","null","null","null","null","2005-11-01 13:02:22.0","null" "xx4","V","2006-06-30 07:00:00.0","2006-09-15 07:00:00.0","null","null","null","null","2006-11-20 08:00:00.0" "xx5","R","2012-09-21 06:30:58.0","2013-06-06 09:35:25.0","null","null","null","null","null" "xx6","D","2009-11-25 02:16:03.0","null","null","2010-02-26 12:28:22.0","null","null","null" "xx7","D","2003-08-29 07:00:00.0","null","null","2003-08-29 07:00:00.0","null","null","null" "xx8","R","2003-06-06 12:00:00.0","2003-06-24 12:00:00.0","null","null","null","null","null" "xx9","R","2004-11-05 08:00:00.0","2004-11-15 08:00:00.0","null","null","null","null","null" "xx10","R","2008-02-21 05:13:39.0","2008-09-25 17:20:57.0","null","null","null","null","null" "xx11","R","2007-03-08 17:47:44.0","2007-03-21 23:47:57.0","null","null","null","null","null" "xx12","R","2011-08-22 19:50:25.0","2012-06-21 05:52:12.0","null","null","null","null","null" "xx13","J","2003-07-07 12:00:00.0","null","null","null","2003-07-10 12:00:00.0","null","null" "xx14","A","2008-09-24 11:36:34.0","null","null","null","null","null","null" </code></pre> <p>Thanks guys, any help is appreciated.</p>
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="http://i.stack.imgur.com/qbH6t.png" rel="nofollow"><img src="http://i.stack.imgur.com/qbH6t.png" alt="enter image description here"></a></p>
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 ------------------- 1 | A 2 | A 3 | A 1 | B 2 | B 2 | C </code></pre> <p>Now, I need to compute the average of distinct project per user, in this case it would be:</p> <pre><code>A: 3 B: 2 C: 1 =&gt; ( 3 + 2 + 1 ) / 3 = 2 </code></pre> <p>What I have so far is the following:</p> <pre><code>distinct_pairs = Donation.objects.order_by('project') .values('user', 'project') .distinct() </code></pre> <p>This gives me a list of distincts <code>project</code>/<code>user</code> pairs, that I can work with in python.</p> <p>I would like to know if there is a <code>query-only</code> way to do this?</p> <p>My setup:</p> <ul> <li>Django 1.8</li> <li>PostgreSQL</li> </ul>
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.objects.values('user').distinct().count() average = distinct_pairs_count / float(distinct_users_count) # in Python 2 average = distinct_pairs_count / distinct_users_count # in Python 3 </code></pre> <p>EDIT: make it one QuerySet</p> <p>I think you can achieve this by one query but I can't check it right now:</p> <pre><code>from django.db.models import Count, Avg average = Donation.objects.values('user', 'project') .annotate(num_projects=Count('project', distinct=True)) .aggregate(Avg('num_projects')) </code></pre> <p>See: <a href="https://docs.djangoproject.com/en/1.8/topics/db/aggregation/#aggregating-annotations" rel="nofollow">aggregating annotations in 1.8</a></p>
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 Imperial Pale Ale' }, ] </code></pre> <p>I can successfully update the dicts from a web-client via Http PUT service.</p> <p>I can also fill the list <code>mashrecipies</code> with records from a SQLite DB using SQLAlchemy ORM via a class <code>Mash</code>. </p> <pre><code>Base = declarative_base() class Mash(Base): __tablename__ = 'mash' id = Column(Integer, primary_key=True) selected = Column(Boolean) name = Column(String) type = Column(String) description = Column(String) def __repr__(self): return '&lt;{id}, {selected}, {name}, {type}, {desc}&gt;'\ .format(id=self.id, selected=self.selected, name=self.name, type=self.type, desc=self.description) class Db(): engine = create_engine(SQLALCHEMY_DATABASE_URI) Session = sessionmaker(bind=engine) session = Session() def get_mashrecipies(self,): mashrecipies.clear() rec = None for rec in self.session.query(Mash).order_by(Mash.id): mashrecipies.append(rec) </code></pre> <p>However if I have filled the list using SQLAlchemy, and then try to update the list contents via the same Http PUT I now get the error:</p> <blockquote> <p>File "/Users/xxx/PycharmProjects/AleSheep/server/apis/mashrecipesapi.py", line 81, in mashrecipe = [mashrecipe for mashrecipe in mashrecipies if mashrecipe['id'] == id] <strong>TypeError: 'Mash' object is not subscriptable</strong></p> </blockquote> <p>The put handler in my Flask-Restful Resource is:</p> <pre><code>def put(self, id): mashrecipe = [mashrecipe for mashrecipe in mashrecipies if mashrecipe['id'] == id] </code></pre> <p>The only explicit link (in my code) between <code>mashrecipies</code> and <code>Mash</code> is when I fill <code>mashrecipies</code> from <code>Mash</code> by directly appending records from the SQLAlchemy query.</p> <p>If rather than doing <code>mashrecipies.append(rec)</code>, I copy the fields into a dict, and append the dict:</p> <pre><code>dict = {'id': rec.id, 'name': rec.name, 'description': rec.description} mashrecipies.append(dict) </code></pre> <p>then my PUT service works without error again. This solves my immediate problem.</p> <p>But what is the difference between filling the list with dicts with fields copied from a SQLAlchemy query (OK), and directly appending records returned from a query (NOT OK)?</p> <p>Is SQLAlchemy tracking changes to the query records, perhaps to persist them?</p>
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 object subscriptable you have to implement function <code>__getitem__(self, index)</code>. It will be called when you use (for example) <code>mashrecipe["hello"]</code>. The first argument (self) is an instance of an object and the second (index) is the index you are trying to access. The function should return whatever you are expecting.</p> <p>That seems like this functionality is not implemented in a class you are inheriting from and it is not implemented in your class. Thus, the error.</p> <p>Read more about <code>__getitem__</code> here - <a href="http://www.diveintopython.net/object_oriented_framework/special_class_methods.html" rel="nofollow">http://www.diveintopython.net/object_oriented_framework/special_class_methods.html</a></p>
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_Occured': [True,False,False,True,True,False,False,True,False,False]}) print df Event_Occured Time 0 True 5 1 False 10 2 False 15 3 True 20 4 True 25 5 False 30 6 False 35 7 True 40 8 False 45 9 False 50 </code></pre> <p>I'm trying to generate a column that would look like this:</p> <pre><code> Event_Occured Time Time_since_last 0 True 5 0 1 False 10 5 2 False 15 10 3 True 20 0 4 True 25 0 5 False 30 5 6 False 35 10 7 True 40 0 8 False 45 5 9 False 50 10 </code></pre> <p>Thanks very much!</p> <p>​</p>
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: x - x.iloc[0]) df </code></pre> <p><a href="http://i.stack.imgur.com/wuZ7R.png" rel="nofollow"><img src="http://i.stack.imgur.com/wuZ7R.png" alt="enter image description here"></a></p>
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_Occured': [True,False,False,True,True,False,False,True,False,False]}) print df Event_Occured Time 0 True 5 1 False 10 2 False 15 3 True 20 4 True 25 5 False 30 6 False 35 7 True 40 8 False 45 9 False 50 </code></pre> <p>I'm trying to generate a column that would look like this:</p> <pre><code> Event_Occured Time Time_since_last 0 True 5 0 1 False 10 5 2 False 15 10 3 True 20 0 4 True 25 0 5 False 30 5 6 False 35 10 7 True 40 0 8 False 45 5 9 False 50 10 </code></pre> <p>Thanks very much!</p> <p>​</p>
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: float64 </code></pre>
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 TileMargin = 4 BLACK = (0, 0, 0) WHITE = (255, 255, 255) GREEN = (0, 255, 0) RED = (255, 0, 0) BLUE = (0, 0, 255) class MapTile(object): def __init__(self, Name, xlocation, ylocation): self.Name = Name self.xlocation = xlocation self.ylocation = ylocation class Character(object): def __init__(self, Name, HP, Allegiance, xlocation, ylocation): self.Name = Name self.HP = HP self.Allegiance = Allegiance self.xlocation = xlocation self.ylocation = ylocation def Move(self, Direction): if Direction == "UP": self.ylocation += 1 elif Direction == "LEFT": self.xlocation -= 1 elif Direction == "RIGHT": self.xlocation += 1 elif Direction == "DOWN": self.ylocation -= 1 self.Location() def Location(self): print("Coordinates: " + str(self.xlocation) + ", " + str(self.ylocation)) class Map(object): Grid = [] global MapSize for Row in range(MapSize): # Creating grid Grid.append([]) for Column in range(MapSize): Grid[Row].append([]) for Row in range(MapSize): #Filling grid with grass for Column in range(MapSize): TempTile = MapTile("Grass", Row, Column) Grid[Row][Column].append(TempTile) for Row in range(MapSize): #Rocks for Column in range(MapSize): TempTile = MapTile("Rock", Row, Column) if Row == 1: Grid[Row][Column].append(TempTile) for i in range(10): #Random trees RandomRow = random.randint(0, MapSize - 1) RandomColumn = random.randint(0, MapSize - 1) TempTile = MapTile("Tree", Row, Column) Grid[RandomRow][RandomColumn].append(TempTile) def update(self): for Row in range(MapSize): for Column in range(MapSize): for i in range(len(Map.Grid[Row][Column])): if Map.Grid[Row][Column][i].xlocation != Column: print("BOOP") Map.Grid[Row][Map.Grid[Row][Column][i].xlocation].append(Map.Grid[Row][Column][i]) Map.Grid.remove(Map.Grid[Row][Column][i]) if Map.Grid[Row][Column][i].ylocation != Row: print("BOOP") Map.Grid[Row][Map.Grid[Row][Column][i].xlocation].append(Map.Grid[Row][Column][i]) else: break RandomRow = random.randint(0, MapSize - 1) RandomColumn = random.randint(0, MapSize - 1) Hero = Character("boop", 10, "Friendly", RandomRow, RandomColumn) Grid[RandomRow][RandomColumn].append(Hero) Map = Map() while not Done: for event in pygame.event.get(): if event.type == pygame.QUIT: Done = True elif event.type == pygame.MOUSEBUTTONDOWN: Pos = pygame.mouse.get_pos() Column = Pos[0] // (TileWidth + TileMargin) Row = Pos[1] // (TileHeight + TileMargin) print(str(Row) + ", " + str(Column)) for i in range(len(Map.Grid[Row][Column])): print(str(Map.Grid[Row][Column][i].Name)) elif event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: Map.Hero.Move("LEFT") if event.key == pygame.K_RIGHT: Map.Hero.Move("RIGHT") if event.key == pygame.K_UP: Map.Hero.Move("UP") if event.key == pygame.K_DOWN: Map.Hero.Move("DOWN") Map.update() Screen.fill(BLACK) for Row in range(MapSize): # Drawing grid for Column in range(MapSize): Color = WHITE if len(Map.Grid[Row][Column]) == 2: Color = RED for i in range(0, len(Map.Grid[Row][Column])): if Map.Grid[Row][Column][i].Name == "boop": Color = GREEN if Map.Grid[Row][Column][i].Name == "MoveTile": Color = BLUE pygame.draw.rect(Screen, Color, [(TileMargin + TileWidth) * Column + TileMargin, (TileMargin + TileHeight) * Row + TileMargin, TileWidth, TileHeight]) clock.tick(60) pygame.display.flip() pygame.quit() </code></pre> <p>And the relevant bits: </p> <pre><code>elif event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: Map.Hero.Move("LEFT") if event.key == pygame.K_RIGHT: Map.Hero.Move("RIGHT") if event.key == pygame.K_UP: Map.Hero.Move("UP") if event.key == pygame.K_DOWN: Map.Hero.Move("DOWN") Map.update() </code></pre> <p>The move function:</p> <pre><code>def Move(self, Direction): if Direction == "UP": self.ylocation += 1 elif Direction == "LEFT": self.xlocation -= 1 elif Direction == "RIGHT": self.xlocation += 1 elif Direction == "DOWN": self.ylocation -= 1 </code></pre> <p>And the update function, where the problem lies:</p> <pre><code>def update(self): for Row in range(MapSize): for Column in range(MapSize): for i in range(len(Map.Grid[Row][Column])): if Map.Grid[Row][Column][i].xlocation != Column: print("BOOP") Map.Grid[Row][Map.Grid[Row][Column][i].xlocation].append(Map.Grid[Row][Column][i]) Map.Grid.remove(Map.Grid[Row][Column][i]) if Map.Grid[Row][Column][i].ylocation != Row: print("BOOP") Map.Grid[Row][Map.Grid[Row][Column][i].xlocation].append(Map.Grid[Row][Column][i]) else: break </code></pre> <p>The intended behavior of the update function is to check every object in the grid and see if it has moved (if there is a discrepancy between the object's internal coordinates and its current position on the grid), and replace it in the grid at its proper position. It does this by appending a new version of the object at the new location and deleting the old one. </p> <p>The error I'm getting is:</p> <pre><code>Traceback (most recent call last): File "/Users/kosay.jabre/Desktop/Monster.py", line 136, in &lt;module&gt; Map.update() File "/Users/kosay.jabre/Desktop/Monster.py", line 93, in update Map.Grid.remove(Map.Grid[Row][Column][i]) ValueError: list.remove(x): x not in list </code></pre> <p>How best could I achieve the intended behavior?</p>
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 following the <a href="https://www.python.org/dev/peps/pep-0008/" rel="nofollow">PEP 8 - Style Guide for Python Code</a> recommendations, which made your version of the code difficult for me to read and understand. The general lack of comments explaining what was going on, especially in certain parts, didn't make it any easier.</p> <p>The <code>Map.update()</code> method is where I implemented something somewhat like I described in my comment under your question about how to fix the <code>ValueError</code> problem.</p> <pre><code>import pygame as pygame import random as random import sys GRASS_NAME = "Grass" HERO_NAME = "Hero" MOVETILE_NAME = "MoveTile" ROCK_NAME = "Rock" TREE_NAME = "Tree" MAP_SIZE = 25 TILE_WIDTH = 20 TILE_HEIGHT = 20 TILE_MARGIN = 4 TILE_SIZE = TILE_WIDTH+TILE_MARGIN BLACK = 0, 0, 0 WHITE = 255, 255, 255 GREEN = 0, 255, 0 RED = 255, 0, 0 BLUE = 0, 0, 255 YELLOW = 255, 255, 0 BROWN = 128, 128, 0 UP, DOWN, LEFT, RIGHT = 0, 1, 2, 3 MOVEMENTS = {UP: (-1, 0), DOWN: (1, 0), LEFT: (0, -1,), RIGHT: (0, 1)} MOVEMENT_KEYS = {pygame.K_LEFT, pygame.K_RIGHT, pygame.K_UP, pygame.K_DOWN} def quit_game(): pygame.quit() sys.exit() class MapTile(object): def __init__(self, name, xloc, yloc): self.name = name self.xloc = xloc self.yloc = yloc class Character(object): def __init__(self, name, hp, allegiance, xloc, yloc): self.name = name self.hp = hp self.allegiance = allegiance self.xloc = xloc self.yloc = yloc def move(self, direction): dy, dx = MOVEMENTS[direction] self.yloc += dy self.xloc += dx # Enforce boundaries if self.xloc &lt; 0: self.xloc = 0 elif self.xloc &gt; MAP_SIZE-1: self.xloc = MAP_SIZE-1 if self.yloc &lt; 0: self.yloc = 0 elif self.yloc &gt; MAP_SIZE-1: self.yloc = MAP_SIZE-1 self.location() def location(self): print("{} coordinates: ({}, {})".format(self.name, self.xloc, self.yloc)) class Map(object): # Initialize grid grid = [[[] for column in range(MAP_SIZE)] for row in range(MAP_SIZE)] for row in range(MAP_SIZE): # Completely fill grid with grass for column in range(MAP_SIZE): grid[row][column].append(MapTile(GRASS_NAME, column, row)) # Add row of rocks near top row = 1 for column in range(MAP_SIZE): grid[row][column].append(MapTile(ROCK_NAME, column, row)) for _ in range(10): # Add some random trees row, column = random.randint(0, MAP_SIZE-1), random.randint(0, MAP_SIZE-1) grid[row][column].append(MapTile(TREE_NAME, column, row)) # Put hero character in random location row, column = random.randint(0, MAP_SIZE-1), random.randint(0, MAP_SIZE-1) hero = Character(HERO_NAME, 10, "Friendly", column, row) grid[row][column].append(hero) del row, column # clean up class context def update(self): """Check every object in the grid and see if it has moved (if there is a discrepancy between the object's internal coordinates and its current position on the grid), and if so put it in its proper place by deleting it from its old list and appending it to the one for the proper location. """ for row in range(MAP_SIZE): for column in range(MAP_SIZE): for i, object in enumerate(map.grid[row][column]): if object.xloc != column or object.yloc != row: # wrong spot? #print("BOOP") map.grid[row][column].pop(i) map.grid[object.yloc][object.xloc].append(object) pygame.init() clock = pygame.time.Clock() # to limit framerate screen = pygame.display.set_mode([1000, 1000]) map = Map() while True: for event in pygame.event.get(): if event.type == pygame.QUIT: quit_game() elif(event.type == pygame.MOUSEBUTTONDOWN and pygame.mouse.get_pressed()[0]): # button1 pressed? xpos, ypos = pygame.mouse.get_pos() column, row = xpos // TILE_SIZE, ypos // TILE_SIZE if 0 &lt;= column &lt; MAP_SIZE and 0 &lt;= row &lt; MAP_SIZE: # on map? print(str(row) + ", " + str(column)) for i in range(len(map.grid[row][column])): print(str(map.grid[row][column][i].name)) elif event.type == pygame.KEYDOWN: if event.key in MOVEMENT_KEYS: if event.key == pygame.K_LEFT: map.hero.move(LEFT) elif event.key == pygame.K_RIGHT: map.hero.move(RIGHT) elif event.key == pygame.K_UP: map.hero.move(UP) else: map.hero.move(DOWN) map.update() elif event.key == pygame.K_ESCAPE: quit_game() screen.fill(BLACK) # Draw grid for row in range(MAP_SIZE): for column in range(MAP_SIZE): # Determine color based on objects in this spot names = {object.name for object in map.grid[row][column]} color = WHITE # default color (Grass) if HERO_NAME in names: color = YELLOW elif MOVETILE_NAME in names: color = BLUE elif TREE_NAME in names: color = GREEN elif ROCK_NAME in names: color = RED pygame.draw.rect(screen, color, [TILE_SIZE*column + TILE_MARGIN, TILE_SIZE*row + TILE_MARGIN, TILE_WIDTH, TILE_HEIGHT]) clock.tick(60) pygame.display.flip() pygame.quit() </code></pre>
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.16269605108256963, 0.17534585680947898, 0.17575928008998876, 0.1797698945349952, 0.19140660888739167, 0.1957585644371941, 0.19736565837544265, 0.21997813082909887, 0.22955485152768082, 0.24996957973509318, 0.29229031347077095, 0.31290263206331675, 0.32396867885822933, 0.3546099290780142, 0.3868519865218288, 0.46728971962616817, 0.48625583010816714, 0.4941864275695728, 0.5247165920267484, 0.5524861878453038, 0.564214589168688, 0.6127450980392157, 0.641025641025641, 0.6548963526282728, 0.7150582862636703, 0.823158183564275, 0.9224003861210919, 0.9253497118428529, 1.0174746597810627, 1.1462377518949898, 1.2255992248732304, 1.3000416806982482, 1.398793198025233, 1.3995903637959621, 1.4131338320864506, 1.592256254439621, 1.6498929836480547, 1.9240644218177165, 2.0467034604427172, 2.0581059831456088, 2.2849018651470887, 2.321192247101101, 2.478639485813531, 2.502272275797079, 3.530109015879148, 4.062209258467651, 6.116463053656961, 7.042445376777638, 7.177446333392399, 7.997926085414144, 8.793098189482022, 13.318221845340986, 14.199853408258, 25.417144730372073, 32.31529306085785, 53.557772100818454] </code></pre> <p>And I want to build a bar chart using plotly so I did this:</p> <pre><code>import plotly.offline as po from plotly.graph_objs import Scatter, Layout import plotly.graph_objs as go po.offline.init_notebook_mode() distribution = go.Histogram( x=my_list, xbins=dict( size=1 ) ) data = [distribution] layout = go.Layout( title="Distribution", ) fig = go.Figure(data=data, layout=layout) po.iplot(fig) </code></pre> <p>I obtain a chart like: <a href="http://i.stack.imgur.com/5Ax24.png" rel="nofollow"><img src="http://i.stack.imgur.com/5Ax24.png" alt="My chart"></a></p> <p>But when I change the size of xbins my chart doesn't change. How can I spread my first column?</p>
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 should at least be a start to brute force the axis in the right direction.</p>
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 do this (you don't really need to read the following)</h2> <p>The reason I want to do this is that I have some code that usually needs to run on my own machine (which is fine because I use Pycharm to run it) but sometimes needs to run on a remote server (on the commandline), and it doesn't work because the remote server doesn't have the <code>PYTHONPATH</code>s that Pycharm automatically temporarily adds. I don't want to <code>export PYTHONPATH=[...]</code> because it's a big hassle to change it often (and suppose it really does need to change often).</p>
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 do this (you don't really need to read the following)</h2> <p>The reason I want to do this is that I have some code that usually needs to run on my own machine (which is fine because I use Pycharm to run it) but sometimes needs to run on a remote server (on the commandline), and it doesn't work because the remote server doesn't have the <code>PYTHONPATH</code>s that Pycharm automatically temporarily adds. I don't want to <code>export PYTHONPATH=[...]</code> because it's a big hassle to change it often (and suppose it really does need to change often).</p>
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'].dt.time date_debut = pd.to_datetime('2015-08-01 23:10:00') date_fin = pd.to_datetime('2015-10-01 00:00:00') df5 = df5[(df5['TIMESTAMP'] &gt;= date_debut) &amp; (df5['TIMESTAMP'] &lt; date_fin)] df5.info() &lt;class 'pandas.core.frame.DataFrame'&gt; Int64Index: 8645 entries, 145 to 8789 Data columns (total 9 columns): TIMESTAMP 8645 non-null datetime64[ns] ACT_TIME_AERATEUR_1_F1 8645 non-null float64 ACT_TIME_AERATEUR_1_F3 8645 non-null float64 ACT_TIME_AERATEUR_1_F5 8645 non-null float64 ACT_TIME_AERATEUR_1_F6 8645 non-null float64 ACT_TIME_AERATEUR_1_F7 8645 non-null float64 ACT_TIME_AERATEUR_1_F8 8645 non-null float64 date 8645 non-null object time 8645 non-null object dtypes: datetime64[ns](1), float64(6), object(2) memory usage: 675.4+ KB </code></pre> <p>Then, I resampled it by day like this : </p> <pre><code>df5 = df5.set_index('TIMESTAMP') df5 = df5.resample('1d').mean() df5.info() &lt;class 'pandas.core.frame.DataFrame'&gt; DatetimeIndex: 61 entries, 2015-08-01 to 2015-09-30 Freq: D Data columns (total 6 columns): ACT_TIME_AERATEUR_1_F1 61 non-null float64 ACT_TIME_AERATEUR_1_F3 61 non-null float64 ACT_TIME_AERATEUR_1_F5 61 non-null float64 ACT_TIME_AERATEUR_1_F6 61 non-null float64 ACT_TIME_AERATEUR_1_F7 61 non-null float64 ACT_TIME_AERATEUR_1_F8 61 non-null float64 dtypes: float64(6) memory usage: 3.3 KB </code></pre> <p>After, I try to assign for each timestamp a date, a time and a day of week like this : </p> <pre><code>df5['date'] = df5['TIMESTAMP'].dt.date df5['time'] = df5['TIMESTAMP'].dt.time df5['day_of_week'] = df5['date'].dt.dayofweek days = {0:'Mon',1:'Tues',2:'Weds',3:'Thurs',4:'Fri',5:'Sat',6:'Sun'} df5['day_of_week'] = df5['day_of_week'].apply(lambda x: days[x]) </code></pre> <p>But As the Timestamp become an index of a dataframe when resampling, I get a problem : </p> <blockquote> <pre><code>KeyError Traceback (most recent call last) C:\Users\Demonstrator\Anaconda3\lib\site-packages\pandas\indexes\base.py </code></pre> <p>in get_loc(self, key, method, tolerance) 1944 try: -> 1945 return self._engine.get_loc(key) 1946 except KeyError:</p> <pre><code>pandas\index.pyx in pandas.index.IndexEngine.get_loc (pandas\index.c:4154)() pandas\index.pyx in pandas.index.IndexEngine.get_loc (pandas\index.c:4018)() pandas\hashtable.pyx in pandas.hashtable.PyObjectHashTable.get_item </code></pre> <p>(pandas\hashtable.c:12368)()</p> <pre><code>pandas\hashtable.pyx in pandas.hashtable.PyObjectHashTable.get_item </code></pre> <p>(pandas\hashtable.c:12322)()</p> <pre><code>KeyError: 'TIMESTAMP' During handling of the above exception, another exception occurred: KeyError Traceback (most recent call last) &lt;ipython-input-164-9887c2fb7404&gt; in &lt;module&gt;() ----&gt; 1 df5['date'] = df5['TIMESTAMP'].dt.date 2 df5['time'] = df5['TIMESTAMP'].dt.time 3 4 df5['day_of_week'] = df5['date'].dt.dayofweek 5 C:\Users\Demonstrator\Anaconda3\lib\site-packages\pandas\core\frame.py </code></pre> <p>in <strong>getitem</strong>(self, key) 1995 return self._getitem_multilevel(key) 1996 else: -> 1997 return self._getitem_column(key) 1998 1999 def _getitem_column(self, key):</p> <pre><code>C:\Users\Demonstrator\Anaconda3\lib\site-packages\pandas\core\frame.py </code></pre> <p>in _getitem_column(self, key) 2002 # get column 2003 if self.columns.is_unique: -> 2004 return self._get_item_cache(key) 2005 2006 # duplicate columns &amp; possible reduce dimensionality</p> <pre><code>C:\Users\Demonstrator\Anaconda3\lib\site-packages\pandas\core\generic.py </code></pre> <p>in _get_item_cache(self, item) 1348 res = cache.get(item) 1349 if res is None: -> 1350 values = self._data.get(item) 1351 res = self._box_item_values(item, values) 1352 cache[item] = res</p> <pre><code>C:\Users\Demonstrator\Anaconda3\lib\site-packages\pandas\core\internals.py </code></pre> <p>in get(self, item, fastpath) 3288 3289 if not isnull(item): -> 3290 loc = self.items.get_loc(item) 3291 else: 3292 indexer = np.arange(len(self.items))[isnull(self.items)]</p> <pre><code>C:\Users\Demonstrator\Anaconda3\lib\site-packages\pandas\indexes\base.py </code></pre> <p>in get_loc(self, key, method, tolerance) 1945 return self._engine.get_loc(key) 1946 except KeyError: -> 1947 return self._engine.get_loc(self._maybe_cast_indexer(key)) 1948 1949 indexer = self.get_indexer([key], method=method, tolerance=tolerance)</p> <pre><code>pandas\index.pyx in pandas.index.IndexEngine.get_loc (pandas\index.c:4154)() pandas\index.pyx in pandas.index.IndexEngine.get_loc (pandas\index.c:4018)() pandas\hashtable.pyx in pandas.hashtable.PyObjectHashTable.get_item </code></pre> <p>(pandas\hashtable.c:12368)()</p> <pre><code>pandas\hashtable.pyx in pandas.hashtable.PyObjectHashTable.get_item </code></pre> <p>(pandas\hashtable.c:12322)()</p> <pre><code>KeyError: 'TIMESTAMP' </code></pre> </blockquote> <p>Have you an idea please to resolve this problem? Thank you in advance</p> <p>Kind regards</p>
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.layers.DenseLayer(l_input,num_units=256,nonlinearity=lasagne.nonlinearities.sigmoid,W=lasagne.init.GlorotUniform()) return l_hidden1 </code></pre> <p>This is used inside</p> <pre><code>from load_dataset import load_dataset from build_DNNs import build_first_auto import sys import os import time import numpy as np from numpy import linalg as LA import theano import theano.tensor as T import lasagne import scipy.io as sio def iterate_minibatches(inputs, targets, batchsize, shuffle=False): assert len(inputs) == len(targets) if shuffle: indices = np.arange(len(inputs)) np.random.shuffle(indices) for start_idx in range(0, len(inputs) - batchsize + 1, batchsize): if shuffle: excerpt = indices[start_idx:start_idx + batchsize] else: excerpt = slice(start_idx, start_idx + batchsize) yield inputs[excerpt], targets[excerpt] def train_autoencoder(num_epochs): Xtrain, ytrain = load_dataset() # Prepare Theano variables for inputs and targets input_var = T.tensor4('inputs') target_var = T.matrix('targets') # Create neural network model network = build_first_auto(input_var) prediction = lasagne.layers.get_output(network) params = lasagne.layers.get_all_params(network, trainable=True) loss = lasagne.objectives.binary_crossentropy(prediction, target_var) loss = loss.mean() updates = lasagne.updates.nesterov_momentum(loss, params, learning_rate=0.01, momentum=0.9) np.save('params', params) #Monitoring the training test_prediction = lasagne.layers.get_output(network, deterministic=True) test_loss = lasagne.objectives.categorical_crossentropy(test_prediction,target_var) test_loss = test_loss.mean() test_acc = T.mean(T.eq(T.argmax(test_prediction,axis=1),target_var),dtype=theano.config.floatX) #Compile train_fn = theano.function([input_var, target_var], loss, updates=updates, on_unused_input='ignore' ) #on_unused_input='ignore' # Compile a second function computing the validation loss and accuracy: val_fn = theano.function([input_var, target_var], [test_loss, test_acc]) #Training print("Starting training...") for epoch in range(num_epochs): # In each epoch, we do a full pass over the training data: train_err = 0 train_batches = 0 start_time = time.time() for batch in iterate_minibatches(Xtrain, ytrain, 30821, shuffle=True): inputs, targets = batch train_err += train_fn(inputs, targets) train_batches += 1 # And a full pass over the validation data: val_err = 0 val_acc = 0 val_batches = 0 for batch in iterate_minibatches(Xtrain, ytrain, 30821, shuffle=False): inputs, targets = batch err, acc = val_fn(inputs, targets) val_err += err val_acc += acc val_batches += 1 # Then we print the results for this epoch: print("Epoch {} of {} took {:.3f}s".format( epoch + 1, num_epochs, time.time() - start_time)) print(" training loss:\t\t{:.6f}".format(train_err / train_batches)) print(" validation loss:\t\t{:.6f}".format(val_err / val_batches)) print(" validation accuracy:\t\t{:.2f} %".format( val_acc / val_batches * 100)) </code></pre> <p>The loss function is the binary cross-entropy. The problem is that I am getting an error related to the arrays dimensions:</p> <blockquote> <p>ValueError: Input dimension mis-match. (input[1].shape[1] = 1, input[3].shape[1] = 256)</p> <p>Apply node that caused the error: Elemwise{Composite{(((i0 * i1 * (i2 - scalar_sigmoid(i3))) / i4) - ((i0 * i5 * scalar_sigmoid(i3)) / i4))}}(TensorConstant{(1, 1) of -1.0}, targets, TensorConstant{(1, 1) of 1.0}, Elemwise{Add}[(0, 0)].0, Elemwise{mul,no_inplace}.0, Elemwise{sub,no_inplace}.0)</p> <p>Toposort index: 17</p> <p>Inputs types: [TensorType(float64, (True, True)), TensorType(float64, matrix), TensorType(float64, (True, True)), TensorType(float64, matrix), TensorType(float64, (True, True)), TensorType(float64, matrix)]</p> <p>Inputs shapes: [(1, 1), (30821, 1), (1, 1), (30821, 256), (1, 1), (30821, 1)]</p> <p>Inputs strides: [(8, 8), (8, 8), (8, 8), (2048, 8), (8, 8), (8, 8)]</p> <p>Inputs values: [array([[-1.]]), 'not shown', array([[ 1.]]), 'not shown', array([[ 30821.]]), 'not shown']</p> <p>Outputs clients: [[Dot22Scalar(InplaceDimShuffle{1,0}.0, Elemwise{Composite{(((i0 * i1 * (i2 - scalar_sigmoid(i3))) / i4) - ((i0 * i5 * scalar_sigmoid(i3)) / i4))}}.0, TensorConstant{0.01}), Sum{axis=[0], acc_dtype=float64}(Elemwise{Composite{(((i0 * i1 * (i2 - scalar_sigmoid(i3))) / i4) - ((i0 * i5 * scalar_sigmoid(i3)) / i4))}}.0)]]</p> </blockquote> <p>As a hint I can say that the dimension of inputs is (30821, 1, 48, 1) and for targets (30821, 1). I have read several pages about how to fix this error with reshape, but it doesn't work for my case. Also defining target_var=T.matrix() instead of T.ivector() didn't help. Setting a proper dimension for the hidden layer would work, but the functionality of this neural network should be independent by this number. Thanks for any help.</p>
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, 1),input_var=input_var) l_hidden1=lasagne.layers.DenseLayer(l_input,num_units=256,nonlinearity=lasagne.nonlinearities.sigmoid,W=lasagne.init.GlorotUniform()) l_output=lasagne.layers.DenseLayer(l_hidden1,num_units=2,nonlinearity=lasagne.nonlinearities.softmax,W=lasagne.init.GlorotUniform()) return l_output </code></pre> <p>This should work. If there is any problem, please let me know.</p>
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 href="https://www.kaggle.com/blobs/download/forum-message-attachment-files/2876/xgboost.rar" rel="nofollow">xgboost.rar</a> and then extracted it into Lib/Site packages </p> <p>now when i opening my site packages it is showing xgboost but when i <code>import xgboost</code> it says <code>no module named xgboost</code> . </p> <p>please please help </p>
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 xtrain is (6283L, 400L) . Shape of yTrain is (6283L,). Below is the code for the nueral network.</p> <pre><code>net1 = NeuralNet( layers=[ # three layers: one hidden layer ('input', layers.InputLayer), ('hidden', layers.DenseLayer), ('output', layers.DenseLayer), ], # layer parameters: input_shape=(None, 400), # 20x20 input pixels per batch hidden_num_units=100, # number of units in hidden layer # output layer uses identity function output_nonlinearity=lasagne.nonlinearities.softmax, output_num_units=63, # optimization method: update=nesterov_momentum, update_learning_rate=0.01, update_momentum=0.9, # flag to indicate we're dealing with regression problem regression=False, max_epochs=400, # we want to train this many epochs verbose=1, ) net1.fit(xTrain, yTrain) </code></pre> <p>If I select the size as 63, I get the following error:</p> <blockquote> <blockquote> <p>net1.fit(xTrain, yTrain) File "C:\Users\FTS.fts-gnosis\Anaconda2\lib\site-packages\nolearn\lasagne\base.py", line 539, in fit self.train_loop(X, y, epochs=epochs) File "C:\Users\FTS.fts-gnosis\Anaconda2\lib\site-packages\nolearn\lasagne\base.py", line 597, in train_loop self.apply_batch_func(self.train_iter_, Xb, yb)) File "C:\Users\FTS.fts-gnosis\Anaconda2\lib\site-packages\nolearn\lasagne\base.py", line 687, in apply_batch_func return func(Xb) if yb is None else func(Xb, yb) File "C:\Users\FTS.fts-gnosis\Anaconda2\lib\site-packages\theano\compile\function_module.py", line 879, in <strong>call</strong> storage_map=getattr(self.fn, 'storage_map', None)) File "C:\Users\FTS.fts-gnosis\Anaconda2\lib\site-packages\theano\gof\link.py", line 325, in raise_with_op reraise(exc_type, exc_value, exc_trace) File "C:\Users\FTS.fts-gnosis\Anaconda2\lib\site-packages\theano\compile\function_module.py", line 866, in <strong>call</strong> self.fn() if output_subset is None else\ ValueError: y_i value out of bounds Apply node that caused the error: CrossentropySoftmaxArgmax1HotWithBias(Dot22.0, output.b, y_batch) Toposort index: 11 Inputs types: [TensorType(float64, matrix), TensorType(float64, vector), TensorType(int32, vector)] Inputs shapes: [(128L, 63L), (63L,), (128L,)] Inputs strides: [(504L, 8L), (8L,), (4L,)] Inputs values: ['not shown', 'not shown', 'not shown'] Outputs clients: [[Sum{acc_dtype=float64}(CrossentropySoftmaxArgmax1HotWithBias.0)], [CrossentropySoftmax1HotWithBiasDx(Elemwise{Inv}[(0, 0)].0, CrossentropySoftmaxArgmax1HotWithBias.1, y_batch)], []] HINT: Re-running with most Theano optimization disabled could give you a back-trace of when this node was created. This can be done with by setting the Theano flag 'optimizer=fast_compile'. If that does not work, Theano optimizations can be disabled with 'optimizer=None'. HINT: Use the Theano flag 'exception_verbosity=high' for a debugprint and storage map footprint of this apply node.</p> </blockquote> </blockquote> <p>If I change the </p> <pre><code>output_nonlinearity=lasagne.nonlinearities.rectify </code></pre> <p>I get the following error:</p> <blockquote> <blockquote> <p>File "C:\Users\FTS.fts-gnosis\Anaconda2\lib\site-packages\theano\tensor\nnet\nnet.py", line 1453, in perform y[i] = -numpy.log(coding[i, one_of_n[i]]) IndexError: index 107 is out of bounds for axis 1 with size 63 Apply node that caused the error: CrossentropyCategorical1Hot(Elemwise{Composite{(i0 * (Abs(i1) + i2 + i3))}}[(0, 2)].0, y_batch) Toposort index: 14 Inputs types: [TensorType(float64, matrix), TensorType(int32, vector)] Inputs shapes: [(128L, 63L), (128L,)] Inputs strides: [(504L, 8L), (4L,)] Inputs values: ['not shown', 'not shown'] Outputs clients: [[Sum{acc_dtype=float64}(CrossentropyCategorical1Hot.0)]] Backtrace when the node is created(use Theano flag traceback.limit=N to make it longer): File "C:\Users\FTS.fts-gnosis\workspace\hello1\facialrec.py", line 200, in net1.fit(xTrain, yTrain)</p> </blockquote> </blockquote>
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 only applies to the second value iterated in the list - the first is the initialised value - 99 in the code below. </p> <p>I have also tried to specify a lambda function that updates i[1] individually, however this does not work - bad syntax. Besides the quit() function seems to be the only way to continue the iteration. </p> <p>Is there a way to do this cleanly and with the first item in the list updated?</p> <pre><code>from Tkinter import * example_list = [['Jimmy Bob','x','78'],[" Bobby Jim",'x','45'] ,["Sammy Jim Bob",'x','67'] ] #Nickname/Real Name/Age newValue = 99 def replace(): global newValue newValue = e1.get() print("Their real name is %s" %(e1.get())) #return(newValue) win.quit() root = Tk() for i in example_list: win = Toplevel(root) #win.lift() e1 = Entry(win) e1.grid(row=1, column=0) var = StringVar() var.set(i[0]) Label(win, textvariable = var).grid(row=0, column=0) Button(win, text='Enter Real Name', command=replace).grid(row=2, column=0, pady=4) #Button(win, text='Enter Real Name', command=lambda: i[1] =replace()).grid(row=2, column=0, pady=4) i[1] = newValue win.mainloop( ) root.mainloop() for i in example_list: print(i) </code></pre>
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 = "Enter the names in the dialog").grid(row=0, column=0) for i in example_list: root.lower() i[1] = tkSimpleDialog.askstring('Enter their real name', 'What is %s real name' %i[0]) print(i[1]) root.mainloop() </code></pre>
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 user this expression in other functions. Is there any existing library that can accomplish this in Python?</p>
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://sympy.org" rel="nofollow">SymPy</a>'s <a href="http://docs.sympy.org/dev/modules/parsing.html" rel="nofollow"><code>parse_expr</code></a>.</p>
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 51.496457 0.051234 3 2016-07-11 2 lenny 48.863281 2.339698 4 2016-07-11 2 wendy 51.522469 -0.148812 5 2016-07-11 3 john 51.490746 -0.022011 </code></pre> <p>I want to group this dataframe by both date and ID, then return the second row of this group for the other three columns. In the case that there is only one row for that group, then I want it to return the first row (i.e. not drop the group).</p> <p>Currently I have the following but this is dropping occasions where there is only one instance of that group.</p> <pre><code>df_grouped = df.groupby(['date', 'id']).nth(1).reset_index() </code></pre> <p>The output I am aiming for is:</p> <pre><code> date id person latitude longitude 0 2016-07-11 1 harry 51.485146 0.041339 1 2016-07-11 2 wendy 51.522469 -0.148812 2 2016-07-11 3 john 51.490746 -0.022011 </code></pre> <p>Any help would be greatly appreciated! Thanks.</p>
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 51.485146 0.041339 #1 2016-07-11 2 wendy 51.522469 -0.148812 #2 2016-07-11 3 john 51.490746 -0.022011 </code></pre>
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 51.496457 0.051234 3 2016-07-11 2 lenny 48.863281 2.339698 4 2016-07-11 2 wendy 51.522469 -0.148812 5 2016-07-11 3 john 51.490746 -0.022011 </code></pre> <p>I want to group this dataframe by both date and ID, then return the second row of this group for the other three columns. In the case that there is only one row for that group, then I want it to return the first row (i.e. not drop the group).</p> <p>Currently I have the following but this is dropping occasions where there is only one instance of that group.</p> <pre><code>df_grouped = df.groupby(['date', 'id']).nth(1).reset_index() </code></pre> <p>The output I am aiming for is:</p> <pre><code> date id person latitude longitude 0 2016-07-11 1 harry 51.485146 0.041339 1 2016-07-11 2 wendy 51.522469 -0.148812 2 2016-07-11 3 john 51.490746 -0.022011 </code></pre> <p>Any help would be greatly appreciated! Thanks.</p>
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'], keep='last') Out: date id person latitude longitude 1 2016-07-11 1 harry 51.485146 0.041339 4 2016-07-11 2 wendy 51.522469 -0.148812 5 2016-07-11 3 john 51.490746 -0.022011 </code></pre>
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.replace(path,"") with open(fname, 'r') as myfile: </code></pre> <p>My file name looks like C:\Myfolder\data\today\00.log and I just need "today\00.log" The error is IOError: [Errno 2] No such file or directory: '\today\00.log' How to remove \ from the file name?</p>
-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.path.join(root,filename) if os.path.isfile(fullname) and fullname[-4:] == '.log': if fullname not in rows1: print fullname fname = fullname[len(path)+1:] with open(fullname, 'r') as myfile: do_something </code></pre>
-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 spaces from the left hand margin). 4 spaces per level.</p>
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()</code> widths.</p>
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.</p> <p>Have you run QWidget::setMaximumWidth() on the smallish widgets? That would also be useful, perhaps.</p>
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()</code> widths.</p>
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 about the current original scikit-lean package)</p></li> <li><p>Can I add the modified folder to the Python path ?</p></li> <li><p>How to manage versioning when loading package in Python since both are same names ?<br> (ie: the original package vs the package I modified)</p></li> </ol> <p>Sorry, it looks like beginner questions, but could not find anything how to start with </p>
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 instance of a list for nothing, but it worked.</p> <p>With Python 3, as <code>map</code> returns an iterator and not a list, the above code does nothing. I found a workaround, since <code>os.remove</code> returns <code>None</code>, I use <code>any</code> to force iteration on the full list, without creating a <code>list</code> (better performance)</p> <pre><code>any(map(os.remove,glob.glob("*.pyc"))) </code></pre> <p>But it seems a bit hazardous, specially when applying it to methods that return something. Another way to do that with a one-liner and not create an unnecessary list?</p>
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 @vaultah nailed it in the comments..</p>
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 code, out of 10 sections required to solve the problem. Each has one more nested loop, and while the time is not an issue I would like to improve this code, but I am not sure how to implement this algorithm in a more concise manner. </p> <p>What the nth section does is generate all numbers less than 1e9, that contain only the first n prime numbers(and then add numbers relating to the problem to a set). </p> <p>I have tried for example to have a list of exponents for all primes, and incrementing the outermost nonzero exponent, and then backtracking when the product is larger than 1e9, however I have not been able to do anything successful. </p> <p>If this question is not appropriate for this site I can delete it.</p> <pre><code>pseudofortunate=set() pr=generate_primes(24) num1=1 while num1&lt;1e9/2: num1*=pr[0] num2=num1 while num2&lt;1e9/3: num2*=pr[1] m=num2+3 while True: if is_prime(m): pseudofortunate.add(m-num2) break m+=2 num1=1 while num1&lt;1e9/2: num1*=pr[0] num2=num1 while num2&lt;1e9/3: num2*=pr[1] num3=num2 while num3&lt;1e9/5: num3*=pr[2] m=num3+3 while True: if is_prime(m): pseudofortunate.add(m-num3) break m+=2 num1=1 while num1&lt;1e9/2: num1*=pr[0] num2=num1 while num2&lt;1e9/3: num2*=pr[1] num3=num2 while num3&lt;1e9/5: num3*=pr[2] num4=num3 while num4&lt;1e9/7: num4*=pr[3] m=num4+3 while True: if is_prime(m): pseudofortunate.add(m-num4) break m+=2 </code></pre>
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) { break; } } if (j == (i-1)) { ++numPrimes; } } // now add 1 for the value 2 numPrimes = ++numPrimes; </code></pre>
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 code, out of 10 sections required to solve the problem. Each has one more nested loop, and while the time is not an issue I would like to improve this code, but I am not sure how to implement this algorithm in a more concise manner. </p> <p>What the nth section does is generate all numbers less than 1e9, that contain only the first n prime numbers(and then add numbers relating to the problem to a set). </p> <p>I have tried for example to have a list of exponents for all primes, and incrementing the outermost nonzero exponent, and then backtracking when the product is larger than 1e9, however I have not been able to do anything successful. </p> <p>If this question is not appropriate for this site I can delete it.</p> <pre><code>pseudofortunate=set() pr=generate_primes(24) num1=1 while num1&lt;1e9/2: num1*=pr[0] num2=num1 while num2&lt;1e9/3: num2*=pr[1] m=num2+3 while True: if is_prime(m): pseudofortunate.add(m-num2) break m+=2 num1=1 while num1&lt;1e9/2: num1*=pr[0] num2=num1 while num2&lt;1e9/3: num2*=pr[1] num3=num2 while num3&lt;1e9/5: num3*=pr[2] m=num3+3 while True: if is_prime(m): pseudofortunate.add(m-num3) break m+=2 num1=1 while num1&lt;1e9/2: num1*=pr[0] num2=num1 while num2&lt;1e9/3: num2*=pr[1] num3=num2 while num3&lt;1e9/5: num3*=pr[2] num4=num3 while num4&lt;1e9/7: num4*=pr[3] m=num4+3 while True: if is_prime(m): pseudofortunate.add(m-num4) break m+=2 </code></pre>
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,depth-1): num_depth=i while num_depth&lt;n/pr[depth]: num_depth*=pr[depth] yield num_depth def amicablenums(n=1e9): p=set() for i in range(len(pr)): a=set(loop(n,i)) p=p|a return p def pseudofortunate(n): m=n+3 while True: if is_prime(m): return m-n m+=2 pr=generate_primes(24) pseudofortunates=set() for i in amicablenums(): pseudofortunates.add(pseudofortunate(i)) print sum(pseudofortunates) </code></pre>
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> <pre><code>test_dict = {'A': [['ap11', 'ct1', 'status a'], ['ap2', 'ct2', 'status b'], ['ap11', 'ct1', 'status a']], 'B': [['ap33', 'ct3', 'status b']]} for k, v in test_dict.iteritems(): site_id = k alert_header = str(['aname', 'cname', 'status']) ap_list = [i for i in v] # SendMail(site_id, alert_header, ap_list) print(site_id) print(alert_header) print(ap_list) </code></pre> <p>Output:</p> <pre><code>A ['aname', 'cname', 'status'] [['ap11', 'ct1', 'status a'], ['ap2', 'ct2', 'status b'], ['ap11', 'ct1', 'status a']] B ['aname', 'cname', 'status'] [['ap33', 'ct3', 'status b']] </code></pre> <p>Desired Output is a single string comprising of the key, the <em>alert_header</em> and the str representation of each sublist, one per line:</p> <pre><code>A ['name', 'cname', 'status'] ['ap11', 'ct1', 'status a'] ['ap2', 'ct2', 'status b'] ['ap11', 'ct1', 'status a'] B ['name', 'cname', 'status'] ['ap33', 'ct3', 'status b'] </code></pre> <p>TIA</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: print(ap) </code></pre>
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> <pre><code>test_dict = {'A': [['ap11', 'ct1', 'status a'], ['ap2', 'ct2', 'status b'], ['ap11', 'ct1', 'status a']], 'B': [['ap33', 'ct3', 'status b']]} for k, v in test_dict.iteritems(): site_id = k alert_header = str(['aname', 'cname', 'status']) ap_list = [i for i in v] # SendMail(site_id, alert_header, ap_list) print(site_id) print(alert_header) print(ap_list) </code></pre> <p>Output:</p> <pre><code>A ['aname', 'cname', 'status'] [['ap11', 'ct1', 'status a'], ['ap2', 'ct2', 'status b'], ['ap11', 'ct1', 'status a']] B ['aname', 'cname', 'status'] [['ap33', 'ct3', 'status b']] </code></pre> <p>Desired Output is a single string comprising of the key, the <em>alert_header</em> and the str representation of each sublist, one per line:</p> <pre><code>A ['name', 'cname', 'status'] ['ap11', 'ct1', 'status a'] ['ap2', 'ct2', 'status b'] ['ap11', 'ct1', 'status a'] B ['name', 'cname', 'status'] ['ap33', 'ct3', 'status b'] </code></pre> <p>TIA</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_dict.iteritems(): # call str on each sublist and separate by newlines. data = "\n".join(map(str, v)) # concatenate all three stings into one. to_send = site_id + "\n" + alert_header + "\n" + data print(to_send) </code></pre> <p>Output:</p> <pre><code>A ['aname', 'cname', 'status'] ['ap11', 'ct1', 'status a'] ['ap2', 'ct2', 'status b'] ['ap11', 'ct1', 'status a'] B ['aname', 'cname', 'status'] [['ap33', 'ct3', 'status b']] </code></pre>
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, else a 0.</p> <p>In other words, I'm trying to merge the two dataframes and create conditional columns based on if the id was present for each original dataframe. Any suggestions on how to approach this problem?</p> <p>Here is a small example:</p> <pre><code>import pandas as pd &gt;&gt;&gt; df_a = pd.DataFrame({'group': list('AAABBB'), 'id': [11,12,13,21,22,23]}) &gt;&gt;&gt; df_b = pd.DataFrame({'group': list('AAABB'), 'id': [11,13,14,22,24]}) &gt;&gt;&gt; df_a group id A 11 A 12 A 13 B 21 B 22 B 23 &gt;&gt;&gt; df_b group id A 11 A 13 A 14 B 22 B 24 </code></pre> <p>The output should look like this:</p> <pre><code>&gt;&gt;&gt; df_full group id a b A 11 1 1 A 12 1 0 A 13 1 1 A 14 0 1 B 21 1 0 B 22 1 1 B 23 1 0 B 24 0 1 </code></pre>
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 1.0 1.0 # 3 B 21.0 1.0 0.0 # 4 B 22.0 1.0 1.0 # 5 B 23.0 1.0 0.0 # 6 A 14.0 0.0 1.0 # 7 B 24.0 0.0 1.0 </code></pre>
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-upgrader version '0.220.3' started 2016-08-18 18:40:08,940 INFO locale: 'en_US' 'UTF-8' 2016-08-18 18:40:08,999 DEBUG Using 'DistUpgradeViewText' view 2016-08-18 18:40:09,025 DEBUG aufsOptionsAndEnvironmentSetup() 2016-08-18 18:40:09,027 DEBUG using '/tmp/upgrade-rw-xlP_6c' as aufs_rw_dir 2016-08-18 18:40:09,027 DEBUG using '/tmp/upgrade-chroot-RJMewm' as aufs chroot dir 2016-08-18 18:40:09,027 DEBUG enable dpkg --force-overwrite 2016-08-18 18:40:09,072 DEBUG creating statefile: '/var/log/dist-upgrade/apt-clone_system_state.tar.gz' 2016-08-18 18:40:10,482 DEBUG lsb-release: 'precise' 2016-08-18 18:40:11,766 ERROR not handled exception: Traceback (most recent call last): File "/tmp/update-manager-W9tKZ8/trusty", line 10, in &lt;module&gt; sys.exit(main()) File "/tmp/update-manager-W9tKZ8/DistUpgrade/DistUpgradeMain.py", line 244, in main if app.run(): File "/tmp/update-manager-W9tKZ8/DistUpgrade/DistUpgradeController.py", line 1827, in run return self.fullUpgrade() File "/tmp/update-manager-W9tKZ8/DistUpgrade/DistUpgradeController.py", line 1649, in fullUpgrade if not self.prepare(): File "/tmp/update-manager-W9tKZ8/DistUpgrade/DistUpgradeController.py", line 441, in prepare self._sshMagic() File "/tmp/update-manager-W9tKZ8/DistUpgrade/DistUpgradeController.py", line 317, in _sshMagic "-p",str(port)]) File "/usr/lib/python2.7/subprocess.py", line 522, in call return Popen(*popenargs, **kwargs).wait() File "/usr/lib/python2.7/subprocess.py", line 710, in __init__ errread, errwrite) File "/usr/lib/python2.7/subprocess.py", line 1327, in _execute_child raise child_exception OSError: [Errno 2] No such file or directory 2016-08-18 18:40:11,767 DEBUG enabling apt cron job </code></pre> <p>Cant get any information on web to fix this. I already updated pyton 2.7.3 to python 2.7.11, tried linking to python3. Still the same issue...</p> <p>Any ideas?</p>
-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 column that is the district that user entry is located in.</p> <p>I have searched the web and found <a href="https://github.com/harsha2010/magellan" rel="nofollow" title="Magellan">Magellan</a>, but the Python support is <a href="https://github.com/harsha2010/magellan/issues/59#issuecomment-240209859" rel="nofollow">not working</a> at this time. I have also found Hive support for GIS functions in <a href="https://github.com/Esri/spatial-framework-for-hadoop%20Esri%20Spatial" rel="nofollow">Esri Spatial</a>, but didn't find documentation on how to load the correct package when starting up PySpark or how to register the needed functions in the PySpark shell: (ST_Polygon, ST_Contains, etc...).</p> <p>Are there other alternatives that I should look into? I am using Azure's HDInsight so I have access to a HiveContext object in the PySpark shell:</p> <pre><code>&gt;&gt;&gt; sqlContext &lt;pyspark.sql.context.HiveContext object at 0x7f3294093b10&gt; </code></pre> <p>Sample dataset:</p> <blockquote> <p>| Timestamp| User| Latitude|Longitude| |1462838468|49B4361512443A4DA...|39.777982|-7.054599| |1462838512|49B4361512443A4DA...|39.777982|-7.054599| |1462838389|49B4361512443A4DA...|39.777982|-7.054599| |1462838497|49B4361512443A4DA...|39.777982|-7.054599| |1465975885|6E9E0581E2A032FD8...|37.118362|-8.205041| |1457723815|405C238E25FE0B9E7...|37.177322|-7.426781| |1457897289|405C238E25FE0B9E7...|37.177922|-7.447443| |1457899229|405C238E25FE0B9E7...|37.177922|-7.447443| |1457972626|405C238E25FE0B9E7...| 37.18059| -7.46128| |1458062553|405C238E25FE0B9E7...|37.177322|-7.426781| |1458241825|405C238E25FE0B9E7...|37.178172|-7.444512| |1458244457|405C238E25FE0B9E7...|37.178172|-7.444512| |1458412513|405C238E25FE0B9E7...|37.177322|-7.426781| |1458412292|405C238E25FE0B9E7...|37.177322|-7.426781| |1465197963|6E9E0581E2A032FD8...|37.118362|-8.205041| |1465202192|6E9E0581E2A032FD8...|37.118362|-8.205041| |1465923817|6E9E0581E2A032FD8...|37.118362|-8.205041| |1465923766|6E9E0581E2A032FD8...|37.118362|-8.205041| |1465923748|6E9E0581E2A032FD8...|37.118362|-8.205041| |1465923922|6E9E0581E2A032FD8...|37.118362|-8.205041|</p> </blockquote>
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/</a></p> <p>You would have to install the library you want to use. Instructions on how to install libraries can be found here: <a href="http://stackoverflow.com/a/38754345/1663781">http://stackoverflow.com/a/38754345/1663781</a></p> <p>Then, simply add a column to your RDD using any of the libraries, like so:</p> <pre><code>from my_gis_library_of_choice import in_polygon, district text_lines = sc.textFile('wasb:///mydataset') split = text_lines.map(lambda line: line.split('|')) with_extra_columns = split.map(lambda r: r.append(in_polygon(r[2], r[3])).append(district(r[2], r[3]))) </code></pre>
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" rel="nofollow"><code>gethostbyaddr()</code></a> for <code>getfqdn(name)</code>.</li> </ul> <p>For <code>gethostbyaddr()</code> it picks the first name with a <code>.</code> in the name and defaults to the host's name if no dotted name could be found. See the <a href="https://github.com/python/cpython/blob/642bebc901ea780e40e0295bb9c90a34c2f34503/Lib/socket.py#L650" rel="nofollow">source</a>.</p> <p>Name resolution order <a href="https://support.microsoft.com/en-us/kb/172218" rel="nofollow">on Windows</a> is:</p> <ol> <li>own name</li> <li>hosts file if exists</li> <li>DNS</li> <li>NetBIOS (order changeable, sometimes disabled)</li> </ol>
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,000,000 rule. Any ideas why? Do I need to add Int or Float in my function?</p> <pre><code>FirstList = [] for i in range(5, 2000, 1): FirstList.append(int(sheet.cell(row=i, column=9).value)) if (sheet.cell(row=i, column=9).value) &gt; 1000000: FirstList.append(i) print FirstList </code></pre>
-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 <code>requirements.txt</code>. But I am not sure what does above command do.</p>
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 usage:</p> <blockquote> <pre><code>pip install [options] [-e] &lt;local project path&gt; ... </code></pre> </blockquote>
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. And I don't think the objC buffer is being allocated either. Any help would be greatly appreciated.</p> <pre><code>#!/usr/bin/python import os, sys, objc from Quartz import * os.environ["CG_CONTEXT_SHOW_BACKTRACE"] = '1' resolution = 300 #dpi scale = resolution/72 cs = CGColorSpaceCreateWithName(kCGColorSpaceSRGB) # Options might be: kCGImageAlphaNoneSkipLast, kCGImageAlphaPremultipliedLast \ or FIRST transparency = kCGImageAlphaNoneSkipLast #Save image to file def writeImage (image, url, type, options): destination = CGImageDestinationCreateWithURL(url, type, 1, None) CGImageDestinationAddImage(destination, image, options) CGImageDestinationFinalize(destination) CFRelease(destination) return if __name__ == '__main__': for filename in sys.argv[1:]: pdf = CGPDFDocumentCreateWithProvider(CGDataProviderCreateWithFilename(filename)) numPages = CGPDFDocumentGetNumberOfPages(pdf) shortName = os.path.splitext(filename)[0] # For each page, create a file for i in range (1, numPages+1): page = CGPDFDocumentGetPage(pdf, i) if page: #Get mediabox mediaBox = CGPDFPageGetBoxRect(page, kCGPDFMediaBox) x = CGRectGetWidth(mediaBox) y = CGRectGetHeight(mediaBox) x *= scale y *= scale # Allocate Memory, in this day and age. try: rasterData = objc.allocateBuffer(int(4 * x * y)) except MemoryError: break # Create a Bitmap Context ctx = CGBitmapContextCreate(rasterData, x, y, 8, x, cs, transparency) CGContextSaveGState (ctx) CGContextScaleCTM(ctx, scale,scale) CGContextDrawPDFPage(ctx, page) CGContextRestoreGState(ctx) # Convert to an "Image" image = CGBitmapContextCreateImage(ctx) # Create unique filename per page outFile = shortName + str(i) + ".tiff" url = CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault, outFile, len(outFile), False) # kUTTypeJPEG, kUTTypeTIFF, kUTTypePNG type = 'kUTTypeTIFF' options = { kCGImagePropertyTIFFXResolution : 300, kCGImagePropertyTIFFYResolution : 300 } writeImage (image, url, type, options) CGContextRelease(ctx) del page </code></pre>
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>CGBitmapContextCreate: unsupported parameter combination: 16 integer bits/component; 48 bits/pixel; RGB color space model; kCGImageAlphaNone; 14336 bytes/row. Valid parameters for RGB color space model are: 16 bits per pixel, 5 bits per component, kCGImageAlphaNoneSkipFirst 32 bits per pixel, 8 bits per component, kCGImageAlphaNoneSkipFirst 32 bits per pixel, 8 bits per component, kCGImageAlphaNoneSkipLast 32 bits per pixel, 8 bits per component, kCGImageAlphaPremultipliedFirst 32 bits per pixel, 8 bits per component, kCGImageAlphaPremultipliedLast 64 bits per pixel, 16 bits per component, kCGImageAlphaPremultipliedLast 64 bits per pixel, 16 bits per component, kCGImageAlphaNoneSkipLast 64 bits per pixel, 16 bits per component, kCGImageAlphaPremultipliedLast|kCGBitmapFloatComponents 64 bits per pixel, 16 bits per component, kCGImageAlphaNoneSkipLast|kCGBitmapFloatComponents 128 bits per pixel, 32 bits per component, kCGImageAlphaPremultipliedLast|kCGBitmapFloatComponents 128 bits per pixel, 32 bits per component, kCGImageAlphaNoneSkipLast|kCGBitmapFloatComponents </code></pre> <p>So merely changing the transparency constant to kCGImageAlphaPremultipliedLast has stopped the crashing and fixed the context. However, the script as a whole still doesn't work, and I just get <code>Trace/BPT trap: 5</code> as a response.</p>
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 reduce the number of rows here considerably. The following is the code I am using,</p> <pre><code>bad_words = pd.read_csv('badwords.txt') bad_words.dtypes words object dtype: object bad_words words 0 word1 1 word3 2 word5 3 word13 4 word16 data s.no column1 column2 column3 column4 1 aaaword1b aaaword2b aaaword3b aaaword4b 2 aaaword5b aaaword6b aaaword7b aaaword8b 3 aaaword9b aaaword10b aaaword11b aaaword12b 4 aaaword13b aaaword14b aaaword15b aaaword16b 5 aaaword17b aaaword18b aaaword19b aaaword20b </code></pre> <p>I want to remove the rows that contain words from the bad word document. The output of this should be,</p> <pre><code>data s.no column1 column2 column3 column4 3 aaaword9b aaaword10b aaaword11b aaaword12b 5 aaaword17b aaaword18b aaaword19b aaaword20b </code></pre> <p>I am trying to do something like,</p> <pre><code>data[(data['column1'].str.contains("word1|word3|word5|word13|word16")==False)| (data['column2'].str.contains("word1|word3|word5|word13|word16")==False)| (data['column3'].str.contains("word1|word3|word5|word13|word16")==False)] </code></pre> <p>But I am not sure whether we can do it for the entire 3500 words. Also not sure whether this is the efficient way to do for 87 million rows. </p> <p><strong>Updated the question with string patterns rather that the direct words. Sorry for the bad requirement earlier.</strong></p> <p>Can anybody suggest me a better way to do this?</p> <p>Thanks</p>
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_words.words).any(), axis = 1)] #s.no column1 column2 column3 column4 #2 3 word9 word10 word11 word12 #4 5 word17 word18 word19 word20 </code></pre> <p>For the updated question, here is an option that might work depending on your actual data:</p> <pre><code>data[~data.apply(lambda row: bad_words.words.apply(lambda w: row.str.contains(w + "(?=\D)").any()).any(), axis = 1)] # sno column1 column2 column3 column4 #2 3 aaaword9b aaaword10b aaaword11b aaaword12b #4 5 aaaword17b aaaword18b aaaword19b aaaword20b </code></pre>
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 reduce the number of rows here considerably. The following is the code I am using,</p> <pre><code>bad_words = pd.read_csv('badwords.txt') bad_words.dtypes words object dtype: object bad_words words 0 word1 1 word3 2 word5 3 word13 4 word16 data s.no column1 column2 column3 column4 1 aaaword1b aaaword2b aaaword3b aaaword4b 2 aaaword5b aaaword6b aaaword7b aaaword8b 3 aaaword9b aaaword10b aaaword11b aaaword12b 4 aaaword13b aaaword14b aaaword15b aaaword16b 5 aaaword17b aaaword18b aaaword19b aaaword20b </code></pre> <p>I want to remove the rows that contain words from the bad word document. The output of this should be,</p> <pre><code>data s.no column1 column2 column3 column4 3 aaaword9b aaaword10b aaaword11b aaaword12b 5 aaaword17b aaaword18b aaaword19b aaaword20b </code></pre> <p>I am trying to do something like,</p> <pre><code>data[(data['column1'].str.contains("word1|word3|word5|word13|word16")==False)| (data['column2'].str.contains("word1|word3|word5|word13|word16")==False)| (data['column3'].str.contains("word1|word3|word5|word13|word16")==False)] </code></pre> <p>But I am not sure whether we can do it for the entire 3500 words. Also not sure whether this is the efficient way to do for 87 million rows. </p> <p><strong>Updated the question with string patterns rather that the direct words. Sorry for the bad requirement earlier.</strong></p> <p>Can anybody suggest me a better way to do this?</p> <p>Thanks</p>
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_ 3 _word13_ 4 _word16_""" text_data = """s.no column1 column2 column3 column4 1 aaa_word1_b aaa_word2_b aaa_word3_b aaa_word4_b 2 aaa_word5_b aaa_word6_b aaa_word7_b aaa_word8_b 3 aaa_word9_b aaa_word10_b aaa_word11_b aaa_word12_b 4 aaa_word13_b aaa_word14_b aaa_word15_b aaa_word16_b 5 aaa_word17_b aaa_word18_b aaa_word19_b aaa_word20_b""" bad_words = pd.read_csv( StringIO(text_bad_words), squeeze=True, index_col=0, delim_whitespace=True) data = pd.read_csv( StringIO(text_data), squeeze=True, index_col=0, delim_whitespace=True) </code></pre> <h3>Solution</h3> <p>I'll use <code>regex</code> and <code>contains</code></p> <pre><code>regex = r'|'.join(bad_words) regex '_word1_|_word3_|_word5_|_word13_|_word16_' </code></pre> <p>Create boolean mask</p> <pre><code>mask = data.stack().str.contains(regex).unstack().any(1) mask s.no 1 True 2 True 3 False 4 True 5 False dtype: bool </code></pre> <hr> <pre><code>data.loc[~mask] </code></pre> <p><a href="http://i.stack.imgur.com/lHtVo.png" rel="nofollow"><img src="http://i.stack.imgur.com/lHtVo.png" alt="enter image description here"></a></p>
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 but there is a blank screen when doing so. </p> <p>My question is: Can i have a message box that says "Running..." while the function runs and then close when the entire process completes? </p> <p>Bonus points: to have a progress bar while process runs.</p> <p>Now I've done some searching but some of this stuff is over my head (I'm fairly new to Python). I'm not sure how to incorporate these parts into my code. Is there anything that is easy like EasyGUI to solve my problem? Thanks!</p> <p>Related posts: <a href="http://stackoverflow.com/questions/8835374/python-displaying-a-message-box-that-can-be-closed-in-the-code-no-user-interve">Python- Displaying a message box that can be closed in the code (no user intervention)</a></p> <p><a href="http://stackoverflow.com/questions/23215226/how-to-pop-up-a-message-while-processing-python">How to pop up a message while processing - python</a></p> <p><a href="http://stackoverflow.com/questions/3002085/python-to-print-out-status-bar-and-percentage">Python to print out status bar and percentage</a></p> <p>If you absolutely need to see my code i can try and re-create it without giving away information. The higher-ups would appreciate me not giving away information about this project - Security is tight here. </p>
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 ttk class GUI(object): def __init__(self): self.root = tkinter.Tk() self.progbar = ttk.Progressbar(self.root) self.progbar.config(maximum=10, mode='determinate') self.progbar.pack() self.i = 0 self.b_start = ttk.Button(self.root, text='Start') self.b_start['command'] = self.start_thread self.b_start.pack() def start_thread(self): self.b_start['state'] = 'disable' self.work_thread = threading.Thread(target=work) self.work_thread.start() self.root.after(50, self.check_thread) self.root.after(50, self.update) def check_thread(self): if self.work_thread.is_alive(): self.root.after(50, self.check_thread) else: self.root.destroy() def update(self): #Updates the progressbar self.progbar["value"] = self.i if self.work_thread.is_alive(): self.root.after(50, self.update)#method is called all 50ms gui = GUI() def work(): #Do your work :D for i in range(11): gui.i = i time.sleep(0.1) gui.root.mainloop() </code></pre> <p>Let me know if that helps :)</p>
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 dashboard, I get an H10 error every time. What gives?</p> <p>Edit: logs</p> <pre><code> 2016-08-18T17:34:25.925592+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=hwt1.herokuapp.com request_id=a0cabc52-0f80-4094-a420-06147b8c860c fwd="199.133.80.68" dyno= connect= service= status=503 bytes= 2016-08-18T17:34:26.646976+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=hwt1.herokuapp.com request_id=27121a16-ad6b-489f-8ffc-1d3b5e21d225 fwd="199.133.80.68" dyno= connect= service= status=503 bytes= </code></pre>
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 either. </p> <pre><code>from random import randint def make_a_phrase(): random_string = '' take_from = ['a','b','c','d','e','f','g','h','i','j','k','l', 'm','n','o','p','q','r','s','t','v','u','w','x', 'y','z',' '] for i in range(28): random_string = random_string + take_from[randint (0,len(take_from))] return random_string </code></pre>
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 to:</p> <pre><code>for i in range(28): random_string = random_string + take_from[randint (0,len(take_from)-1)] </code></pre>
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 either. </p> <pre><code>from random import randint def make_a_phrase(): random_string = '' take_from = ['a','b','c','d','e','f','g','h','i','j','k','l', 'm','n','o','p','q','r','s','t','v','u','w','x', 'y','z',' '] for i in range(28): random_string = random_string + take_from[randint (0,len(take_from))] return random_string </code></pre>
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(take_from)</code> - <strong>inclusive the endpoints</strong> - which in case of the upper bound would be out of list's index range as it is zero based and as such only has <code>len(take_from) - 1</code> elements</p>
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 either. </p> <pre><code>from random import randint def make_a_phrase(): random_string = '' take_from = ['a','b','c','d','e','f','g','h','i','j','k','l', 'm','n','o','p','q','r','s','t','v','u','w','x', 'y','z',' '] for i in range(28): random_string = random_string + take_from[randint (0,len(take_from))] return random_string </code></pre>
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 either. </p> <pre><code>from random import randint def make_a_phrase(): random_string = '' take_from = ['a','b','c','d','e','f','g','h','i','j','k','l', 'm','n','o','p','q','r','s','t','v','u','w','x', 'y','z',' '] for i in range(28): random_string = random_string + take_from[randint (0,len(take_from))] return random_string </code></pre>
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 either. </p> <pre><code>from random import randint def make_a_phrase(): random_string = '' take_from = ['a','b','c','d','e','f','g','h','i','j','k','l', 'm','n','o','p','q','r','s','t','v','u','w','x', 'y','z',' '] for i in range(28): random_string = random_string + take_from[randint (0,len(take_from))] return random_string </code></pre>
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><code>&gt;&gt;&gt; i = [1,2,3] &gt;&gt;&gt; len(i) 3 &gt;&gt;&gt; i[len(i)] Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; IndexError: list index out of range </code></pre> <p>However, if you -1 from the length you will get the last item:</p> <pre><code>&gt;&gt;&gt; i[len(i)-1] 3 </code></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 my location and called the detector program. Here are my doubts and questions.</p> <p>What should I use as the testing XML file while running the program? I ran without assigning any testing XML in place. However, I get the following. Training with C: 5 Training with epsilon: 0.01 Training using 8 threads. Training with sliding window 81 pixels wide by 79 pixels tall. Training on both left and right flipped versions of images. Killed What does 'killed' mean by the way?</p> <p>What should I do now? Please guide!</p>
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 to memory issues. In Linux, it is the result of the OOM Killer. Since the images are so large, your machine is running out of memory and killing the training process.<br> Possible solutions:<br> 1) <a href="http://www.oracle.com/technetwork/articles/servers-storage-dev/oom-killer-1911807.html" rel="nofollow">Configure the OOM killer</a> to allow dlib to use more memory.<br> 2) Scale down the images if possible for your application.<br> 3) Use a machine with more RAM. If you don't have one on hand, AWS offers several high-RAM <a href="https://aws.amazon.com/ec2/pricing/" rel="nofollow">EC2 options</a> at relatively low cost.</p>
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> first item. </p> <pre><code>[[58 58 56 54 52] [56 56 54 52 50] [54 54 52 50 48] [52 52 50 48 46] [50 50 48 46 44] [48 48 46 44 42] [46 46 44 42 40] [44 44 42 40 38] [42 42 40 38 36] [40 40 38 36 34] [38 38 36 34 32] [36 36 34 32 30] [34 34 32 30 None] [32 32 30 None None] [30 30 None None None]] </code></pre> <p>The code below works, want it faster without 'for' loop and enumerate.</p> <pre><code>arr = np.empty((0,5), int) for i,e in enumerate(x): arr2 = np.hstack((x[i], x[i:i+4], np.asarray([None]*5)))[:5] arr = np.vstack((arr,arr2)) </code></pre>
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,-2) + [float('nan')]*width) arr = np.empty([len(x)-width, width+2]) arr[:,0] = x[:len(x)-width] for i in xrange(len(x)-width): arr[i,1:] = x[i:i+width+1] print(time()-t) t = time() for _ in range(1000): #1000 iterations of OP code x = range(30,60,2)[::-1]; x = np.asarray(x) arr = np.empty((0,5), int) for i,e in enumerate(x): arr2 = np.hstack((x[i], x[i:i+4], np.asarray([None]*5)))[:5] arr = np.vstack((arr,arr2)) print(time()-t) t = time() for _ in range(1000): x = np.array(range(58,28,-2)) N = 4 # width factor x_ext = np.hstack((x,[None]*(N-1))) arr2D = x_ext[np.arange(N) + np.arange(x_ext.size-N+1)[:,None]] out = np.column_stack((x,arr2D)) print(time()-t) </code></pre> <p>prints out:</p> <pre><code>&gt;&gt;&gt; runfile('...temp.py', wdir='...') 0.0160000324249 0.374000072479 0.0319998264313 &gt;&gt;&gt; </code></pre>
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> first item. </p> <pre><code>[[58 58 56 54 52] [56 56 54 52 50] [54 54 52 50 48] [52 52 50 48 46] [50 50 48 46 44] [48 48 46 44 42] [46 46 44 42 40] [44 44 42 40 38] [42 42 40 38 36] [40 40 38 36 34] [38 38 36 34 32] [36 36 34 32 30] [34 34 32 30 None] [32 32 30 None None] [30 30 None None None]] </code></pre> <p>The code below works, want it faster without 'for' loop and enumerate.</p> <pre><code>arr = np.empty((0,5), int) for i,e in enumerate(x): arr2 = np.hstack((x[i], x[i:i+4], np.asarray([None]*5)))[:5] arr = np.vstack((arr,arr2)) </code></pre>
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) for i,e in enumerate(x): arr2 = np.hstack((x[i], x[i:i+4], np.asarray([None]*5)))[:5] arr = np.vstack((arr,arr2)) return arr def sol2(): # My proposal x2 = np.hstack((x, [None]*3)) mat = np.matlib.repmat(x2, 5, 1) for i in range(3): mat[i+2, :] = np.roll(mat[i+2, :], -(i+1)) return mat[:,:-3].T print(ti.timeit(sol1, number=100)) print(ti.timeit(sol2, number=100)) </code></pre> <p>which guives:</p> <pre><code>0.026760146000015084 0.0038611710006080102 </code></pre> <p>It uses a for loop but it only iterates over the shorter axis. Also, it should not be hard to adapt this code for other configurations instead of using hardcoded numbers.</p>
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> first item. </p> <pre><code>[[58 58 56 54 52] [56 56 54 52 50] [54 54 52 50 48] [52 52 50 48 46] [50 50 48 46 44] [48 48 46 44 42] [46 46 44 42 40] [44 44 42 40 38] [42 42 40 38 36] [40 40 38 36 34] [38 38 36 34 32] [36 36 34 32 30] [34 34 32 30 None] [32 32 30 None None] [30 30 None None None]] </code></pre> <p>The code below works, want it faster without 'for' loop and enumerate.</p> <pre><code>arr = np.empty((0,5), int) for i,e in enumerate(x): arr2 = np.hstack((x[i], x[i:i+4], np.asarray([None]*5)))[:5] arr = np.vstack((arr,arr2)) </code></pre>
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_ext.size-N+1)[:,None]] out = np.column_stack((x,arr2D)) </code></pre> <hr> <p><strong>Approach #2</strong></p> <p>Here's another one using <a href="http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.linalg.hankel.html" rel="nofollow"><code>hankel</code></a> -</p> <pre><code>from scipy.linalg import hankel N = 4 # width factor x_ext = np.concatenate((x,[None]*(N-1))) out = np.column_stack((x,hankel(x_ext[:4], x_ext[3:]).T)) </code></pre> <hr> <p><strong>Runtime test</strong></p> <p>Here's a modified version of <a href="http://stackoverflow.com/a/39024845/3293881"><code>@Aaron's benchmarking script</code></a> using an input format for this post identical to the one used for his post in that script for a fair benchmarking and focusing just on these two approaches -</p> <pre><code>upper_limit = 58 # We will edit this to vary the dataset sizes print "Timings are : " t = time() for _ in range(1000): #1000 iterations of @Aaron's soln. width = 3 x = np.array(range(upper_limit,28,-2) + [float('nan')]*width) arr = np.empty([len(x)-width, width+2]) arr[:,0] = x[:len(x)-width] for i in xrange(len(x)-width): arr[i,1:] = x[i:i+width+1] print(time()-t) t = time() for _ in range(1000): N = 4 # width factor x_ext = np.array(range(upper_limit,28,-2) + [float('nan')]*(N-1)) arr2D = x_ext[np.arange(N) + np.arange(x_ext.size-N+1)[:,None]] out = np.column_stack((x_ext[:len(x_ext)-N+1],arr2D)) print(time()-t) </code></pre> <p>Case #1 (upper_limit = 58 ) :</p> <pre><code>Timings are : 0.0316879749298 0.0322730541229 </code></pre> <p>Case #2 (upper_limit = 1058 ) :</p> <pre><code>Timings are : 0.680443048477 0.124517917633 </code></pre> <p>Case #3 (upper_limit = 5058 ) :</p> <pre><code>Timings are : 3.28129291534 0.47504901886 </code></pre>
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> first item. </p> <pre><code>[[58 58 56 54 52] [56 56 54 52 50] [54 54 52 50 48] [52 52 50 48 46] [50 50 48 46 44] [48 48 46 44 42] [46 46 44 42 40] [44 44 42 40 38] [42 42 40 38 36] [40 40 38 36 34] [38 38 36 34 32] [36 36 34 32 30] [34 34 32 30 None] [32 32 30 None None] [30 30 None None None]] </code></pre> <p>The code below works, want it faster without 'for' loop and enumerate.</p> <pre><code>arr = np.empty((0,5), int) for i,e in enumerate(x): arr2 = np.hstack((x[i], x[i:i+4], np.asarray([None]*5)))[:5] arr = np.vstack((arr,arr2)) </code></pre>
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 column stack could be eliminated with a little change to the indexing:</p> <pre><code>idx = np.r_[0,np.arange(N)] + np.arange(x_ext.size-N+1)[:,None] </code></pre> <p>this produces</p> <pre><code>array([[ 0, 0, 1, 2, 3], [ 1, 1, 2, 3, 4], [ 2, 2, 3, 4, 5], [ 3, 3, 4, 5, 6], [ 4, 4, 5, 6, 7], ... </code></pre> <p>so the full result is </p> <pre><code>x_ext[idx] </code></pre> <p>================</p> <p>A different approach is to use striding to create a kind of rolling window.</p> <pre><code>as_strided = np.lib.stride_tricks.as_strided arr2D = as_strided(x_ext, shape=(15,4), str‌​ides=(4,4)) </code></pre> <p>This is one of easier applications of <code>as_strided</code>. <code>shape</code> is straight forward - the shape of the desired result (without the repeat column) <code>(x.shape[0],N)</code>.</p> <pre><code>In [177]: x_ext.strides Out[177]: (4,) </code></pre> <p>For 1d array of this type, the step to the next item is 4 bytes. If I reshape the array to 2d with 3 columns, the stride to the next row is 12 - 3*4 (3 offset).</p> <pre><code>In [181]: x_ext.reshape(6,3).strides Out[181]: (12, 4) </code></pre> <p>Using <code>strides=(4,4)</code> means that the step to next row is just 4 bytes, one element in original.</p> <pre><code>as_strided(x_ext,shape=(8,4),strides=(8,4)) </code></pre> <p>produces a 2 item overlap</p> <pre><code>array([[58, 56, 54, 52], [54, 52, 50, 48], [50, 48, 46, 44], [46, 44, 42, 40], .... </code></pre> <p>The potentially dangerous part of <code>as_strided</code> is that it is possible to create an array that samples memory outside of the original data buffer. Usually that appears as large random numbers where <code>None</code> appears in this example. It's the same sort of error that you would encounter if C code if you were careless in using array pointers and indexing.</p> <p>The <code>as_strided</code> array is a view (the repeated values are not copied). So writing to that array could be dangerous. The <code>column_stack</code> with <code>x</code> will make a copy, replicating the repeated values as needed.</p>
3
2016-08-18T19:52:06Z
[ "python", "arrays", "numpy" ]