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
Referencing fields (columns) by field name in Teradata
39,646,631
<p>I am using python (3.4.3) to ODBC to a Teradata database, (rather new to this) I am wondering (if possible) to reference values of rows by their field name as i am looping through them instead of by their list index. (in case i change my tables) Much like a record set in VBA with the ! syntax (recordset!FIELD_NAME)</p> <p>If i run this code,</p> <pre><code>udaExec = teradata.UdaExec (appName="HelloWorld", version="1.0", logConsole=False) session = udaExec.connect(method="odbc", dsn="TEST") cursor = session.cursor() rows = list(cursor.execute("SELECT TOP 1 * FROM RES_TBL")) print(rows) </code></pre> <p>My output is: <code>[&lt;teradata.util.Row object at 0x000000000402D080&gt;]</code></p> <p>I eventually was able to store each row as string in a list so i could see them\ mess with them, but i feel like thats a bad idea for larger data sets. I am sorry if this is not a good question, but anything helps!!</p> <p>my full code currently is:</p> <pre><code>import teradata import pyodbc import json udaExec = teradata.UdaExec (appName="HelloWorld", version="1.0", logConsole=False) session = udaExec.connect(method="odbc", dsn="TEST") cursor = session.cursor() rows = list(cursor.execute("SELECT TOP 1 * FROM RES_TBL")) print(rows) for row in session.execute("SELECT TOP 1 * FROM RES_TBL"): testlist = [] testlist.append(str(row)) print(testlist) </code></pre>
0
2016-09-22T18:42:57Z
39,647,924
<p>Hello for anyone else that is trying to figure this out, I HAVE SOLVED IT w00t!</p> <p>I found great links for help here, there are some programming wizzards in those links, i learned lots!! <a href="http://stackoverflow.com/questions/3286525/return-sql-table-as-json-in-python">return SQL table as JSON in python</a></p> <p><a href="http://stackoverflow.com/questions/16519385/output-pyodbc-cursor-results-as-python-dictionary">Output pyodbc cursor results as python dictionary</a></p> <p><a href="http://developer.teradata.com/tools/reference/teradata-python-module" rel="nofollow">http://developer.teradata.com/tools/reference/teradata-python-module</a></p> <p>Here is the solution!!!</p> <pre><code>import teradata import pyodbc import json ###Dev environment for learning teradata interactions with python #form the ODBC connection to teradata try: udaExec = teradata.UdaExec (appName="HelloWorld", version="1.0", logConsole=False) session = udaExec.connect(method="odbc", dsn="TEST") cursor = session.cursor() columnNames = [] rows = cursor.execute("SELECT TOP 1 * FROM RES_TBL") for col in rows.description: columnNames.append(col[0]) for row in rows: #session.execute("SELECT TOP 1 * FROM RES_TBL"): testlist = [] testlist.append(dict(zip(columnNames, row))) print(testlist) except: raise finally: cursor.close() </code></pre>
0
2016-09-22T20:01:18Z
[ "python", "teradata" ]
Referencing fields (columns) by field name in Teradata
39,646,631
<p>I am using python (3.4.3) to ODBC to a Teradata database, (rather new to this) I am wondering (if possible) to reference values of rows by their field name as i am looping through them instead of by their list index. (in case i change my tables) Much like a record set in VBA with the ! syntax (recordset!FIELD_NAME)</p> <p>If i run this code,</p> <pre><code>udaExec = teradata.UdaExec (appName="HelloWorld", version="1.0", logConsole=False) session = udaExec.connect(method="odbc", dsn="TEST") cursor = session.cursor() rows = list(cursor.execute("SELECT TOP 1 * FROM RES_TBL")) print(rows) </code></pre> <p>My output is: <code>[&lt;teradata.util.Row object at 0x000000000402D080&gt;]</code></p> <p>I eventually was able to store each row as string in a list so i could see them\ mess with them, but i feel like thats a bad idea for larger data sets. I am sorry if this is not a good question, but anything helps!!</p> <p>my full code currently is:</p> <pre><code>import teradata import pyodbc import json udaExec = teradata.UdaExec (appName="HelloWorld", version="1.0", logConsole=False) session = udaExec.connect(method="odbc", dsn="TEST") cursor = session.cursor() rows = list(cursor.execute("SELECT TOP 1 * FROM RES_TBL")) print(rows) for row in session.execute("SELECT TOP 1 * FROM RES_TBL"): testlist = [] testlist.append(str(row)) print(testlist) </code></pre>
0
2016-09-22T18:42:57Z
39,680,905
<p>Maybe you don't want to use pandas for some reason but otherwise I'd suggest this:</p> <pre><code>import pandas ad pd cursor = session.execute(SQL_script) df = pd.DataFrame.from_records(cursor) cols = [] for row in cursor.description: cols.append(row[0]) df.columns = cols session.close() </code></pre>
1
2016-09-24T20:57:31Z
[ "python", "teradata" ]
How to create a new column in Python Dataframe by referencing two other columns?
39,646,634
<p>I have a dataframe that looks something like this:</p> <pre><code>df = pd.DataFrame({'Name':['a','a','a','a','b','b','b'], 'Year':[1999,1999,1999,2000,1999,2000,2000], 'Name_id':[1,1,1,1,2,2,2]}) Name Name_id Year 0 a 1 1999 1 a 1 1999 2 a 1 1999 3 a 1 2000 4 b 2 1999 5 b 2 2000 6 b 2 2000 </code></pre> <p>What I'd like to have is a new column 'yr_name_id' that increases for each unique Name_id-Year combination and then begins anew with each new Name_id.</p> <pre><code> Name Name_id Year yr_name_id 0 a 1 1999 1 1 a 1 1999 1 2 a 1 1999 1 3 a 1 2000 2 4 b 2 1999 1 5 b 2 2000 2 6 b 2 2000 2 </code></pre> <p>I've tried a variety of things and looked <a href="http://stackoverflow.com/questions/21420187/getting-previous-row-values-from-within-pandas-apply-function">here</a>, <a href="http://stackoverflow.com/questions/16698415/reference-previous-row-when-iterating-through-dataframe">here</a> and at a few posts on groupby and enumerate. </p> <p>At first I tried creating a unique dictionary after combining Name_id and Year and then using map to assign values, but when I try to combine Name_id and Year as strings via:</p> <pre><code>df['yr_name_id'] = str(df['Name_id']) + str(df['Year']) </code></pre> <p>The new column has a non-unique syntax of <code>0 0 1\n1 1\n2 1\n3 1\n4 2\n5 2...</code> which I don't really understand. </p> <p>A more promising approach that I think I just need help with the lambda is by using groupby</p> <pre><code>df['yr_name_id'] = df.groupby(['Name_id', 'Year'])['Name_id'].transform(lambda x: )#unsure from this point </code></pre> <p>I am very unfamiliar with lambda's so any guidance on how I might do this would be greatly appreciated.</p>
1
2016-09-22T18:43:07Z
39,646,756
<p>IIUC you can do it this way:</p> <pre><code>In [99]: df['yr_name_id'] = pd.Categorical(pd.factorize(df['Name_id'].astype(str) + '-' + df['Year'].astype(str))[0] + 1) In [100]: df Out[100]: Name Name_id Year yr_name_id 0 a 1 1999 1 1 a 1 1999 1 2 a 1 1999 1 3 a 1 2000 2 4 b 2 1999 3 5 b 2 2000 4 6 b 2 2000 4 In [101]: df.dtypes Out[101]: Name object Name_id int64 Year int64 yr_name_id category dtype: object </code></pre> <p>But looking at your desired DF, it looks like you want to categorize just a <code>Year</code> column, <strong>not</strong> a combination of <code>Name_id</code> + <code>Year</code></p> <pre><code>In [102]: df['yr_name_id'] = pd.Categorical(pd.factorize(df.Year)[0] + 1) In [103]: df Out[103]: Name Name_id Year yr_name_id 0 a 1 1999 1 1 a 1 1999 1 2 a 1 1999 1 3 a 1 2000 2 4 b 2 1999 1 5 b 2 2000 2 6 b 2 2000 2 In [104]: df.dtypes Out[104]: Name object Name_id int64 Year int64 yr_name_id category dtype: object </code></pre>
1
2016-09-22T18:48:41Z
[ "python", "pandas", "dataframe" ]
How to create a new column in Python Dataframe by referencing two other columns?
39,646,634
<p>I have a dataframe that looks something like this:</p> <pre><code>df = pd.DataFrame({'Name':['a','a','a','a','b','b','b'], 'Year':[1999,1999,1999,2000,1999,2000,2000], 'Name_id':[1,1,1,1,2,2,2]}) Name Name_id Year 0 a 1 1999 1 a 1 1999 2 a 1 1999 3 a 1 2000 4 b 2 1999 5 b 2 2000 6 b 2 2000 </code></pre> <p>What I'd like to have is a new column 'yr_name_id' that increases for each unique Name_id-Year combination and then begins anew with each new Name_id.</p> <pre><code> Name Name_id Year yr_name_id 0 a 1 1999 1 1 a 1 1999 1 2 a 1 1999 1 3 a 1 2000 2 4 b 2 1999 1 5 b 2 2000 2 6 b 2 2000 2 </code></pre> <p>I've tried a variety of things and looked <a href="http://stackoverflow.com/questions/21420187/getting-previous-row-values-from-within-pandas-apply-function">here</a>, <a href="http://stackoverflow.com/questions/16698415/reference-previous-row-when-iterating-through-dataframe">here</a> and at a few posts on groupby and enumerate. </p> <p>At first I tried creating a unique dictionary after combining Name_id and Year and then using map to assign values, but when I try to combine Name_id and Year as strings via:</p> <pre><code>df['yr_name_id'] = str(df['Name_id']) + str(df['Year']) </code></pre> <p>The new column has a non-unique syntax of <code>0 0 1\n1 1\n2 1\n3 1\n4 2\n5 2...</code> which I don't really understand. </p> <p>A more promising approach that I think I just need help with the lambda is by using groupby</p> <pre><code>df['yr_name_id'] = df.groupby(['Name_id', 'Year'])['Name_id'].transform(lambda x: )#unsure from this point </code></pre> <p>I am very unfamiliar with lambda's so any guidance on how I might do this would be greatly appreciated.</p>
1
2016-09-22T18:43:07Z
39,647,671
<p>Use <code>itertools.count</code>:</p> <pre><code>from itertools import count counter = count(1) df['yr_name_id'] = (df.groupby(['Name_id', 'Year'])['Name_id'] .transform(lambda x: next(counter))) </code></pre> <p>Output:</p> <pre class="lang-none prettyprint-override"><code> Name Name_id Year yr_name_id 0 a 1 1999 1 1 a 1 1999 1 2 a 1 1999 1 3 a 1 2000 2 4 b 2 1999 3 5 b 2 2000 4 6 b 2 2000 4 </code></pre>
0
2016-09-22T19:45:54Z
[ "python", "pandas", "dataframe" ]
Python exception base class vs. specific exception
39,646,635
<p>I just wonder, when using try.. except, what's the difference between using the Base class "Except" and using a specific exception like "ImportError" or "IOError" or any other specific exception. Are there pros and cons between one and the other?</p>
-2
2016-09-22T18:43:09Z
39,646,704
<p>Never catch the base exception. Always capture only the specific exceptions that you know how to handle. Everything else should be left alone; otherwise you are potentially hiding important errors.</p>
5
2016-09-22T18:46:03Z
[ "python", "exception", "exception-handling" ]
Python exception base class vs. specific exception
39,646,635
<p>I just wonder, when using try.. except, what's the difference between using the Base class "Except" and using a specific exception like "ImportError" or "IOError" or any other specific exception. Are there pros and cons between one and the other?</p>
-2
2016-09-22T18:43:09Z
39,646,747
<p>Of course it has advantages using the correct exception for the corresponding issue. However Python already defined all possible errors for coding problems. But you can make your own exception classes by inheriting from the <code>Exception</code> class. This way you can make more meaningful errors for spesific parts of your code. You can even make the expections print errors like this.</p> <pre><code>SomeError: 10 should have been 5. </code></pre> <p>Provides easier debugging of the code.</p> <p><a href="http://stackoverflow.com/questions/1319615/proper-way-to-declare-custom-exceptions-in-modern-python">For more info.</a></p>
0
2016-09-22T18:48:20Z
[ "python", "exception", "exception-handling" ]
How to save stack of arrays to .csv when there is a mismatch between array dtype and format specifier?
39,646,653
<p>These are my stacks of arrays, both with variables arranged columnwise.</p> <pre><code>final_a = np.stack((four, five, st, dist, ru), axis=-1) final_b = np.stack((org, own, origin, init), axis=-1) </code></pre> <p>Example:</p> <pre><code>In: final_a Out: array([['9999', '10793', ' 1', '99', '2'], ['9999', '10799', ' 1', '99', '2'], ['9999', '10712', ' 1', '99', '2'], ..., ['9999', '23960', '33', '99', '1'], ['9999', '82920', '33', '99', '2'], ['9999', '82920', '33', '99', '2']], dtype='&lt;U5') </code></pre> <p>But when I try to save either of them to a .csv file using this code:</p> <pre><code>np.savetxt("/Users/jaisaranc/Documents/ASI selected data - A.csv", final_a, delimiter=",") </code></pre> <p>It throws this error:</p> <pre><code>TypeError: Mismatch between array dtype ('&lt;U5') and format specifier ('%.18e,%.18e,%.18e,%.18e,%.18e') </code></pre> <p>I have no idea what to do.</p>
0
2016-09-22T18:43:56Z
39,648,947
<p><code>savetxt</code> in Numpy allows you <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.savetxt.html" rel="nofollow">specify a format</a> for how the array will be displayed when it's written to a file. The default format (<code>fmt='%.18e'</code>) can only format arrays containing only numeric elements. Your array contains strings (<code>dtype='&lt;U5'</code> means the type is unicode with length 5) so it raises an error. In your case you should also include <code>fmt='%s'</code> as an argument to ensure the array elements in the output file are formatted as strings. For example:</p> <pre><code>np.savetxt("example.csv", final_a, delimeter=",", fmt="%s") </code></pre>
0
2016-09-22T21:12:15Z
[ "python", "arrays", "python-3.x", "csv" ]
How to find out number of unique rows within a pandas groupby object?
39,646,728
<p>I know that we can use .nunique() on a groupby column to find out the unique number of elements in the column like below:</p> <pre><code>df = pd.DataFrame({'c1':['foo', 'bar', 'foo', 'foo'], 'c2': ['A', 'B', 'A', 'B'], 'c3':[1, 2, 1, 1]}) c1 c2 c3 0 foo A 1 1 bar B 2 2 foo A 1 3 foo B 1 df.groupby('c1')['c2'].nunique() c1 bar 1 foo 2 Name: c2, dtype: int64 </code></pre> <p>However, now I have a groupby object that contains multiple columns, is there any way to find out the number of unique rows?</p> <pre><code>df.groupby('c1')['c2', 'c3'].??? </code></pre> <hr> <p>Update: So the end result I want is the number of unique rows within each group that's grouped based on the 'c1' column, such as this:</p> <pre><code>foo 2 bar 1 </code></pre> <hr> <p>Update 2: Here's a new test dataframe:</p> <pre><code>df = pd.DataFrame({'c1': ['foo', 'bar', 'foo', 'foo', 'bar'], 'c2': ['A' , 'B', 'A', 'B', 'A'], 'c3': [1, 2, 1, 1, 1]}) </code></pre>
1
2016-09-22T18:47:22Z
39,646,832
<p><strong>UPDATE:</strong></p> <pre><code>In [131]: df.groupby(['c1','c2','c3']).size().rename('count').reset_index()[['c1','count']].drop_duplicates(subset=['c1']) Out[131]: c1 count 0 bar 1 1 foo 2 </code></pre> <p><strong>OLD answer:</strong></p> <p>IIYC you need this:</p> <pre><code>In [43]: df.groupby(['c1','c2','c3']).size() Out[43]: c1 c2 c3 bar B 2 1 foo A 1 2 B 1 1 dtype: int64 </code></pre>
1
2016-09-22T18:52:49Z
[ "python", "pandas", "dataframe", "group-by" ]
How to find out number of unique rows within a pandas groupby object?
39,646,728
<p>I know that we can use .nunique() on a groupby column to find out the unique number of elements in the column like below:</p> <pre><code>df = pd.DataFrame({'c1':['foo', 'bar', 'foo', 'foo'], 'c2': ['A', 'B', 'A', 'B'], 'c3':[1, 2, 1, 1]}) c1 c2 c3 0 foo A 1 1 bar B 2 2 foo A 1 3 foo B 1 df.groupby('c1')['c2'].nunique() c1 bar 1 foo 2 Name: c2, dtype: int64 </code></pre> <p>However, now I have a groupby object that contains multiple columns, is there any way to find out the number of unique rows?</p> <pre><code>df.groupby('c1')['c2', 'c3'].??? </code></pre> <hr> <p>Update: So the end result I want is the number of unique rows within each group that's grouped based on the 'c1' column, such as this:</p> <pre><code>foo 2 bar 1 </code></pre> <hr> <p>Update 2: Here's a new test dataframe:</p> <pre><code>df = pd.DataFrame({'c1': ['foo', 'bar', 'foo', 'foo', 'bar'], 'c2': ['A' , 'B', 'A', 'B', 'A'], 'c3': [1, 2, 1, 1, 1]}) </code></pre>
1
2016-09-22T18:47:22Z
39,646,943
<p>If need by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.SeriesGroupBy.nunique.html" rel="nofollow"><code>nunique</code></a> concanecated column <code>c2</code> and <code>c3</code>, the easier is use:</p> <pre><code>df['c'] = df.c2 + df.c3.astype(str) print (df.groupby('c1')['c'].nunique()) c1 bar 1 foo 2 Name: c, dtype: int64 </code></pre> <p>Or <code>groupby</code> by <code>Series</code> <code>c</code> by column <code>df.c1</code>:</p> <pre><code>c = df.c2.astype(str) + df.c3.astype(str) print (c.groupby([df.c1]).nunique()) c1 bar 2 foo 2 dtype: int64 </code></pre>
0
2016-09-22T19:00:07Z
[ "python", "pandas", "dataframe", "group-by" ]
How to find out number of unique rows within a pandas groupby object?
39,646,728
<p>I know that we can use .nunique() on a groupby column to find out the unique number of elements in the column like below:</p> <pre><code>df = pd.DataFrame({'c1':['foo', 'bar', 'foo', 'foo'], 'c2': ['A', 'B', 'A', 'B'], 'c3':[1, 2, 1, 1]}) c1 c2 c3 0 foo A 1 1 bar B 2 2 foo A 1 3 foo B 1 df.groupby('c1')['c2'].nunique() c1 bar 1 foo 2 Name: c2, dtype: int64 </code></pre> <p>However, now I have a groupby object that contains multiple columns, is there any way to find out the number of unique rows?</p> <pre><code>df.groupby('c1')['c2', 'c3'].??? </code></pre> <hr> <p>Update: So the end result I want is the number of unique rows within each group that's grouped based on the 'c1' column, such as this:</p> <pre><code>foo 2 bar 1 </code></pre> <hr> <p>Update 2: Here's a new test dataframe:</p> <pre><code>df = pd.DataFrame({'c1': ['foo', 'bar', 'foo', 'foo', 'bar'], 'c2': ['A' , 'B', 'A', 'B', 'A'], 'c3': [1, 2, 1, 1, 1]}) </code></pre>
1
2016-09-22T18:47:22Z
39,648,586
<p>Finally figured out how to do this!</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({'c1': ['foo', 'bar', 'foo', 'foo', 'bar'], 'c2': ['A', 'B', 'A', 'B', 'A'], 'c3': [1, 2, 1, 1, 1]}) def check_unique(df): return len(df.groupby(list(df.columns.values))) print(df.groupby('c1').apply(check_unique)) </code></pre>
0
2016-09-22T20:45:41Z
[ "python", "pandas", "dataframe", "group-by" ]
Sum of Two Integers without using '+' operator in python 2 or 3
39,646,749
<pre><code>class Solution(object): def getSum(self, a, b): if (a == 0): return b if (b == 0): return a; while(b != 0): _a = a ^ b _b = (a &amp; b) &lt;&lt; 1 a = _a b = _b return a </code></pre> <p>But when one of a, b &lt; 0 or both, how the script should be like?</p>
1
2016-09-22T18:48:21Z
39,646,861
<p>I enjoy solving other people's problems.</p> <pre><code>class Solution(object): def getSum(self, a, b): return sum([a, b]) </code></pre> <p><strong>Edit:</strong> If you are in for some fantasy. You can do operator overloading.</p> <pre><code>class CrappyInt(int): def __init__(self, num): self.num = num def __eq__(self, a): return self.__add__(a) m = CrappyInt(3) n = CrappyInt(4) print m == n # 7 </code></pre> <p>This maybe a little hard for you now. But it is fun.</p>
0
2016-09-22T18:54:21Z
[ "python" ]
Sum of Two Integers without using '+' operator in python 2 or 3
39,646,749
<pre><code>class Solution(object): def getSum(self, a, b): if (a == 0): return b if (b == 0): return a; while(b != 0): _a = a ^ b _b = (a &amp; b) &lt;&lt; 1 a = _a b = _b return a </code></pre> <p>But when one of a, b &lt; 0 or both, how the script should be like?</p>
1
2016-09-22T18:48:21Z
39,646,900
<p>You can also use <a href="https://docs.python.org/3/library/operator.html" rel="nofollow"><code>operator</code></a> package</p> <pre><code>import operator class Solution(object): def getSum(self, a, b): return operator.add(a, b) </code></pre> <p>And if you want to hassle with binary bitwise operations. Here is first method:</p> <pre><code>def complex_add_1(x, y): while y != 0: b = x &amp; y x = x ^ y y = b &lt;&lt; 1 return x </code></pre> <p>And here is the another one with recursion:</p> <pre><code>def complex_add_2(x, y): if y == 0: return x else: return complex_add_2(x ^ y, (x &amp; y) &lt;&lt; 1) </code></pre> <p><strong>Edit</strong>: methods with bitwise operations are working only in Python 3</p>
0
2016-09-22T18:57:01Z
[ "python" ]
Sum of Two Integers without using '+' operator in python 2 or 3
39,646,749
<pre><code>class Solution(object): def getSum(self, a, b): if (a == 0): return b if (b == 0): return a; while(b != 0): _a = a ^ b _b = (a &amp; b) &lt;&lt; 1 a = _a b = _b return a </code></pre> <p>But when one of a, b &lt; 0 or both, how the script should be like?</p>
1
2016-09-22T18:48:21Z
39,646,912
<p><code>+</code> operator internally makes a call to <code>__add__()</code>. So, you may directly call <code>a.__add__(b)</code> to get sum. Below is the modified code:</p> <pre><code>&gt;&gt;&gt; class Solution(object): ... def getSum(self, a, b): ... return a.__add__(b) ... &gt;&gt;&gt; s = Solution() &gt;&gt;&gt; s.getSum(1, 2) 3 </code></pre> <p><strong>OR</strong>, you may use <a href="https://docs.python.org/2/library/operator.html#operator.add" rel="nofollow"><code>operator.add(a, b)</code></a> as:</p> <pre><code>&gt;&gt;&gt; import operator &gt;&gt;&gt; operator.add(1, 2) 3 </code></pre>
3
2016-09-22T18:57:56Z
[ "python" ]
Sum of Two Integers without using '+' operator in python 2 or 3
39,646,749
<pre><code>class Solution(object): def getSum(self, a, b): if (a == 0): return b if (b == 0): return a; while(b != 0): _a = a ^ b _b = (a &amp; b) &lt;&lt; 1 a = _a b = _b return a </code></pre> <p>But when one of a, b &lt; 0 or both, how the script should be like?</p>
1
2016-09-22T18:48:21Z
39,648,078
<p>My old highschool program that I found on my usb stick. Yes it's crude but it works.</p> <pre><code>def s(a,b): a = bin(a)[2:] b = bin(b)[2:] c_in = 0 value = '' if not len(a) == len(b): to_fill = abs(len(a) - len(b)) if len(a) &gt; len(b): b = b.zfill(len(a)) else: a = a.zfill(len(b)) for i,j in zip(reversed(a),reversed(b)): i_xor_j = int(i) ^ int(j) i_and_j = int(i) and int(j) s = int(c_in) ^ int(i_xor_j) c_in_and_i_xor_j = int(c_in) and int(i_xor_j) c_in = int(i_and_j) or int(c_in_and_i_xor_j) value += str(int(s)) value += str(int(c_in)) return int(value[::-1],2) print(s(5,9)) #&gt;&gt; 14 </code></pre> <p>Or I would have see if I could cheat with <code>sum</code>.</p>
0
2016-09-22T20:12:12Z
[ "python" ]
Sum of Two Integers without using '+' operator in python 2 or 3
39,646,749
<pre><code>class Solution(object): def getSum(self, a, b): if (a == 0): return b if (b == 0): return a; while(b != 0): _a = a ^ b _b = (a &amp; b) &lt;&lt; 1 a = _a b = _b return a </code></pre> <p>But when one of a, b &lt; 0 or both, how the script should be like?</p>
1
2016-09-22T18:48:21Z
39,648,430
<p>This was kinda fun :) I'm not sure if this is what you're after, but these all should work so long as you're using integers</p> <pre class="lang-python prettyprint-override"><code>def subtract(a, b): if a &lt; 0: return negative(add(negative(a), b)) if b &lt; 0: return add(a, negative(b)) if a &lt; b: return negative(subtract(b, a)) if b == 0: return a return subtract(a^b, (~a &amp; b) &lt;&lt; 1) def negative(a): if a == 0: return 0 a = ~a b = 1 while b &gt; 0: a, b = a^b, (a&amp;b) &lt;&lt; 1 return a def add(a, b): if a &lt; 0: return negative(subtract(negative(a), b)) if b &lt; 0: return subtract(a, negative(b)) if b == 0: return a return add(a^b, (a &amp; b) &lt;&lt; 1) def multiply(a, b): if a == 0 or b == 0: return 0 if b &lt; 0: a = negative(a) b = negative(b) A = 0 while b &gt; 0: A = add(A, a) b = subtract(b, 1) return A def div(a, b): if b == 0: raise ZeroDivisionError if a == 0: return 0 if b &lt; 0: a = negative(a) b = negative(b) A = 0 if a &lt; 0: while a &lt; 0: a = add(a, b) A = subtract(A, 1) else: while b &lt; a : a = subtract(a, b) A = add(A, 1) return A def mod(a, b): return subtract(a, multiply(div(a, b),b)) </code></pre> <p>negation by <a href="https://en.wikipedia.org/wiki/Two%27s_complement" rel="nofollow">two's compliment</a> is used to get a function where a and b are both greater than 0 and the correct operation (addition or subtraction) is selected. further with subtraction, care is taken to not yield a negative result. This is done because the recursive definitions of add and subtract hate crossing 0. Also in this case the recursive add and subtract do the exact same thing as your loop. </p>
0
2016-09-22T20:36:21Z
[ "python" ]
Modules and variable scopes
39,646,760
<p>I'm not an expert at python, so bear with me while I try to understand the nuances of variable scopes.</p> <p>As a simple example that describes the problem I'm facing, say I have the following three files.</p> <p>The first file is outside_code.py. Due to certain restrictions I cannot modify this file. It must be taken as is. It contains some code that runs an eval at some point (yes, I know that eval is the spawn of satan but that's a discussion for a later day). For example, let's say that it contains the following lines of code:</p> <pre><code>def eval_string(x): return eval(x) </code></pre> <p>The second file is a set of user defined functions. Let's call it functions.py. It contains some unknown number of function definitions, for example, let's say that functions.py contains one function, defined below:</p> <pre><code>def foo(x): print("Your number is {}!".format(x)) </code></pre> <p>Now I write a third file, let's call it main.py. Which contains the following code:</p> <pre><code>import outside_code from functions import * outside_code.eval_string("foo(4)") </code></pre> <p>I import all of the function definitions from functions.py with a *, so they should be accessible by main.py without needing to do something like functions.foo(). I also import outside_code.py so I can access its core functionality, the code that contains an eval. Finally I call the function in outside_code.py, passing a string that is related to a function defined in functions.py.</p> <p>In the simplified example, I want the code to print out "Your number is 4!". However, I get an error stating that 'foo' is not defined. This obviously means that the code in outside_code.py cannot access the same foo function that exists in main.py. So somehow I need to make foo accessible to it. Could anyone tell me exactly what the scope of foo currently is, and how I could extend it to cover the space that I actually want to use it in? What is the best way to solve my problem?</p>
3
2016-09-22T18:48:48Z
39,646,839
<p><code>foo</code> has been imported into main.py; its scope is restricted to that file (and to the file where it was originally defined, of course). It does not exist within outside_code.py.</p> <p>The real <code>eval</code> function accepts locals and globals dicts to allow you to add elements to the namespace of the evaluted code. But you can't do anything if your <code>eval_string</code> doesn't already pass those on.</p>
1
2016-09-22T18:53:11Z
[ "python", "python-3.x" ]
Modules and variable scopes
39,646,760
<p>I'm not an expert at python, so bear with me while I try to understand the nuances of variable scopes.</p> <p>As a simple example that describes the problem I'm facing, say I have the following three files.</p> <p>The first file is outside_code.py. Due to certain restrictions I cannot modify this file. It must be taken as is. It contains some code that runs an eval at some point (yes, I know that eval is the spawn of satan but that's a discussion for a later day). For example, let's say that it contains the following lines of code:</p> <pre><code>def eval_string(x): return eval(x) </code></pre> <p>The second file is a set of user defined functions. Let's call it functions.py. It contains some unknown number of function definitions, for example, let's say that functions.py contains one function, defined below:</p> <pre><code>def foo(x): print("Your number is {}!".format(x)) </code></pre> <p>Now I write a third file, let's call it main.py. Which contains the following code:</p> <pre><code>import outside_code from functions import * outside_code.eval_string("foo(4)") </code></pre> <p>I import all of the function definitions from functions.py with a *, so they should be accessible by main.py without needing to do something like functions.foo(). I also import outside_code.py so I can access its core functionality, the code that contains an eval. Finally I call the function in outside_code.py, passing a string that is related to a function defined in functions.py.</p> <p>In the simplified example, I want the code to print out "Your number is 4!". However, I get an error stating that 'foo' is not defined. This obviously means that the code in outside_code.py cannot access the same foo function that exists in main.py. So somehow I need to make foo accessible to it. Could anyone tell me exactly what the scope of foo currently is, and how I could extend it to cover the space that I actually want to use it in? What is the best way to solve my problem?</p>
3
2016-09-22T18:48:48Z
39,646,859
<p>The relevant documentation: <a href="https://docs.python.org/3.5/library/functions.html#eval" rel="nofollow">https://docs.python.org/3.5/library/functions.html#eval</a> </p> <p><code>eval</code> takes an optional dictionary mapping global names to values</p> <pre><code>eval('foo(4)', {'foo': foo}) </code></pre> <p>Will do what you need. It is mapping the string 'foo' to the function object foo.</p> <p>EDIT</p> <p>Rereading your question, it looks like this won't work for you. My only other thought is to try </p> <pre><code>eval_str('eval("foo(4)", {"foo": lambda x: print("Your number is {}!".format(x))})') </code></pre> <p>But that's a very hackish solution and doesn't scale well to functions that don't fit in lambdas.</p>
1
2016-09-22T18:54:06Z
[ "python", "python-3.x" ]
Modules and variable scopes
39,646,760
<p>I'm not an expert at python, so bear with me while I try to understand the nuances of variable scopes.</p> <p>As a simple example that describes the problem I'm facing, say I have the following three files.</p> <p>The first file is outside_code.py. Due to certain restrictions I cannot modify this file. It must be taken as is. It contains some code that runs an eval at some point (yes, I know that eval is the spawn of satan but that's a discussion for a later day). For example, let's say that it contains the following lines of code:</p> <pre><code>def eval_string(x): return eval(x) </code></pre> <p>The second file is a set of user defined functions. Let's call it functions.py. It contains some unknown number of function definitions, for example, let's say that functions.py contains one function, defined below:</p> <pre><code>def foo(x): print("Your number is {}!".format(x)) </code></pre> <p>Now I write a third file, let's call it main.py. Which contains the following code:</p> <pre><code>import outside_code from functions import * outside_code.eval_string("foo(4)") </code></pre> <p>I import all of the function definitions from functions.py with a *, so they should be accessible by main.py without needing to do something like functions.foo(). I also import outside_code.py so I can access its core functionality, the code that contains an eval. Finally I call the function in outside_code.py, passing a string that is related to a function defined in functions.py.</p> <p>In the simplified example, I want the code to print out "Your number is 4!". However, I get an error stating that 'foo' is not defined. This obviously means that the code in outside_code.py cannot access the same foo function that exists in main.py. So somehow I need to make foo accessible to it. Could anyone tell me exactly what the scope of foo currently is, and how I could extend it to cover the space that I actually want to use it in? What is the best way to solve my problem?</p>
3
2016-09-22T18:48:48Z
39,646,997
<p>You'd have to add those names to the scope of <code>outside_code</code>. If <code>outside_code</code> is a regular Python module, you can do so directly:</p> <pre><code>import outside_code import functions for name in getattr(functions, '__all__', (n for n in vars(functions) if not n[0] == '_')): setattr(outside_code, name, getattr(functions, name)) </code></pre> <p>This takes all names <code>functions</code> exports (which you'd import with <code>from functions import *</code>) and adds a reference to the corresponding object to <code>outside_code</code> so that <code>eval()</code> inside <code>outside_code.eval_string()</code> can find them.</p> <p>You could use the <a href="https://docs.python.org/2/library/ast.html#ast.parse" rel="nofollow"><code>ast.parse()</code> function</a> to produce a parse tree from the expression before passing it to <code>eval_function()</code> and then extract all global names from the expression and only add <em>those</em> names to <code>outside_code</code> to limit the damage, so to speak, but you'd still be clobbering the other module namespace to make this work.</p> <p>Mind you, this is almost as evil as using <code>eval()</code> in the first place, but it's your only choice if you can't tell <code>eval()</code> in that other module to take a namespace parameter. That's because <em>by default</em>, <code>eval()</code> uses the global namespace of the module it is run in as the namespace.</p> <p>If, however, your <code>eval_string()</code> function actually accepts more parameters, look for a namespace or <code>globals</code> option. If that exists, the function probably looks more like this:</p> <pre><code>def eval_string(x, namespace=None): return eval(x, globals=namespace) </code></pre> <p>after which you could just do:</p> <pre><code>outside_code.eval_string('foo(4)', vars(functions)) </code></pre> <p>where <code>vars(functions)</code> gives you the namespace of the <code>functions</code> module.</p>
1
2016-09-22T19:03:18Z
[ "python", "python-3.x" ]
Compile error in Java corenlp sentiment score program via py4j in Python
39,646,779
<p>I mainly use Python and new to Java. However I am trying to write a Java program and make it work in Python via Py4j Python package. Following program is what I adapted from an example. I encountered a compile error. Could you shed some light? I am pretty sure it is basic error. Thanks. </p> <pre><code>&gt; compile error: incompatible type: SimpleMatrix cannot be converted to String: return senti_scores. &gt; intended input in Python: app = CoreNLPSentiScore() app.findSentiment("I like this book") intended output: matrix: Type = dense , numRows = 5 , numCols = 1 0.016 0.037 0.132 0.618 0.196 import java.util.List; import java.util.Properties; import edu.stanford.nlp.ling.CoreAnnotations; import edu.stanford.nlp.neural.rnn.RNNCoreAnnotations; import edu.stanford.nlp.pipeline.Annotation; import edu.stanford.nlp.pipeline.StanfordCoreNLP; import edu.stanford.nlp.sentiment.SentimentCoreAnnotations.SentimentAnnotatedTree; import edu.stanford.nlp.trees.Tree; import edu.stanford.nlp.util.ArrayCoreMap; import edu.stanford.nlp.util.CoreMap; import py4j.GatewayServer; import org.ejml.simple.SimpleMatrix; public class CoreNLPSentiScore { static StanfordCoreNLP pipeline; public static void init() { Properties props = new Properties(); props.setProperty("annotators", "tokenize, ssplit, parse, sentiment"); pipeline = new StanfordCoreNLP(props); } public static void main(String[] args) { CoreNLPSentiScore app = new CoreNLPSentiScore(); // app is now the gateway.entry_point GatewayServer server = new GatewayServer(app); server.start(); } //public static void main(String tweet) { //public static String findSentiment(String tweet) { public String findSentiment(String tweet) { //String SentiReturn = "2"; //String[] SentiClass ={"very negative", "negative", "neutral", "positive", "very positive"}; //Sentiment is an integer, ranging from 0 to 4. //0 is very negative, 1 negative, 2 neutral, 3 positive and 4 very positive. //int sentiment = 2; SimpleMatrix senti_score = new SimpleMatrix(); if (tweet != null &amp;&amp; tweet.length() &gt; 0) { Annotation annotation = pipeline.process(tweet); List&lt;CoreMap&gt; sentences = annotation.get(CoreAnnotations.SentencesAnnotation.class); if (sentences != null &amp;&amp; sentences.size() &gt; 0) { ArrayCoreMap sentence = (ArrayCoreMap) sentences.get(0); //Tree tree = sentence.get(SentimentAnnotatedTree.class); Tree tree = sentence.get(SentimentAnnotatedTree.class); senti_score = RNNCoreAnnotations.getPredictions(tree); //SentiReturn = SentiClass[sentiment]; } } //System.out.println(senti_score); return senti_score; //System.out.println(senti_score); } } </code></pre>
0
2016-09-22T18:50:04Z
39,647,079
<p>Java is object oriented program but it is not like python where everything is considered as object. </p> <p>In your program mentioned above. There is a method findsentiment is returning SimpleMatrix but in the method declaration it is String. </p> <p>Solution - You can overide a method toString() in your class SimpleMatrix and while returning senti_score return senti_score.toString() </p>
1
2016-09-22T19:07:54Z
[ "java", "python", "corenlp", "py4j" ]
Using Python to Call Excel Macro That Opens All Files in a Folder
39,646,877
<p>I have a simple python program (shown here in block 1), that I am using to open an Excel file and call a macro (shown here in block 2). The macro opens all excel files in a specific folder. The Python I have works to open the Excel files and call macros (I've tested it with different files), but for some reason when I try to call this file with this macro it doesn't work (opens the excel file, but the macro doesn't run to open all xlsx files in the folder). Has anyone encountered this before? If so, have you been able to resolve the issue? <strong><em>Here is the Python</em></strong></p> <pre><code>from win32com.client import Dispatch xl = Dispatch('Excel.Application') wb = xl.Workbooks.Open("K:\\updatebloomberg.xlsm") xl.Visible = True wb.Application.Run("'updatebloomberg.xlsm'!Module1.runfiles()") wb.Close(True) </code></pre> <p><strong>and here is the VBA</strong></p> <pre><code>Sub runfiles() Dim wb As Workbook Dim myPath As String Dim myFile As String Dim myExtension As String Dim ws As Worksheet Dim c As Range myPath = "K:\Bloomberg Data\" myExtension = "*.xlsx" myFile = Dir(myPath &amp; myExtension) Do While myFile &lt;&gt; "" Set wb = Workbooks.Open(Filename:=myPath &amp; myFile) myFile = Dir Loop Application.OnTime (Now + TimeValue("00:00:02")), "refreshSheet" End Sub </code></pre>
1
2016-09-22T18:55:23Z
39,646,907
<p>why on eartth would you do this????</p> <pre><code>import glob for fnam in glob.glob("K:\Bloomberg Data\*.xlsx"): os.startfile(fname) </code></pre> <p>if that doesnt work have you checked that your network drive ((K i assume is a network drive) doesnt have an X over it when you look in file explorer)</p>
2
2016-09-22T18:57:37Z
[ "python", "excel", "vba", "macros" ]
How to recursively get absolute url from parent instance(s)?
39,646,917
<p>I have a page model that contains instance of itself as possible parent page. So every page can be child of another page. What I would like to do is get the absolute url to give me link that is structured according to its parent architecture. So let's say I have a Page AAA with child BBB, which itself has a child CCC. The url of last child would be mysite.com/AAA/BBB/CCC. I've played around and figured a recursive method that would work for me, however I hit a brick wall on resolving the urls.</p> <p><strong>models.py</strong></p> <pre><code>class Page { ... parent = models.ForeignKey('self', null=True, blank=True, unique=False) .... def get_parent_path(self, list=None): parenturl = [] if list is not None: parenturl = list if self.parent is not None: parenturl.insert(0,self.parent.slug) return self.parent.get_parent_path(parenturl) return parenturl def get_absolute_url(self): path = '' if self.parent is not None: parentlisting = self.get_parent_path() for parent in parentlisting: path = path + parent + '/' path = path + self.slug; return reverse("pages:details", kwargs={"path": path, "slug": self.slug}) </code></pre> <p><strong>urls.py</strong></p> <pre><code> url(r'^(?P&lt;path&gt;.+)(?P&lt;slug&gt;[\w-]+)/$', views.page, name='details'), </code></pre> <p>Testing it, showed me that path I get gives the correct parental part of the path. But resolving urls doesn't seem to work and I'm thinking it has something to do with reverse and/or regex. Using any page link, even where 404 should be, will now give me type error.</p> <pre><code>TypeError at /###/###/ page() got an unexpected keyword argument 'path' </code></pre> <p>What am I doing wrong?</p> <p>EDIT:</p> <p><strong>views.py</strong></p> <pre><code>def page(request, slug): instance = get_object_or_404(Page, slug=slug) context = { "title": instance.title, "page": instance, } return render(request, "page.html", context) </code></pre>
0
2016-09-22T18:58:11Z
39,646,980
<p>So first of all your <code>page</code> view is not accepting <code>path</code> argument.</p> <p>You need to change <code>def page(request, slug):</code> to <code>def page(request, slug, path):</code>. Also you need to rethink if you need that param in your url and in your view, because you don't use it.</p> <p><strong>Further part might not be relevant</strong></p> <p>And one more thing, you forgot to put <code>/</code> between params in url</p> <pre><code>url(r'^(?P&lt;path&gt;.+)(?P&lt;slug&gt;[\w-]+)/$', views.page, name='details'), </code></pre> <p>should be </p> <pre><code>url(r'^(?P&lt;path&gt;.+)/(?P&lt;slug&gt;[\w-]+)/$', views.page, name='details') </code></pre>
1
2016-09-22T19:02:21Z
[ "python", "django", "resolveurl" ]
from keras.layers import Dense -- cannot import name 'Dense'
39,646,921
<p>I am trying to play around with Keras a little.</p> <p>When I try the following code : </p> <pre><code>from keras.layers import Dense </code></pre> <p>I get the following error:</p> <pre><code>Traceback (most recent call last): File "&lt;pyshell#0&gt;", line 1, in &lt;module&gt; from keras.layers import Dense ImportError: cannot import name 'Dense' </code></pre> <p>I am using Python 3.4.3, I am on a Windows 8 64 bit machine. </p> <p>Thank you.</p>
0
2016-09-22T18:58:18Z
39,647,057
<p>The error is telling you that it found nothing named <code>Dense</code> in that module.</p> <p>Perhaps you meant <code>from keras.layers.core import Dense</code>?</p>
2
2016-09-22T19:06:16Z
[ "python", "keras" ]
How to find why a task fails in dask distributed?
39,647,019
<p>I am developing a distributed computing system using <code>dask.distributed</code>. Tasks that I submit to it with the <code>Executor.map</code> function sometimes fail, while others seeming identical, run successfully. </p> <p>Does the framework provide any means to diagnose problems?</p> <p><strong>update</strong> By failing I mean increasing counter of failed tasks in the Bokeh web UI, provided by the scheduler. Counter of finished tasks increases too.</p> <p>Function that is run by the <code>Executor.map</code> returns <code>None</code>. It communicates to a database, retrieves some rows from its table, performs calculations and updates values. </p> <p>I've got more than 40000 tasks in map, so it is a bit tedious to study logs.</p>
1
2016-09-22T19:04:26Z
39,647,783
<p>If a task fails then any attempt to retrieve the result will raise the same error that occurred on the worker</p> <pre><code>In [1]: from distributed import Client In [2]: c = Client() In [3]: def div(x, y): ...: return x / y ...: In [4]: future = c.submit(div, 1, 0) In [5]: future.result() &lt;ipython-input-3-398a43a7781e&gt; in div() 1 def div(x, y): ----&gt; 2 return x / y ZeroDivisionError: division by zero </code></pre> <p>However, other things can go wrong. For example you might not have the same software on your workers as on your client or your network might not let connections go through, or any of the other things that happen in real-world networks. To help diagnose these there are a few options:</p> <ol> <li>You can use the <a href="http://distributed.readthedocs.io/en/latest/web.html" rel="nofollow">web interface</a> to track the progress of your tasks and workers</li> <li>You can <a href="http://distributed.readthedocs.io/en/latest/ipython.html#launch-ipython-within-dask-workers" rel="nofollow">start IPython kernels</a> in the scheduler or workers to inspect them directly</li> </ol>
2
2016-09-22T19:52:41Z
[ "python", "distributed", "dask" ]
Salt in PBKDF2 - Python
39,647,123
<p>I'm just learning about securing password while developing using MySQL and Python, following <a href="http://www.cyberciti.biz/python-tutorials/securely-hash-passwords-in-python/" rel="nofollow">this tutorial</a>.</p> <p>It's my understanding that the userpassword is stored at the database hashed, and the salt is stored along side unencrypted, so that we can grab the hashed password and the salt, and rehash using the salt the inputted password, then compare the two.</p> <p>Though, when using PBKDF2 (via the <code>passlib.hash.sha256_crypt()</code> function) I can't set my own salt, only its size. So how can I rehash the password using the same salt so I can compare both?</p>
1
2016-09-22T19:10:38Z
39,660,610
<p>The <a href="https://pythonhosted.org/passlib/password_hash_api.html" rel="nofollow">Passlib Password Hash interface</a> either lets you set the salt <em>size</em>, <em>or</em> the <code>salt</code> value itself. From the <a href="https://pythonhosted.org/passlib/lib/passlib.hash.pbkdf2_digest.html#passlib.hash.pbkdf2_sha256" rel="nofollow">documentation on <code>pbkdf2_sha256</code></a>:</p> <blockquote> <ul> <li><p><code>salt</code> (<em>bytes</em>) Optional salt bytes. If specified, the length must be between 0-1024 bytes. If not specified, a 16 byte salt will be autogenerated (this is recommended).</p></li> <li><p><code>salt_size</code> (<em>int</em>) – Optional number of bytes to use when autogenerating new salts. Defaults to 16 bytes, but can be any value between 0 and 1024.</p></li> </ul> </blockquote> <p>so you <em>can</em> set your own pre-generated salt:</p> <pre><code>&gt;&gt;&gt; from passlib.hash import pbkdf2_sha256 &gt;&gt;&gt; pbkdf2_sha256.encrypt("password", rounds=200000, salt=b'spamhameggs') '$pbkdf2-sha256$200000$c3BhbWhhbWVnZ3M$WL9OLVcb3f7HqHeNT./kCJeunydLCi4JykzEuAdewcI' </code></pre> <p>However, note that the salt is part of the returned string. The string contains not only the resulting hash, but also the algorithm, the number of rounds used <em>and</em> the salt used, delimited by <code>$</code>. The salt is <a href="https://pythonhosted.org/passlib/lib/passlib.utils.html#other" rel="nofollow">encoded to modified form of base64</a>. You can verify this by decoding the string <code>c3BhbWhhbWVnZ3M</code> again::</p> <pre><code>&gt;&gt;&gt; from passlib.utils import ab64_decode &gt;&gt;&gt; ab64_decode(b'c3BhbWhhbWVnZ3M') b'spamhameggs' </code></pre> <p>See the <a href="https://pythonhosted.org/passlib/lib/passlib.hash.pbkdf2_digest.html#format-algorithm" rel="nofollow"><em>Format &amp; Algorithm</em></a> section for the <code>pbkdf2_sha256</code> docs.</p> <p>So when you store the full string <code>pbkdf2_sha256</code> in the database, <em>everything to validate the string</em> is right there in the value, including the salt. Leaving generating a random salt is best left to that library as it'll use a secure method to generate one.</p>
1
2016-09-23T12:18:33Z
[ "python", "mysql", "python-3.x", "salt", "pbkdf2" ]
SQLAlchemy expression language: how to join table with subquery?
39,647,217
<p>I have a subquery table <code>inner_stmt</code>, which I want to join with a table <code>revisions</code>. But <code>revisions.join()</code> gives the following error:</p> <pre><code>Neither 'Label' object nor 'Comparator' object has an attribute 'c' </code></pre> <p>Here is my code. What am I doing wrong?</p> <pre><code>inner_stmt = select([ ratings.c.article_name, func.min(ratings.c.timestamp).label('mintime')]) \ .group_by(ratings.c.article_name).label('firstga') stmt = select([ revisions.c.article_id, func.max(revisions.c.length_bytes)]) \ .select_from(revisions.join( inner_stmt, revisions.c.article_name == inner_stmt.c.article_name)) \ .group_by(table.c.article_id) </code></pre>
0
2016-09-22T19:17:03Z
39,667,297
<p>You are <a href="http://docs.sqlalchemy.org/en/latest/core/selectable.html#sqlalchemy.sql.expression.SelectBase.label" rel="nofollow"><code>label</code></a>ing your subquery <code>inner_stmt</code>. <code>label</code> is for columns or expressions, i.e. <code>SELECT ... AS ...</code>. You want <a href="http://docs.sqlalchemy.org/en/latest/core/selectable.html#sqlalchemy.sql.expression.alias" rel="nofollow"><code>alias</code></a> instead, which is for subquery expressions, i.e. <code>FROM ... AS ...</code>. You cannot access columns (<code>.c.&lt;name&gt;</code>) from the former, even in SQL, because it's a SQL expression.</p>
1
2016-09-23T18:24:11Z
[ "python", "mysql", "sqlalchemy" ]
Slicing a python dictionary to perform operations
39,647,234
<p>New 2.7 user. I have the following dictionary: </p> <pre><code> dict1 = {'A': {'val1': '5', 'val2': '1'}, 'B': {'val1': '10', 'val2': '10'}, 'C': {'val1': '15', 'val3': '100'}} </code></pre> <p>I have another dictionary </p> <pre><code> dict2 = {'val1': '10', 'val2': '16'} </code></pre> <p>I want to subtract the values from A in dict1 from dict2 to get:</p> <pre><code> dict3 = {'val1': '5', 'val2': '15'} </code></pre>
0
2016-09-22T19:18:04Z
39,647,298
<p>If I understood your problem correctly, this should work :</p> <pre><code># dict1 and dict2 have been initialized dict3 = {} for key in dict2: dict3[key] = str(int(dict2[key])-int(dict1["A"][key])) </code></pre>
1
2016-09-22T19:22:24Z
[ "python", "dictionary" ]
Slicing a python dictionary to perform operations
39,647,234
<p>New 2.7 user. I have the following dictionary: </p> <pre><code> dict1 = {'A': {'val1': '5', 'val2': '1'}, 'B': {'val1': '10', 'val2': '10'}, 'C': {'val1': '15', 'val3': '100'}} </code></pre> <p>I have another dictionary </p> <pre><code> dict2 = {'val1': '10', 'val2': '16'} </code></pre> <p>I want to subtract the values from A in dict1 from dict2 to get:</p> <pre><code> dict3 = {'val1': '5', 'val2': '15'} </code></pre>
0
2016-09-22T19:18:04Z
39,647,320
<p>Just create your dict using a dict comprehension:</p> <pre><code>d3 = {k: str(int(v) - int(dict1["A"][k])) for k, v in dict2.items()} print(d3) </code></pre> <p>Which would give you:</p> <pre><code> {'val2': '15', 'val1': '5'} </code></pre> <p><code>for k, v in dict2.items()</code> iterates over the key/value pairs from <em>dict2</em> then we access the corresponding value from <em>dict1's "A"</em> dict with <code>dict1["A"][k])</code> and subtract.</p> <p>If you plan on doing calculations like that you may be as well to store the values as actual ints, not strings.</p>
6
2016-09-22T19:23:34Z
[ "python", "dictionary" ]
Pandas: Compare a column to all other columns of a dataframe
39,647,269
<p>I have a scenario where I have new subjects being tested for a series of characteristics where the results are all string categorical values. Once the testing is done I needs to compare the new dataset to a master dataset of all subjects and look for similarities (matches) of a given thresh hold (say 90%). </p> <p>Therefore, I need to be able to do a columnar (subject-wise) comparison of each one of the new subjects in the new data set to each column in the master data set plus the others in the new data set in the best performance possible because production data set has about half million columns (and growing) and 10,000 rows.</p> <p>Here is some example code:</p> <pre><code>master = pd.DataFrame({'Characteristic':['C1', 'C2', 'C3'], 'S1':['AA','BB','AB'], 'S2':['AB','-','BB'], 'S3':['AA','AB','--']}) new = pd.DataFrame({'Characteristic':['C1', 'C2', 'C3'], 'S4':['AA','BB','AA'], 'S5':['AB','-','BB']}) new_master = pd.merge(master, new, on='Characteristic', how='inner') def doComparison(comparison_df, new_columns, master_columns): summary_dict = {} row_cnt = comparison_df.shape[0] for new_col_idx, new_col in enumerate(new_columns): # don't compare the Characteristic column if new_col != 'Characteristic': print 'Evalating subject ' + new_col + ' for matches' summary_dict[new_col] = [] new_data = comparison_df.ix[:, new_col] for master_col_idx, master_col in enumerate(master_columns): # don't compare same subject or Characteristic column if new_col != master_col and master_col != 'Characteristic': master_data = comparison_df.ix[:, master_col] is_same = (new_data == master_data) &amp; (new_data != '--') &amp; (master_data != '--') pct_same = sum(is_same) * 100 / row_cnt if pct_same &gt; 90: print ' Found potential match ' + master_col + ' ' + str(pct_same) + ' pct' summary_dict[new_col].append({'match' : master_col, 'pct' : pct_same}) return summary_dict result = doComparison(new_master, new.columns, master.columns) </code></pre> <p>This way works but I would like to increase the efficiency and performance and don't exactly know how.</p>
3
2016-09-22T19:20:46Z
39,651,658
<p>Consider the following adjustment that runs a list comprehension to build all combinations of both dataframe column names that is then iterated on to <code>&gt; 90%</code> threshold matches.</p> <pre><code># LIST COMPREHENSION (TUPLE PAIRS) LEAVES OUT CHARACTERISTIC (FIRST COL) AND SAME NAMED COLS columnpairs = [(i,j) for i in new.columns[1:] for j in master.columns[1:] if i != j] # DICTIONARY COMPREHENSION TO INITIALIZE DICT OBJ summary_dict = {col:[] for col in new.columns[1:]} for p in columnpairs: i, j = p is_same = (new['Characteristic'] == master['Characteristic']) &amp; \ (new[i] == master[j]) &amp; (new[i] != '--') &amp; (master[j] != '--') pct_same = sum(is_same) * 100 / len(master) if pct_same &gt; 90: summary_dict[i].append({'match' : j, 'pct': pct_same}) print(summary_dict) # {'S4': [], 'S5': [{'match': 'S2', 'pct': 100.0}]} </code></pre>
0
2016-09-23T02:29:51Z
[ "python", "pandas", "dataframe", "analytics", "data-science" ]
Pandas: Compare a column to all other columns of a dataframe
39,647,269
<p>I have a scenario where I have new subjects being tested for a series of characteristics where the results are all string categorical values. Once the testing is done I needs to compare the new dataset to a master dataset of all subjects and look for similarities (matches) of a given thresh hold (say 90%). </p> <p>Therefore, I need to be able to do a columnar (subject-wise) comparison of each one of the new subjects in the new data set to each column in the master data set plus the others in the new data set in the best performance possible because production data set has about half million columns (and growing) and 10,000 rows.</p> <p>Here is some example code:</p> <pre><code>master = pd.DataFrame({'Characteristic':['C1', 'C2', 'C3'], 'S1':['AA','BB','AB'], 'S2':['AB','-','BB'], 'S3':['AA','AB','--']}) new = pd.DataFrame({'Characteristic':['C1', 'C2', 'C3'], 'S4':['AA','BB','AA'], 'S5':['AB','-','BB']}) new_master = pd.merge(master, new, on='Characteristic', how='inner') def doComparison(comparison_df, new_columns, master_columns): summary_dict = {} row_cnt = comparison_df.shape[0] for new_col_idx, new_col in enumerate(new_columns): # don't compare the Characteristic column if new_col != 'Characteristic': print 'Evalating subject ' + new_col + ' for matches' summary_dict[new_col] = [] new_data = comparison_df.ix[:, new_col] for master_col_idx, master_col in enumerate(master_columns): # don't compare same subject or Characteristic column if new_col != master_col and master_col != 'Characteristic': master_data = comparison_df.ix[:, master_col] is_same = (new_data == master_data) &amp; (new_data != '--') &amp; (master_data != '--') pct_same = sum(is_same) * 100 / row_cnt if pct_same &gt; 90: print ' Found potential match ' + master_col + ' ' + str(pct_same) + ' pct' summary_dict[new_col].append({'match' : master_col, 'pct' : pct_same}) return summary_dict result = doComparison(new_master, new.columns, master.columns) </code></pre> <p>This way works but I would like to increase the efficiency and performance and don't exactly know how.</p>
3
2016-09-22T19:20:46Z
39,652,228
<p>Another option</p> <pre><code>import numpy as np import pandas as pd from sklearn.utils.extmath import cartesian </code></pre> <p>leveraging sklearn's cartesian function</p> <pre><code>col_combos = cartesian([ new.columns[1:], master.columns[1:]]) print (col_combos) [['S4' 'S1'] ['S4' 'S2'] ['S4' 'S3'] ['S5' 'S1'] ['S5' 'S2'] ['S5' 'S3']] </code></pre> <p>Creating a dict with a key for every column in new except Characteristic. Note, this seems like a waste of space. Maybe just save the ones with matches?</p> <pre><code>summary_dict = {c:[] for c in new.columns[1:]} #copied from @Parfait's answer </code></pre> <p>Pandas/Numpy makes it easy to compare two Series.<br> Example;</p> <pre><code>print (new_master['S4'] == new_master['S1']) 0 True 1 True 2 False dtype: bool </code></pre> <p>And now we iterate thru the Series combos and count the Trues with the help of numpy's count_nonzero(). The rest is similar to what you have</p> <pre><code>for combo in col_combos: match_count = np.count_nonzero(new_master[combo[0]] == new_master[combo[1]]) pct_same = match_count * 100 / len(new_master) if pct_same &gt; 90: summary_dict[combo[0]].append({'match' : combo[1], 'pct': match_count / len(new_master)}) print (summary_dict) {'S4': [], 'S5': [{'pct': 1.0, 'match': 'S2'}]} </code></pre> <p>I'd be interested to know how it performs. Good luck!</p>
1
2016-09-23T03:43:03Z
[ "python", "pandas", "dataframe", "analytics", "data-science" ]
How to access the current response's status_code in Flask's teardown_request?
39,647,430
<p>I'm interfacing with an internal logging system and I'd like to obtain the current response's <code>status_code</code> from within Flask's <code>teardown_request</code> callback: <a href="http://flask.pocoo.org/docs/0.11/api/#flask.Flask.teardown_request" rel="nofollow">http://flask.pocoo.org/docs/0.11/api/#flask.Flask.teardown_request</a>. I like that it is guaranteed to be called and I can get all the other information needed for my purposes.</p> <p>I can access the current response and it's <code>status_code</code> if I connect to the <code>request_finished</code> signal:</p> <pre><code>def request_finished_listener(sender, response): print(response.status_code) request_finished.connect(request_finished_listener) </code></pre> <p>But I'd like to do all my data collection within the <code>teardown_request</code> if possible.</p>
0
2016-09-22T19:29:48Z
39,648,172
<p>You can't. <code>teardown_request</code> is called as cleanup after the response is generated, it does not have access to the response. You should use the <code>request_finished</code> signal or <code>after_request</code> decorator if you need access to the response from within Flask. <code>teardown_request</code> is only intended for cleaning up resources.</p> <p>If you need to log something about the response and absolutely don't want to use <code>request_finished</code> or <code>after_request</code>, you'll have to wrap the Flask app in WSGI middleware.</p>
1
2016-09-22T20:18:36Z
[ "python", "flask" ]
How can I repeatedly play a sound sample, allowing the next loop to overlap the previous
39,647,440
<p>Not sure if this isn't a dupe, but the posts I found so far didn't solve my issue. </p> <hr> <p>A while ago, I wrote a (music) <a href="http://askubuntu.com/a/814889/72216">metronome for Ubuntu</a>. The metronome is written in <code>python3/Gtk</code> </p> <p>To repeatedly play the metronome- tick (a recorded sound sample), I used <code>subprocess.Popen()</code> to play the sound, using <code>ogg123</code> as a cli tool: </p> <pre><code>subprocess.Popen(["ogg123", soundfile]) </code></pre> <p>This works fine, I can easily run up to 240 beats per minute.</p> <h3>On WIndows</h3> <p>I decided to rewrite the project on Windows (<code>python3/tkinter/ttk</code>). I am having a hard time however to play the sound, repeating the beat sample in higher tempi. The next beat simply won't start while the previous one (appearantly) hasn't finished yet, playing the beat sample.</p> <p>Is there a way, in <code>python3</code> on Windows, I can start playing the next beat while the sample is still playing?</p> <p>Currently, I am using <code>winsound</code>: </p> <pre><code>winsound.Playsound() </code></pre> <p>Running this in a loop has, as mentioned issues.</p>
2
2016-09-22T19:30:32Z
39,648,261
<p>You can use <a href="https://github.com/jiaaro/pydub" rel="nofollow">pydub</a> for audio manipulation , including playing repetedly.</p> <p>Here is an example. You can develop this further using examples from <a href="http://pydub.com/" rel="nofollow">pydub site.</a></p> <pre><code>from pydub import AudioSegment from pydub.playback import play n = 2 audio = AudioSegment.from_file("sound.wav") #your audio file play(audio * n) #Play audio 2 times </code></pre> <p>Change <code>n</code> above to the number that you need.</p>
1
2016-09-22T20:24:35Z
[ "python", "windows", "python-3.x", "audio" ]
parse a section of an XML file with python
39,647,459
<p>Im new to both python and xml. Have looked at the previous posts on the topic, and I cant figure out how to do exactly what I need to. Although it seems to be simple enough in principle.</p> <pre><code>&lt;Project&gt; &lt;Items&gt; &lt;Item&gt; &lt;Code&gt;A456B&lt;/Code&gt; &lt;Database&gt; &lt;Data&gt; &lt;Id&gt;mountain&lt;/Id&gt; &lt;Value&gt;12000&lt;/Value&gt; &lt;/Data&gt; &lt;Data&gt; &lt;Id&gt;UTEM&lt;/Id&gt; &lt;Value&gt;53.2&lt;/Value&gt; &lt;/Data&gt; &lt;/Database&gt; &lt;/Item&gt; &lt;Item&gt; &lt;Code&gt;A786C&lt;/Code&gt; &lt;Database&gt; &lt;Data&gt; &lt;Id&gt;mountain&lt;/Id&gt; &lt;Value&gt;5000&lt;/Value&gt; &lt;/Data&gt; &lt;Data&gt; &lt;Id&gt;UTEM&lt;/Id&gt; &lt;Value&gt;&lt;/Value&gt; &lt;/Data&gt; &lt;/Database&gt; &lt;/Item&gt; &lt;/Items&gt; &lt;/Project&gt; </code></pre> <p>All I want to do is extract all of the Codes, Values and ID's, which is no problem.</p> <pre><code>import xml.etree.cElementTree as ET name = 'example tree.xml' tree = ET.parse(name) root = tree.getroot() codes=[] ids=[] val=[] for db in root.iter('Code'): codes.append(db.text) for ID in root.iter('Id'): ids.append(ID.text) for VALUE in root.iter('Value'): val.append(VALUE.text) print codes print ids print val ['A456B', 'A786C'] ['mountain', 'UTEM', 'mountain', 'UTEM'] ['12000', '53.2', '5000', None] </code></pre> <p>I want to know which Ids and Values go with which Code. Something like a dictionary of dictionaries maybe OR perhaps a list of DataFrames with the row index being the Id, and the column header being Code. </p> <p>for example</p> <p>A456B = {mountain:12000, UTEM:53.2}<br> A786C = {mountain:5000, UTEM: None}</p> <p>Eventually I want to use the Values to feed an equation.</p> <p>Note that the real xml file might not contain the same number of Ids and Values in each Code. Also, Id and Value might be different from one Code section to another.</p> <p>Sorry if this question is elementary, or unclear...I've only been doing python for a month :/</p>
2
2016-09-22T19:32:21Z
39,648,179
<p><a href="https://www.crummy.com/software/BeautifulSoup/" rel="nofollow">BeautifulSoup</a> is a very useful module for parsing HTML and XML. </p> <pre><code>from bs4 import BeautifulSoup import os # read the file into a BeautifulSoup object soup = BeautifulSoup(open(os.getcwd() + "\\input.txt")) results = {} # parse the data, and put it into a dict, where the values are dicts for item in soup.findAll('item'): # assemble dicts on the fly using a dict comprehension: # http://stackoverflow.com/a/14507637/4400277 results[item.code.text] = {data.id.text:data.value.text for data in item.findAll('data')} &gt;&gt;&gt; results {u'A786C': {u'mountain': u'5000', u'UTEM': u''}, u'A456B': {u'mountain': u'12000', u'UTEM': u'53.2'} </code></pre>
1
2016-09-22T20:19:21Z
[ "python", "xml" ]
parse a section of an XML file with python
39,647,459
<p>Im new to both python and xml. Have looked at the previous posts on the topic, and I cant figure out how to do exactly what I need to. Although it seems to be simple enough in principle.</p> <pre><code>&lt;Project&gt; &lt;Items&gt; &lt;Item&gt; &lt;Code&gt;A456B&lt;/Code&gt; &lt;Database&gt; &lt;Data&gt; &lt;Id&gt;mountain&lt;/Id&gt; &lt;Value&gt;12000&lt;/Value&gt; &lt;/Data&gt; &lt;Data&gt; &lt;Id&gt;UTEM&lt;/Id&gt; &lt;Value&gt;53.2&lt;/Value&gt; &lt;/Data&gt; &lt;/Database&gt; &lt;/Item&gt; &lt;Item&gt; &lt;Code&gt;A786C&lt;/Code&gt; &lt;Database&gt; &lt;Data&gt; &lt;Id&gt;mountain&lt;/Id&gt; &lt;Value&gt;5000&lt;/Value&gt; &lt;/Data&gt; &lt;Data&gt; &lt;Id&gt;UTEM&lt;/Id&gt; &lt;Value&gt;&lt;/Value&gt; &lt;/Data&gt; &lt;/Database&gt; &lt;/Item&gt; &lt;/Items&gt; &lt;/Project&gt; </code></pre> <p>All I want to do is extract all of the Codes, Values and ID's, which is no problem.</p> <pre><code>import xml.etree.cElementTree as ET name = 'example tree.xml' tree = ET.parse(name) root = tree.getroot() codes=[] ids=[] val=[] for db in root.iter('Code'): codes.append(db.text) for ID in root.iter('Id'): ids.append(ID.text) for VALUE in root.iter('Value'): val.append(VALUE.text) print codes print ids print val ['A456B', 'A786C'] ['mountain', 'UTEM', 'mountain', 'UTEM'] ['12000', '53.2', '5000', None] </code></pre> <p>I want to know which Ids and Values go with which Code. Something like a dictionary of dictionaries maybe OR perhaps a list of DataFrames with the row index being the Id, and the column header being Code. </p> <p>for example</p> <p>A456B = {mountain:12000, UTEM:53.2}<br> A786C = {mountain:5000, UTEM: None}</p> <p>Eventually I want to use the Values to feed an equation.</p> <p>Note that the real xml file might not contain the same number of Ids and Values in each Code. Also, Id and Value might be different from one Code section to another.</p> <p>Sorry if this question is elementary, or unclear...I've only been doing python for a month :/</p>
2
2016-09-22T19:32:21Z
39,648,264
<p>This might be what you want:</p> <pre><code>import xml.etree.cElementTree as ET name = 'test.xml' tree = ET.parse(name) root = tree.getroot() codes={} for item in root.iter('Item'): code = item.find('Code').text codes[code] = {} for datum in item.iter('Data'): if datum.find('Value') is not None: value = datum.find('Value').text else: value = None if datum.find('Id') is not None: id = datum.find('Id').text codes[code][id] = value print codes </code></pre> <p>This produces: <code>{'A456B' : {'mountain' : '12000', 'UTEM' : '53.2'}, 'A786C' : {'mountain' : '5000', 'UTEM' : None}}</code></p> <p>This iterates over all Item tags, and for each one, creates a dict key pointing to a dict of id/value pairs. An id/data pair is only created if the Id tag is not empty.</p>
0
2016-09-22T20:24:41Z
[ "python", "xml" ]
Unable to mock class methods using unitest in python
39,647,480
<p>module <code>a.ClassA</code>:</p> <pre><code>class ClassA(): def __init__(self,callingString): print callingString def functionInClassA(self,val): return val </code></pre> <p>module <code>b.ClassB</code>:</p> <pre><code>from a.ClassA import ClassA class ClassB(): def __init__(self,val): self.value=val def functionInsideClassB(self): obj=ClassA("Calling From Class B") value=obj.functionInClassA(self.value) </code></pre> <p>Python <code>unittest</code> class</p> <pre><code>import unittest from b.ClassB import ClassB from mock import patch, Mock, PropertyMock,mock class Test(unittest.TestCase): @patch('b.ClassB.ClassA',autospec = True) def _test_sample(self,classAmock): dummyMock=Mock() dummyMock.functionInClassA.return_value="mocking functionInClassA" classAmock.return_value=dummyMock obj=ClassB("dummy_val") obj.functionInsideClassB() assert dummyMock.functionInClassA.assert_called_once_with("dummy_val") </code></pre> <p>Assertion fails. Where exactly am I going wrong? I am using python 2.7</p>
1
2016-09-22T19:33:24Z
39,647,554
<p>You assigned to <code>return_value</code> twice:</p> <pre><code>classAmock.return_value=dummyMock classAmock.return_value=Mock() </code></pre> <p>That second assignment undoes your work setting up <code>dummyMock</code> entirely; the new <code>Mock</code> instance has no <code>functionInClassA</code> attribute set up.</p> <p>You don't need to create new mock objects; just use the default <code>return_value</code> attribute value:</p> <pre><code>class Test(unittest.TestCase): @patch('b.ClassB.ClassA', autospec=True) def test_sample(self, classAmock): instance = classAmock.return_value instance.functionInClassA.return_value = "mocking functionInClassA" obj = ClassB("dummy_val") obj.functionInsideClassB() instance.functionInClassA.assert_called_once_with("dummy_val") </code></pre> <p>You do <strong>not</strong> need to assert the return value of <code>assert_called_once_with()</code> as that is always <code>None</code> (making your extra <code>assert</code> fail, always). Leave the assertion to the <code>assert_called_once_with()</code> method, it'll raise as needed.</p>
1
2016-09-22T19:38:45Z
[ "python", "mocking", "python-unittest" ]
Simple, random encounters in a python text-adventure.. I´m stuck
39,647,497
<p>i recently started simple coding with python 3 and i´m stuck with a simple problem:</p> <hr> <pre><code>import random def enemy_bandit01(): bandit01 = {'race': 'human', 'weapon': 'a sword'} def enemy_orc01(): orc01 = {'race': 'orc', 'weapon': 'a club'} def enemy_wolf01(): wolf01 = {'race': 'wolf', 'weapon': 'claws'} encounter_choice = [enemy_bandit01, enemy_orc01, enemy_wolf01] print('You fight against a ____. He has ____!') </code></pre> <hr> <p>I simply want python to pick a random enemy_x - function and then print out a text which includes the race/weapon etc.. without writing a new text for every enemy.</p> <p>I am aware that this is a noob question, but i was not able to figure this out by myself.</p>
0
2016-09-22T19:34:37Z
39,647,593
<p>the dicts and your functions are really pointless as they are, they need to actual return something so you can randomly pick a pair:</p> <pre><code>from random import choice # use to pick a random element from encounter_choice def enemy_bandit01(): return 'human', 'a sword' # just return a tuple def enemy_orc01(): return 'orc', 'a club' def enemy_wolf01(): return 'wolf', 'claws' encounter_choice = [enemy_bandit01, enemy_orc01, enemy_wolf01] # use str.format and unpack the tuple of race, weapon print('You fight against a {}. He has {}!'.format(*choice(encounter_choice)())) </code></pre> <p>which may as well just become picking a random tuple from a list:</p> <pre><code>from random import choice encounter_choice = [('human', 'a sword'), ( 'orc', 'a club'), ('wolf', 'claws') ] print('You fight against a {}. He has {}!'.format(*choice(encounter_choice))) </code></pre> <p><code>*choice(encounter_choice)</code> is equivalent to doing:</p> <pre><code>race, weapon = choice(encounter_choice) print('You fight against a {}. He has {}!'.format(race, weapon)) </code></pre>
1
2016-09-22T19:41:30Z
[ "python", "python-3.x", "random" ]
How to stop Python 3 printing none
39,647,520
<p>how do I stop this from printing none at the end. Or is it inevitable? </p> <pre><code>x = int(input("Please enter a number to print up to.")) def print_upto(x): for y in range(1,x+1): print(y) print(print_upto(x)) </code></pre> <p>Many thanks.</p>
0
2016-09-22T19:35:58Z
39,647,536
<p>instead of </p> <pre><code>print(print_upto(x)) </code></pre> <p>on the last line, just do, </p> <pre><code>print_upto(x)` </code></pre> <p>thats it, and it will work fine.</p>
1
2016-09-22T19:37:22Z
[ "python" ]
How to stop Python 3 printing none
39,647,520
<p>how do I stop this from printing none at the end. Or is it inevitable? </p> <pre><code>x = int(input("Please enter a number to print up to.")) def print_upto(x): for y in range(1,x+1): print(y) print(print_upto(x)) </code></pre> <p>Many thanks.</p>
0
2016-09-22T19:35:58Z
39,647,565
<p>Your function does not return any value, it just <code>print</code> it. So return value is <code>None</code>. And when you <code>print(print_upto(x))</code> it's equal to <code>print(None)</code></p> <p>And if you want to see printed values you just need to call <code>print_upto(x)</code> without any <code>print()</code></p>
0
2016-09-22T19:39:28Z
[ "python" ]
Pandas groupby datetime, getting the count and price
39,647,538
<p>I'm trying to use pandas to group subscribers by subscription type for a given day and get the average price of a subscription type on that day. The data I have resembles:</p> <pre><code>Sub_Date Sub_Type Price 2011-03-31 00:00:00 12 Month 331.00 2012-04-16 00:00:00 12 Month 334.70 2013-08-06 00:00:00 12 Month 344.34 2014-08-21 00:00:00 12 Month 362.53 2015-08-31 00:00:00 6 Month 289.47 2016-09-03 00:00:00 6 Month 245.57 2013-04-10 00:00:00 4 Month 148.79 2014-03-13 00:00:00 12 Month 348.46 2015-03-15 00:00:00 12 Month 316.86 2011-02-09 00:00:00 12 Month 333.25 2012-03-09 00:00:00 12 Month 333.88 ... 2013-04-03 00:00:00 12 Month 318.34 2014-04-15 00:00:00 12 Month 350.73 2015-04-19 00:00:00 6 Month 291.63 2016-04-19 00:00:00 6 Month 247.35 2011-02-14 00:00:00 12 Month 333.25 2012-05-23 00:00:00 12 Month 317.77 2013-05-28 00:00:00 12 Month 328.16 2014-05-31 00:00:00 12 Month 360.02 2011-07-11 00:00:00 12 Month 335.00 ... </code></pre> <p>I'm looking to get something that resembles:</p> <pre><code>Sub_Date Sub_type Quantity Price 2011-03-31 00:00:00 3 Month 2 125.00 4 Month 0 0.00 # Promo not available this month 6 Month 1 250.78 12 Month 2 334.70 2011-04-01 00:00:00 3 Month 2 125.00 4 Month 2 145.00 6 Month 0 250.78 12 Month 0 334.70 2013-04-02 00:00:00 3 Month 1 125.00 4 Month 3 145.00 6 Month 0 250.78 12 Month 1 334.70 ... 2015-06-23 00:00:00 3 Month 4 135.12 4 Month 0 0.00 # Promo not available this month 6 Month 0 272.71 12 Month 3 354.12 ... </code></pre> <p>I'm only able to get the total number of <code>Sub_Type</code>s for a given date. </p> <pre><code>df.Sub_Date.groupby([df.Sub_Date.values.astype('datetime64[D]')]).size() </code></pre> <p>This is somewhat of a good start, but not exactly what is needed. I've had a look at the <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html" rel="nofollow">groupby</a> documentation on the pandas site but I can't get the output I desire.</p>
2
2016-09-22T19:37:33Z
39,647,665
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.aggregate.html" rel="nofollow"><code>aggregate</code></a> by <code>mean</code> and <code>size</code> and then add missing values by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.unstack.html" rel="nofollow"><code>unstack</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.html" rel="nofollow"><code>stack</code></a>.</p> <p>Also if need change order of level <code>Sub_Type</code>, use <a href="http://pandas.pydata.org/pandas-docs/stable/categorical.html#sorting-and-order" rel="nofollow">ordered categorical</a>.</p> <pre><code>#generating all months ('1 Month','2 Month'...'12 Month') cat = [str(x) + ' Month' for x in range(1,13)] df.Sub_Type = df.Sub_Type.astype('category', categories=cat, ordered=True) df1 = df.Price.groupby([df.Sub_Date.values.astype('datetime64[D]'), df.Sub_Type]) .agg(['mean', 'size']) .rename(columns={'size':'Quantity','mean':'Price'}) .unstack(fill_value=0) .stack() print (df1) Price Quantity Sub_Type 2011-02-09 4 Month 0.00 0 6 Month 0.00 0 12 Month 333.25 1 2011-02-14 4 Month 0.00 0 6 Month 0.00 0 12 Month 333.25 1 2011-03-31 4 Month 0.00 0 6 Month 0.00 0 12 Month 331.00 1 </code></pre>
1
2016-09-22T19:45:38Z
[ "python", "pandas" ]
Why does Python 3 exec() fail when specifying locals?
39,647,566
<p>The following executes without an error in Python 3:</p> <pre><code>code = """ import math def func(x): return math.sin(x) func(10) """ _globals = {} exec(code, _globals) </code></pre> <p>But if I try to capture the local variable dict as well, it fails with a <code>NameError</code>:</p> <pre><code>&gt;&gt;&gt; _globals, _locals = {}, {} &gt;&gt;&gt; exec(code, _globals, _locals) --------------------------------------------------------------------------- NameError Traceback (most recent call last) &lt;ipython-input-9-aeda81bf0af1&gt; in &lt;module&gt;() ----&gt; 1 exec(code, {}, {}) &lt;string&gt; in &lt;module&gt;() &lt;string&gt; in func(x) NameError: name 'math' is not defined </code></pre> <p>Why is this happening, and how can I execute this code while capturing both global and local variables?</p>
9
2016-09-22T19:39:34Z
39,647,647
<p>From the <a href="https://docs.python.org/3/library/functions.html#exec" rel="nofollow"><code>exec()</code> documentation</a>:</p> <blockquote> <p>Remember that at module level, globals and locals are the same dictionary. If <code>exec</code> gets two separate objects as <em>globals</em> and <em>locals</em>, the code will be executed as if it were embedded in a class definition.</p> </blockquote> <p>You passed in two separate dictionaries, but tried to execute code that requires module-scope globals to be available. <code>import math</code> in a class would produce a <em>local scope attribute</em>, and the function you create won't be able to access that as class scope names are not considered for function closures.</p> <p>See <a href="https://docs.python.org/3/reference/executionmodel.html#naming-and-binding" rel="nofollow"><em>Naming and binding</em></a> in the Python execution model reference:</p> <blockquote> <p>Class definition blocks and arguments to <code>exec()</code> and <code>eval()</code> are special in the context of name resolution. A class definition is an executable statement that may use and define names. These references follow the normal rules for name resolution with an exception that unbound local variables are looked up in the global namespace. The namespace of the class definition becomes the attribute dictionary of the class. The scope of names defined in a class block is limited to the class block; it does not extend to the code blocks of methods[.]</p> </blockquote> <p>You can reproduce the error by trying to execute the code in a class definition:</p> <pre><code>&gt;&gt;&gt; class Demo: ... import math ... def func(x): ... return math.sin(x) ... func(10) ... Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "&lt;stdin&gt;", line 5, in Demo File "&lt;stdin&gt;", line 4, in func NameError: name 'math' is not defined </code></pre> <p>Just pass in <em>one</em> dictionary.</p>
10
2016-09-22T19:44:01Z
[ "python", "python-3.x", "exec", "python-exec" ]
Tips for wrapping files faster
39,647,583
<p>In a piece of code, where I go through files that are formatted differently than what I want, I experience a huge slowdown.</p> <p>The slowdown is in the order of 2 hours for processing 500 files that have approximately 1000 lines each. I need to do that many more times so any input on why it is so slow and how to make it faster is welcome. Here's my code:</p> <p>f is an array I have with info about locating the files.</p> <pre><code>def athwrap(athfpath, savefpath, fdirection): ath = [] with open(athfpath, 'r') as file: for j, line in enumerate(file): if j == 6: npts = int(line[5:12]) dt = float(line[17:25]) ath = np.array((fdirection, npts, dt)) elif j &gt; 6: uys = [float(n) for n in line.split()] ath = np.hstack((ath, uys)) if not os.path.isdir(savefpath): os.makedirs(savefpath, exist_ok=True) np.savetxt(savefpath + f[i, 15] + '.txt', ath, fmt='%s') file.close() # Search and Wrap Files k = 1 for i in range(0, len(f)): athpath = path + f[i, 16] + '/' + f[i, 15] + '.ATH' savepath = savpath + f[i, 16] + '/' if os.path.isfile(athpath): if k % 3 == 0: direction = "Y" athwrap(athpath, savepath, direction) elif k % 2 == 0: direction = "X" athwrap(athpath, savepath, direction) else: direction = "Z" athwrap(athpath, savepath, direction) else: print("Could find file " + loc + '/' + site + '/' + f[i, 16] + '/' + f[i, 15]) k += 1 </code></pre>
1
2016-09-22T19:40:42Z
39,647,979
<p>Don't constantly check what line you are on. Build that into the structure of your code.</p> <pre><code>def athwrap(athfpath, savefpath, fdirection): ath = [] with open(athfpath, 'r') as file: # Ignore the first 6 lines, and keep the 7th for __ in range(7): line = next(file) nets = int(line[5:12]) dt = float(line[17:25]) ath = np.array((fdirection, npts, dt)) # For the rest of the lines for line in file: uys = [float(n) for n in line.split()] ath = np.hstack((ath, uys)) if not os.path.isdir(savefpath): os.makedirs(savefpath, exist_ok=True) np.savetxt(savefpath + f[i, 15] + '.txt', ath, fmt='%s') </code></pre> <p>Also, unless you are expecting someone external to remove <code>savefpath</code>, there is no need to repeatedly check for its existence. If someone <em>does</em> remove it, then they are just as likely to do so after you create it but before you try to write to it. There is a race condition here that is beyond the scope of this question to fix. Just check for it once at the top of the function and create it there if necessary.</p>
2
2016-09-22T20:04:30Z
[ "python", "wrap", "enumerate" ]
Tips for wrapping files faster
39,647,583
<p>In a piece of code, where I go through files that are formatted differently than what I want, I experience a huge slowdown.</p> <p>The slowdown is in the order of 2 hours for processing 500 files that have approximately 1000 lines each. I need to do that many more times so any input on why it is so slow and how to make it faster is welcome. Here's my code:</p> <p>f is an array I have with info about locating the files.</p> <pre><code>def athwrap(athfpath, savefpath, fdirection): ath = [] with open(athfpath, 'r') as file: for j, line in enumerate(file): if j == 6: npts = int(line[5:12]) dt = float(line[17:25]) ath = np.array((fdirection, npts, dt)) elif j &gt; 6: uys = [float(n) for n in line.split()] ath = np.hstack((ath, uys)) if not os.path.isdir(savefpath): os.makedirs(savefpath, exist_ok=True) np.savetxt(savefpath + f[i, 15] + '.txt', ath, fmt='%s') file.close() # Search and Wrap Files k = 1 for i in range(0, len(f)): athpath = path + f[i, 16] + '/' + f[i, 15] + '.ATH' savepath = savpath + f[i, 16] + '/' if os.path.isfile(athpath): if k % 3 == 0: direction = "Y" athwrap(athpath, savepath, direction) elif k % 2 == 0: direction = "X" athwrap(athpath, savepath, direction) else: direction = "Z" athwrap(athpath, savepath, direction) else: print("Could find file " + loc + '/' + site + '/' + f[i, 16] + '/' + f[i, 15]) k += 1 </code></pre>
1
2016-09-22T19:40:42Z
39,648,209
<p>Indentation was a life saver!</p> <pre><code>def athwrap(athfpath, savefpath, fdirection): ath = [] with open(athfpath, 'r') as file: for j, line in enumerate(file): if j == 6: npts = int(line[5:12]) dt = float(line[17:25]) ath = np.array((fdirection, npts, dt)) elif j &gt; 6: uys = [float(n) for n in line.split()] ath = np.hstack((ath, uys)) if not os.path.isdir(savefpath): os.makedirs(savefpath, exist_ok=True) np.savetxt(savefpath + f[i, 15] + '.txt', ath, fmt='%s') </code></pre>
0
2016-09-22T20:21:03Z
[ "python", "wrap", "enumerate" ]
Django select_related query
39,647,699
<p>I have the following two models:</p> <pre><code>class StraightredFixture(models.Model): fixtureid = models.IntegerField(primary_key=True) home_team = models.ForeignKey('straightred.StraightredTeam', db_column='hometeamid', related_name='home_fixtures') away_team = models.ForeignKey('straightred.StraightredTeam', db_column='awayteamid', related_name='away_fixtures') fixturedate = models.DateTimeField(null=True) fixturematchday = models.ForeignKey('straightred.StraightredFixtureMatchday', db_column='fixturematchday') hometeamscore = models.IntegerField(null=True) awayteamscore = models.IntegerField(null=True) soccerseason = models.ForeignKey('straightred.StraightredSeason', db_column='soccerseasonid', related_name='fixture_season') def __unicode__(self): return self.fixtureid class Meta: managed = True db_table = 'straightred_fixture' class UserSelection(models.Model): userselectionid = models.AutoField(primary_key=True) campaignno = models.CharField(max_length=36,unique=False) user = models.ForeignKey(User, related_name='selectionUser') teamselection1or2 = models.PositiveSmallIntegerField() teamselectionid = models.ForeignKey('straightred.StraightredTeam', db_column='teamselectionid', related_name='teamID') fixtureid = models.ForeignKey('straightred.StraightredFixture', db_column='fixtureid') class Meta: managed = True db_table = 'straightred_userselection' </code></pre> <p>I am using the following query:</p> <pre><code> prevWeekTeams = UserSelection.objects.select_related().filter(soccerseason=1025,fixturematchday=5,user=currentUserID).order_by('teamselection1or2') </code></pre> <p>When it is run I get the following error:</p> <pre><code>Cannot resolve keyword 'soccerseason' into field. Choices are: campaignno, fixtureid, fixtureid_id, teamselection1or2, teamselectionid, teamselectionid_id, user, user_id, userselectionid </code></pre> <p>I knew it would not work but I can't quite understand how to refer to the soccerseason within the fixture table. Any help would be appreciated. Many thanks, Alan.</p> <p>PS</p> <p>If you require the other two models that are linked to just let me know.</p>
1
2016-09-22T19:47:14Z
39,647,749
<p>You just need to filter on field of foreign model with that format </p> <p><code>field-that-reference-to-foreign-model__foreign-model-field</code> in your case <code>fixtureid__soccerseason</code>. <a href="https://docs.djangoproject.com/en/1.10/topics/db/queries/#lookups-that-span-relationships" rel="nofollow">The docs</a> where it describes at best.</p> <p>What you should do is</p> <pre><code>prevWeekTeams = UserSelection.objects.filter(fixtureid__soccerseason=1025,fixtureid__fixturematchday=5,user=currentUserID).order_by('teamselection1or2') </code></pre>
1
2016-09-22T19:50:40Z
[ "python", "mysql", "django" ]
Calculation of spherical coordinates
39,647,735
<p>I have to say that I'm terrified and surprised how little I know about basic math. Essentially what I have is an origin point (0,0,0), I know the radius of the circle (10), and I know both angles (theta and phi). Given this assumptions I want to calculate the projected point on the sphere. I've came up with the bottom code through reading the answers of <a href="http://stackoverflow.com/a/969880/1230358">http://stackoverflow.com/a/969880/1230358</a>, <a href="http://stackoverflow.com/a/36369852/1230358">http://stackoverflow.com/a/36369852/1230358</a>, <a href="http://tutorial.math.lamar.edu/Classes/CalcII/SphericalCoords.aspx" rel="nofollow">http://tutorial.math.lamar.edu/Classes/CalcII/SphericalCoords.aspx</a> and <a href="https://en.wikipedia.org/wiki/Spherical_coordinate_system" rel="nofollow">https://en.wikipedia.org/wiki/Spherical_coordinate_system</a>. </p> <p>My current code:</p> <pre><code>#!/usr/bin/env python3 import math PI = math.pi PI_2 = PI / 2 def calc_sphere_coordinates(radius, phi, theta): # see: http://stackoverflow.com/a/969880/1230358 # see: http://stackoverflow.com/q/19673067/1230358 # see: http://mathinsight.org/spherical_coordinates # see: https://en.wikipedia.org/wiki/Spherical_coordinate_system # see: http://tutorial.math.lamar.edu/Classes/CalcII/SphericalCoords.aspx # φ phi is the polar angle, rotated down from the positive z-axis (slope) # θ theta is azimuthal angle, the angle of the rotation around the z-axis (aspect) # z # | x # | / # |/ # +-------- y # both angles need to be in radians, not degrees! theta = theta * PI / 180 phi = phi * PI / 180 x = radius * math.sin(phi) * math.cos(theta) y = radius * math.sin(phi) * math.sin(theta) z = radius * math.cos(phi) return (x, y, z) if __name__ == "__main__": # calculate point position in hemisphere by rotating down from positive z-axis for i in (10, 20, 30, 40, 50, 60, 70 , 80, 90): print(calc_sphere_coordinates(10, i, 0)) print("-"*10) # calculate point position in hemisphere by rotating around the z axis for i in (10, 20, 30, 40, 50, 60, 70 , 80, 90): print(calc_sphere_coordinates(10, 0, i)) print("-"*10) # calculate point position by rotating in both directions for i in (10, 20, 30, 40, 50, 60, 70 , 80, 90): print(calc_sphere_coordinates(10, i, 90-i)) </code></pre> <p>The output of the code is as follows:</p> <pre><code>(1.7364817766693033, 0.0, 9.84807753012208) (3.420201433256687, 0.0, 9.396926207859085) (4.999999999999999, 0.0, 8.660254037844387) (6.4278760968653925, 0.0, 7.660444431189781) (7.66044443118978, 0.0, 6.427876096865393) (8.660254037844386, 0.0, 5.000000000000001) (9.396926207859083, 0.0, 3.4202014332566884) (9.84807753012208, 0.0, 1.7364817766693041) (10.0, 0.0, 6.123233995736766e-16) ---------- (0.0, 0.0, 10.0) (0.0, 0.0, 10.0) (0.0, 0.0, 10.0) (0.0, 0.0, 10.0) (0.0, 0.0, 10.0) (0.0, 0.0, 10.0) (0.0, 0.0, 10.0) (0.0, 0.0, 10.0) (0.0, 0.0, 10.0) ---------- (0.30153689607045814, 1.7101007166283433, 9.84807753012208) (1.16977778440511, 3.2139380484326963, 9.396926207859085) (2.5, 4.330127018922192, 8.660254037844387) (4.131759111665348, 4.92403876506104, 7.660444431189781) (5.868240888334652, 4.92403876506104, 6.427876096865393) (7.5, 4.330127018922192, 5.000000000000001) (8.83022221559489, 3.2139380484326963, 3.4202014332566884) (9.69846310392954, 1.7101007166283433, 1.7364817766693041) (10.0, 0.0, 6.123233995736766e-16) </code></pre> <p><a href="http://i.stack.imgur.com/YJbZB.png" rel="nofollow"><img src="http://i.stack.imgur.com/YJbZB.png" alt="enter image description here"></a></p> <p>Shouldn't the line with <code>(10.0, 0.0, 6.123233995736766e-16)</code> have a z-coordinate of <code>0</code> and not <code>6.123233995736766e-16</code>? Also rotating around the z-axis gives always the same result, no matter what angle is used <code>(0.0, 0.0, 10.0)</code>. </p>
1
2016-09-22T19:49:58Z
39,650,001
<p>As far as I can see, your code is working just fine. Being honest, one has to admit that 6.123233995736766e-16 is pretty much 0 for all real applications, right?</p> <p>Your question boils down to </p> <p>why <code>math.cos(math.pi / 2.0)</code> does not equal zero</p> <p>The reason is found in how floating point numbers are generated and stored in a computer. Try calculating <code>0.1+0.2</code> in python. Supprised?! In case you want to know more, just google <em>floating point error</em> or anything related.</p>
0
2016-09-22T22:46:50Z
[ "python", "math", "3d", "trigonometry" ]
Python Tkinter - Run window before loop
39,647,764
<p><strong><em>Background Information</em></strong></p> <p>The below is the code I'm currently working on to create a program that essentially prints a word, and asks you to correctly spell the word. A word can only be printed once, as once used it is put into the usedWords dictionary so that it is not reused. When all the words have been used up, the while loop ends. This all works perfectly, however now I'm trying to integrate this with a GUI.</p> <p><strong><em>What specifically my problem is</em></strong></p> <p>The issue is that I would like to have the Tkinter window have a label, and have the label update every time a new word is printed out. However, I am currently getting an error <strong>AttributeError: 'NoneType' object has no attribute '_root'</strong> I believe this is happening because I have tried to add a Label before defining the main window is defined- but I have unable to do this any other way, if the window is defined before the loop the window does not open before the loop is finished, which is obviously counter-intuitive to what I want to actually do.</p> <p><strong><em>With all that said- my question</em></strong></p> <p>It's as simple as this- how do I make this worK? I want to create the window before the loop, and have the Label within the window update every time a new word is selected from the list</p> <pre><code>import random import time from tkinter import * from tkinter.messagebox import * words = ['reflection', 'attitude', 'replicate', 'accomodate', 'terrain', 'arguemental', 'stipulate', 'stimulation', 'latitude', 'marginal', 'thedubester', 'security', 'documentation', 'ukulele', 'terminal', 'exaggeration', 'declaration', 'apptitude', 'absence', 'aggressive', 'acceptable', ' allegiance', 'embarass', 'hierarchy', 'humorous', 'existence'] usedWords = [] while len(usedWords) &lt; len(words): chooseWord = words[random.randrange(len(words))] var = StringVar() display = Label(textvariable = var) display.place(x=1,y=1) if chooseWord not in usedWords: var.set(chooseWord) userSpelt = input("Spelling: ") usedWords.append(chooseWord) if userSpelt in words: print("Correctly spelt!") else: print("Incorrectly spelt!") master = Tk() master.geometry("500x600") master.title("Minesweeper V 1.0") master.configure(background="#2c3e50") </code></pre>
1
2016-09-22T19:51:32Z
39,648,957
<p>I think that one of the issues that you're running into is trying to create a dialog box from console input. I'm sure there's a way to do it, but at the moment I can't think of a good way.</p> <p>Another issue, you're not actually creating the window (master, in your script) until after you've been through the number of words that are in your word list.</p> <p>Tkinter is a bit different than console scripting. It's event based, so if you write a while loop within the application, tkinter will "pause" until that while loop has completed.</p> <p>Instead, you may want to let the looping be done by tkinter and code around that. Here's a simple implementation that I came up with. It still needs work but it gets the job done (I'm assuming that you're using python 3 because you're using "tkinter" in all lowercase):</p> <pre><code>import random from tkinter import * from tkinter.messagebox import * words = ['reflection', 'attitude', 'replicate', 'accomodate', 'terrain', 'arguemental', 'stipulate', 'stimulation', 'latitude', 'marginal', 'thedubester', 'security', 'documentation', 'ukulele', 'terminal', 'exaggeration', 'declaration', 'apptitude', 'absence', 'aggressive', 'acceptable', ' allegiance', 'embarass', 'hierarchy', 'humorous', 'existence'] usedWords = [] class App(Tk): def __init__(self): super().__init__() self._frame = Frame(self) self._frame.pack() self._label = Label(self, text="") self._label.pack() self._entry_var = StringVar() self._entry = Entry(self, textvariable=self._entry_var) self._entry.pack() self._button = Button( self, text="Check", command=self.check_callback ) self._button.pack() self.get_new_word() def check_callback(self): if self._current_word == self._entry.get(): showinfo("Correct", "Correctly spelled.") usedWords.append(self._current_word) else: showwarning("Incorrect", "Incorrectly spelled.") words.append(self._current_word) self.get_new_word() def get_new_word(self): self._current_word = words.pop(random.randrange(len(words))) self._label.configure(text=self._current_word) self._entry_var.set("") self.title(self._current_word) app = App() app.mainloop() </code></pre> <p>This moves the tkinter portion into a class that inherits from the Tk class. In my opinion, it makes things easier once your program becomes more complex.</p>
2
2016-09-22T21:12:46Z
[ "python", "tkinter" ]
Python histogram is located on the right side of exact solution
39,647,774
<p>I am working on a project in thermal physics, and for that I need to compare a histogram with a smooth curve. My problem is that the histogram is placed to the right for the curve (the curve is consistent going though the upper left corner of the bars):</p> <p><img src="http://i.stack.imgur.com/4wHGV.png" alt="Figure 1"></p> <p>I want the curve to go though the middle of the top of the bars, like it should. It might looks like a trifle, but it really irritates me. I hope someone can help me! </p> <p>The program looks like this:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt #--Constants-- M = 20 # Jmax N = 1000 # Number of J values T = 50 # Actually T/theta_r J1 = np.linspace(0,M,N) J2 = np.linspace(0,M,M+1) #--Calculate z-- def z(J): return(2*J+1)*np.exp(-J*(J+1)/T) #--Plot-- width = .9 #Width of columns plt.bar(J2, z(J2), width=width) #Plotting histogram #plt.xticks(ind + width / 2, ind) #Replacing the indexes under the columns plt.plot(J1,z(J1),'-r', linewidth=2) SZ={'size':'16'} plt.title('Different terms $z(j)$ plotted as function of $j$',**SZ) plt.xlabel('$j$',**SZ) plt.ylabel('$z(j)$',**SZ) plt.show() </code></pre>
3
2016-09-22T19:52:01Z
39,648,039
<p>The first argument to <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.bar" rel="nofollow"><code>plt.bar</code></a> specifies the positions of the <em>left-hand edges</em> for each bar. To make the <em>centre</em> of each bar to align with your plot of <code>z(J2)</code> you need to offset the positions of the edges by minus half the bar width:</p> <pre><code>plt.bar(J2 - 0.5 * width, z(J2), width=width) </code></pre>
2
2016-09-22T20:09:16Z
[ "python", "matplotlib", "histogram" ]
How would I confirm that a python package is installed using ansible
39,647,824
<p>I am writing an <a href="https://www.ansible.com/" rel="nofollow">ansible</a> playbook, and I would first like to install <a href="https://github.com/berdario/pew" rel="nofollow">pew</a>, and transition into that pew environment in order to install some other python libraries.</p> <p>So, my playbook is going to look something like this...</p> <pre><code>tasks: # task 1 - name: install pew if necessary command: pip install pew # task 2 - name: create new pew environment if necessary command: pew new devpi-server # task 3 - name: transition to pew environment command: pew workon devpi-server # task 4 - name: install devpi-server command: pip install devpi-server # task 5 - name: run devpi server command: devpi-server ## various args </code></pre> <p>In the spirit of keeping my playbook idempotent, I would like to do all of these tasks only if necesary.</p> <p>So, I would only want to install pew if it isn't already installed, only want to create a new pew environment if it doesn't already exist, only workon the pew environment if we aren't already... etc etc...</p> <p>Does anyone have good advice as to how to accomplish this? I am somewhat familiar with ansible conditionals, but only when it is something like, "is a file downloaded or not"</p> <p>I haven't had to determine yet if programs are installed, virtual environments are loaded, etc..</p>
2
2016-09-22T19:55:47Z
39,648,014
<p>You can use the <a href="http://docs.ansible.com/ansible/pip_module.html" rel="nofollow">Pip module</a> in Ansible to ensure that certain packages are installed.</p> <p>For your conditionals I would refer to: <a href="http://stackoverflow.com/questions/21892603/how-to-make-ansible-execute-a-shell-script-if-a-package-is-not-installed">How to make Ansible execute a shell script if a package is not installed</a> and <a href="http://docs.ansible.com/ansible/playbooks_conditionals.html#register-variables" rel="nofollow">http://docs.ansible.com/ansible/playbooks_conditionals.html#register-variables</a> - these should get you on the right track.</p> <p>So your playbook would look a little like:</p> <pre><code>- pip: name=pew - name: Check if pew env exists command: pew command register: pew_env_check - name: Execute script if pew environment doesn't exist command: somescript when: pew_env_check.stdout.find('no packages found') != -1 </code></pre>
1
2016-09-22T20:07:32Z
[ "python", "pip", "conditional", "ansible", "virtualenv" ]
Jupyter Python Notebook: interactive scatter plot in which each data point is associated with its own graph?
39,647,935
<p>Consider a set of data points. Each data point consists of two numbers and two arrays. For example, the two numbers might be the values of two parameters and the two arrays might represent associated time course data. I want to produce an inline scatter plot in a Jupyter Python Notebook in which I correlate the two numbers against each other. Additionally, I want the scatter plot to be interactive such that, when I hover the cursor over a data point, a second graph appears in which the two arrays are plotted against each other. How should I do it? </p> <p><a href="http://nbviewer.jupyter.org/github/bokeh/bokeh-notebooks/blob/master/gallery/texas.ipynb" rel="nofollow">Here</a> is an example in Bokeh that is close to what I want but it only shows a floating text box associated with each point instead of a graph. I should say that I would actually prefer if the graph didn't float but instead was anchored adjacent to the scatter plot. </p> <p>Thanks. </p>
1
2016-09-22T20:01:43Z
39,669,124
<p>"Defining callbacks" from the <a href="http://bokeh.pydata.org/en/0.10.0/docs/user_guide/interaction.html#defining-callbacks" rel="nofollow">Bokeh documentation</a> might help. Not convenient, not perfect, but can achieve what you described.</p> <pre><code>from bokeh.models import ColumnDataSource, OpenURL, TapTool from bokeh.plotting import figure, output_file, show output_file("openurl.html") p = figure(plot_width=400, plot_height=400, tools="tap", title="Click the Dots") source = ColumnDataSource(data=dict( x=[1, 2, 3, 4, 5], y=[2, 5, 8, 2, 7], color=["navy", "orange", "olive", "firebrick", "gold"] )) p.circle('x', 'y', color='color', size=20, source=source) url = "http://www.colors.commutercreative.com/@color/" taptool = p.select(type=TapTool) taptool.callback = OpenURL(url=url) show(p) </code></pre>
0
2016-09-23T20:35:27Z
[ "python", "visualization", "jupyter", "interactive", "bokeh" ]
How to give a warning and ask for raw_input again - while inside a loop
39,647,973
<p>I have written the Python code below (actually it's my solution for an exercise from page 80 of "Teach yourself Python in 24 hours").</p> <p>The idea is: there are 4 seats around the table, the waiter knows for how much each seat ordered, enters those 4 amounts and gets a total.</p> <p>If the raw_input provided is not a number (but a string) my code kicks the person out. The goal, however, is to give an error message ("this entry is not valid") and ask for the input again - until it's numeric. However, I can't figure out how to ask the user for the raw input again - because I am already inside a loop.</p> <p>Thanks a lot for your advice!</p> <pre><code>def is_numeric(value): try: input = float(value) except ValueError: return False else: return True total = 0 for seat in range(1,5): print 'Note the amount for seat', seat, 'and' myinput = raw_input("enter it here ['q' to quit]: ") if myinput == 'q': break elif is_numeric(myinput): floatinput = float(myinput) total = total + floatinput else: print 'I\'m sorry, but {} isn\'t valid. Please try again'.format(myinput) break if myinput == 'q': print "Goodbye!" else: total = round(total, 2) print "*****\nTotal: ${}".format(total) print "Goodbye!" </code></pre>
1
2016-09-22T20:04:12Z
39,648,216
<p>Generally, when you don't know how many times you want to run your loop the solution is a <code>while</code> loop. </p> <pre><code>for seat in range(1,5): my_input = raw_input("Enter: ") while not(my_input == 'q' or isnumeric(my_input)): my_input = raw_imput("Please re-enter value") if my_input == 'q': break else: total += float(my_input) </code></pre>
2
2016-09-22T20:21:38Z
[ "python" ]
How to give a warning and ask for raw_input again - while inside a loop
39,647,973
<p>I have written the Python code below (actually it's my solution for an exercise from page 80 of "Teach yourself Python in 24 hours").</p> <p>The idea is: there are 4 seats around the table, the waiter knows for how much each seat ordered, enters those 4 amounts and gets a total.</p> <p>If the raw_input provided is not a number (but a string) my code kicks the person out. The goal, however, is to give an error message ("this entry is not valid") and ask for the input again - until it's numeric. However, I can't figure out how to ask the user for the raw input again - because I am already inside a loop.</p> <p>Thanks a lot for your advice!</p> <pre><code>def is_numeric(value): try: input = float(value) except ValueError: return False else: return True total = 0 for seat in range(1,5): print 'Note the amount for seat', seat, 'and' myinput = raw_input("enter it here ['q' to quit]: ") if myinput == 'q': break elif is_numeric(myinput): floatinput = float(myinput) total = total + floatinput else: print 'I\'m sorry, but {} isn\'t valid. Please try again'.format(myinput) break if myinput == 'q': print "Goodbye!" else: total = round(total, 2) print "*****\nTotal: ${}".format(total) print "Goodbye!" </code></pre>
1
2016-09-22T20:04:12Z
39,648,225
<pre><code>total = 0 for seat in range(1,5): incorrectInput = True while(incorrectInput): print 'Note the amount for seat', seat, 'and' myinput = raw_input("enter it here ['q' to quit]: ") if myinput == 'q': print 'Goodbye' quit() elif is_numeric(myinput): floatinput = float(myinput) total = total + floatinput incorrectInput = False else: print 'I\'m sorry, but {} isn\'t valid. Please try again'.format(myinput) total = round(total, 2) print "*****\nTotal: ${}".format(total) print "Goodbye!" </code></pre>
0
2016-09-22T20:22:11Z
[ "python" ]
How to give a warning and ask for raw_input again - while inside a loop
39,647,973
<p>I have written the Python code below (actually it's my solution for an exercise from page 80 of "Teach yourself Python in 24 hours").</p> <p>The idea is: there are 4 seats around the table, the waiter knows for how much each seat ordered, enters those 4 amounts and gets a total.</p> <p>If the raw_input provided is not a number (but a string) my code kicks the person out. The goal, however, is to give an error message ("this entry is not valid") and ask for the input again - until it's numeric. However, I can't figure out how to ask the user for the raw input again - because I am already inside a loop.</p> <p>Thanks a lot for your advice!</p> <pre><code>def is_numeric(value): try: input = float(value) except ValueError: return False else: return True total = 0 for seat in range(1,5): print 'Note the amount for seat', seat, 'and' myinput = raw_input("enter it here ['q' to quit]: ") if myinput == 'q': break elif is_numeric(myinput): floatinput = float(myinput) total = total + floatinput else: print 'I\'m sorry, but {} isn\'t valid. Please try again'.format(myinput) break if myinput == 'q': print "Goodbye!" else: total = round(total, 2) print "*****\nTotal: ${}".format(total) print "Goodbye!" </code></pre>
1
2016-09-22T20:04:12Z
39,648,412
<p>As Patrick Haugh and SilentLupin suggested, a <code>while</code> loop is probably the best way. Another way is recursion- ie, calling the same function over and over until you get a valid input: </p> <pre><code>def is_numeric(value): try: input = float(value) except ValueError: return False else: return True def is_q(value): return value == 'q' def is_valid(value, validators): return any(validator(input) for validator in validators) def get_valid_input(msg, validators): value = raw_input(msg) if not is_valid(value, validators): print 'I\'m sorry, but {} isn\'t valid. Please try again'.format(value) value = get_valid_input(msg, validators) return value total = 0 for seat in range(1,5): print 'Note the amount for seat', seat, 'and' myinput = get_valid_input("enter it here ['q' to quit]: ", [is_q, is_numeric]) if myinput == 'q': break elif is_numeric(myinput): floatinput = float(myinput) total = total + floatinput if myinput == 'q': print "Goodbye!" else: total = round(total, 2) print "*****\nTotal: ${}".format(total) print "Goodbye!" </code></pre> <p>In the above code, <code>get_valid_input</code> calls itself over and over again until one of the supplied <code>validators</code> produces something truthy. </p>
0
2016-09-22T20:35:28Z
[ "python" ]
Capturing from a html POST form a model in Django
39,647,977
<p>The truth i'm new to django and i would like to know how I can capture a value of an input type = hidden in a view of django, using request.POST [ 'address'] so that it can enter a value in my model in this case I want to fill my field direction but does not receive any data appears in the database as empty. This is the code I have so far:</p> <p><strong>views.py</strong></p> <pre><code>def formularioLleno(request): form = InformationForm() if request.method == 'POST': form = InformationForm(request.POST or None) if form.is_valid(): form.ubicacion = request.POST['direccion'] form.save() #return redirect('formas.index') return HttpResponseRedirect(reverse('index')) else: form = InformationForm() data = { 'form': form, } return render_to_response('forma_form.html', data, context_instance=RequestContext(request)) </code></pre> <p><strong>forms.py</strong></p> <pre><code>from django import forms from .models import forma class InformationForm(forms.ModelForm): class Meta: model = forma fields = ('nombre', 'telefono') </code></pre> <p><strong>models.py</strong></p> <pre><code>class forma(models.Model): nombre = models.CharField(verbose_name='nombre', max_length=50, unique=False) telefono = models.CharField(verbose_name='telefono', max_length=10, unique=False) ubicacion = models.CharField(verbose_name='ubicacion', max_length=15, unique=False) </code></pre> <p>forma_form.html</p> <pre><code>&lt;div id="formularios"&gt; {% block form_content %} &lt;form action="" method="POST"&gt; {% csrf_token %} {{ form.as_p }} &lt;div id="ubicacion"&gt;&lt;/div&gt; &lt;input type="hidden" id="direccion" name="direccion" value="hello"&gt; &lt;button type="submit" onclick="alerta()"&gt;Contactar&lt;/button&gt; &lt;/form&gt; {% endblock form_content %} </code></pre> <p></p>
2
2016-09-22T20:04:18Z
39,648,079
<p>The reason you aren't seeing the input is that the form field "direccion" is not a member of the class InformationForm. When you load data from the request with <code>form = InformationForm(request.POST or None)</code> the direccion field is not captured.</p> <p>I would recommend adding a new member to the <code>InformationForm</code> form (direccion), and set the widget to <code>HiddenInput</code> (read more about Widgets here: <a href="https://docs.djangoproject.com/en/1.10/ref/forms/widgets/" rel="nofollow">https://docs.djangoproject.com/en/1.10/ref/forms/widgets/</a>)</p> <p>This keep the input hidden on the form but will pass the information back to the View. You can then remove the hard coded hidden input HTML from your template. </p>
0
2016-09-22T20:12:23Z
[ "python", "django", "forms", "input", "hidden" ]
Get List of Unique String values per column in a dataframe using python
39,647,978
<p>here I go with another question</p> <p>I have a large dataframe about 20 columns by 400.000 rows. In this dataset I can not have string since the software that will process the data only accepts numeric and nulls.</p> <p>So they way I am thinking it might work is following. 1. go thru each column 2. Get List of unique strings 3. Replace each string with a value from 0 to X 4. repeat the process for the next column 5. Repeat for the next dataframe</p> <p>This is how the dataframe looks like</p> <pre><code>DATE TIME FNRHP306H FNRHP306HC FNRHP306_2MEC_MAX 7-Feb-15 0:00:00 NORMAL NORMAL 1050 7-Feb-15 0:01:00 NORMAL NORMAL 1050 7-Feb-15 0:02:00 NORMAL HIGH 1050 7-Feb-15 0:03:00 HIGH NORMAL 1050 7-Feb-15 0:04:00 LOW NORMAL 1050 7-Feb-15 0:05:00 NORMAL LOW 1050 </code></pre> <p>This is the result expected</p> <pre><code>DATE TIME FNRHP306H FNRHP306HC FNRHP306_2MEC_MAX 7-Feb-15 0:00:00 0 0 1050 7-Feb-15 0:01:00 0 0 1050 7-Feb-15 0:02:00 0 1 1050 7-Feb-15 0:03:00 1 0 1050 7-Feb-15 0:04:00 2 0 1050 7-Feb-15 0:05:00 0 2 1050 </code></pre> <p><a href="http://i.stack.imgur.com/PM8fl.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/PM8fl.jpg" alt="enter image description here"></a></p> <p>I am using python 3.5 and the latest version of Pandas</p> <p>Thanks in advance</p> <p>JV</p>
1
2016-09-22T20:04:27Z
39,648,632
<p><strong>Solution:</strong></p> <pre><code># try to convert all columns to numbers... df = df.apply(lambda x: pd.to_numeric(x, errors='ignore')) cols = df.filter(like='FNR').select_dtypes(include=['object']).columns st = df[cols].stack().to_frame('name') st['cat'] = pd.factorize(st.name)[0] df[cols] = st['cat'].unstack() del st </code></pre> <p><strong>Demo:</strong></p> <pre><code>In [233]: df Out[233]: DATE TIME FNRHP306H FNRHP306HC FNRHP306_2MEC_MAX 0 7-Feb-15 0:00:00 NORMAL NORMAL 1050 1 7-Feb-15 0:01:00 NORMAL NORMAL 1050 2 7-Feb-15 0:02:00 NORMAL HIGH 1050 3 7-Feb-15 0:03:00 HIGH NORMAL 1050 4 7-Feb-15 0:04:00 LOW NORMAL 1050 5 7-Feb-15 0:05:00 NORMAL LOW 1050 </code></pre> <p>first we <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.html" rel="nofollow">stack</a> all <code>object</code> (string) columns:</p> <pre><code>In [235]: cols = df.filter(like='FNR').select_dtypes(include=['object']).columns In [236]: st = df[cols].stack().to_frame('name') </code></pre> <p>now we can <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.factorize.html" rel="nofollow">factorize</a> stacked column: </p> <pre><code>In [238]: st['cat'] = pd.factorize(st.name)[0] In [239]: st Out[239]: name cat 0 FNRHP306H NORMAL 0 FNRHP306HC NORMAL 0 1 FNRHP306H NORMAL 0 FNRHP306HC NORMAL 0 2 FNRHP306H NORMAL 0 FNRHP306HC HIGH 1 3 FNRHP306H HIGH 1 FNRHP306HC NORMAL 0 4 FNRHP306H LOW 2 FNRHP306HC NORMAL 0 5 FNRHP306H NORMAL 0 FNRHP306HC LOW 2 </code></pre> <p>assign <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.unstack.html" rel="nofollow">unstacked</a> result back to original DF (to <code>object</code> columns):</p> <pre><code>In [241]: df[cols] = st['cat'].unstack() In [242]: df Out[242]: DATE TIME FNRHP306H FNRHP306HC FNRHP306_2MEC_MAX 0 7-Feb-15 0:00:00 0 0 1050 1 7-Feb-15 0:01:00 0 0 1050 2 7-Feb-15 0:02:00 0 1 1050 3 7-Feb-15 0:03:00 1 0 1050 4 7-Feb-15 0:04:00 2 0 1050 5 7-Feb-15 0:05:00 0 2 1050 </code></pre> <p><strong>Explanation:</strong></p> <pre><code>In [248]: df.filter(like='FNR') Out[248]: FNRHP306H FNRHP306HC FNRHP306_2MEC_MAX 0 NORMAL NORMAL 1050 1 NORMAL NORMAL 1050 2 NORMAL HIGH 1050 3 HIGH NORMAL 1050 4 LOW NORMAL 1050 5 NORMAL LOW 1050 In [249]: df.filter(like='FNR').select_dtypes(include=['object']) Out[249]: FNRHP306H FNRHP306HC 0 NORMAL NORMAL 1 NORMAL NORMAL 2 NORMAL HIGH 3 HIGH NORMAL 4 LOW NORMAL 5 NORMAL LOW </code></pre>
1
2016-09-22T20:49:17Z
[ "python", "pandas", "dataframe" ]
Improving frequency time normalization/hilbert transfer runtimes
39,648,038
<p>So this is a bit of a nitty gritty question...</p> <p>I have a time-series signal that has a non-uniform response spectrum that I need to whiten. I do this whitening using a frequency time normalization method, where I incrementally filter my signal between two frequency endpoints, using a constant narrow frequency band (~1/4 the lowest frequency end-member). I then find the envelope that characterizes each one of these narrow bands, and normalize that frequency component. I then rebuild my signal using these normalized signals... all done in python (sorry, has to be a python solution)...</p> <p>Here is the raw data: <a href="http://i.stack.imgur.com/MQut2.png" rel="nofollow"><img src="http://i.stack.imgur.com/MQut2.png" alt="enter image description here"></a></p> <p>and here is its spectrum: <a href="http://i.stack.imgur.com/SKvfC.png" rel="nofollow"><img src="http://i.stack.imgur.com/SKvfC.png" alt="enter image description here"></a></p> <p>and here is the spectrum of the whitened data: <a href="http://i.stack.imgur.com/hy3c9.png" rel="nofollow"><img src="http://i.stack.imgur.com/hy3c9.png" alt="enter image description here"></a></p> <p>The problem is, that I have to do this for maybe ~500,000 signals like this, and it takes a while (~a minute each)... With almost the entirety of the time being spend doing the actual (multiple) Hilbert transforms </p> <p>I have it running on a small cluster already. I don't want to parallelize the loop the Hilbert is in.</p> <p>I'm looking for alternative envelope routines/functions (non Hilbert), or alternative ways to calculate the entire narrowband response function without doing a loop.</p> <p>The other option is to make the frequency bands adaptive to the center frequency over which its filtering, so they get progressively larger as we march through the routines; which would just decrease the number of times I have to go through the loop.</p> <p>Any and all suggestions welcome!!!</p> <p>example code/dataset: <a href="https://github.com/ashtonflinders/FTN_Example" rel="nofollow">https://github.com/ashtonflinders/FTN_Example</a></p>
3
2016-09-22T20:09:04Z
39,662,343
<p>Here is a faster method to calculate the enveloop by local max:</p> <pre><code>def calc_envelope(x, ind): x_abs = np.abs(x) loc = np.where(np.diff(np.sign(np.diff(x_abs))) &lt; 0)[0] + 1 peak = x_abs[loc] envelope = np.interp(ind, loc, peak) return envelope </code></pre> <p>Here is an example output:</p> <p><a href="http://i.stack.imgur.com/tRfDN.png" rel="nofollow"><img src="http://i.stack.imgur.com/tRfDN.png" alt="enter image description here"></a></p> <p>It's about 6x faster than hilbert. To speedup even more, you can write a cython function that find next local max point and does normalization up to the local max point iteratively.</p>
1
2016-09-23T13:42:51Z
[ "python", "numpy", "math", "scipy" ]
python pandas parse date without delimiters 'time data '060116' does not match format '%dd%mm%YY' (match)'
39,648,163
<p>I am trying to parse a date column that looks like the one below,</p> <pre><code>date 061116 061216 061316 061416 </code></pre> <p>However I cannot get pandas to accept the date format as there is no delimiter (eg '/'). I have tried this below but receive the error: </p> <blockquote> <p>ValueError: time data '060116' does not match format '%dd%mm%YY' (match)</p> </blockquote> <pre><code>pd.to_datetime(df['Date'], format='%dd%mm%YY') </code></pre>
-1
2016-09-22T20:18:04Z
39,648,193
<p>Your date format is wrong. You have days and months reversed. It should be:</p> <pre><code> %m%d%Y </code></pre>
0
2016-09-22T20:20:07Z
[ "python", "date", "datetime", "pandas", "time-series" ]
python pandas parse date without delimiters 'time data '060116' does not match format '%dd%mm%YY' (match)'
39,648,163
<p>I am trying to parse a date column that looks like the one below,</p> <pre><code>date 061116 061216 061316 061416 </code></pre> <p>However I cannot get pandas to accept the date format as there is no delimiter (eg '/'). I have tried this below but receive the error: </p> <blockquote> <p>ValueError: time data '060116' does not match format '%dd%mm%YY' (match)</p> </blockquote> <pre><code>pd.to_datetime(df['Date'], format='%dd%mm%YY') </code></pre>
-1
2016-09-22T20:18:04Z
39,648,239
<p>You need add parameter <code>errors='coerce'</code> <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow"><code>to_datetime</code></a>, because <code>13</code> and <code>14</code> months does not exist, so this dates are converted to <code>NaT</code>:</p> <pre><code>print (pd.to_datetime(df['Date'], format='%d%m%y', errors='coerce')) 0 2016-11-06 1 2016-12-06 2 NaT 3 NaT Name: Date, dtype: datetime64[ns] </code></pre> <p>Or maybe you need swap months with days:</p> <pre><code>print (pd.to_datetime(df['Date'], format='%m%d%y')) 0 2016-06-11 1 2016-06-12 2 2016-06-13 3 2016-06-14 Name: Date, dtype: datetime64[ns] </code></pre> <p>EDIT:</p> <pre><code>print (df) Date 0 0611160130 1 0612160130 2 0613160130 3 0614160130 print (pd.to_datetime(df['Date'], format='%m%d%y%H%M', errors='coerce')) 0 2016-06-11 01:30:00 1 2016-06-12 01:30:00 2 2016-06-13 01:30:00 3 2016-06-14 01:30:00 Name: Date, dtype: datetime64[ns] </code></pre> <p><a href="http://strftime.org/" rel="nofollow">Python's strftime directives</a>.</p>
1
2016-09-22T20:23:15Z
[ "python", "date", "datetime", "pandas", "time-series" ]
Disable global installs using pip - allow only virtualenvs
39,648,189
<p>Sometimes by mistake I install some packages globally with plain <code>pip install package</code> and contaminate my system instead of creating a proper virtualenv and keeping things tidy.</p> <p>How can I easily disable global installs with <code>pip</code> at all? Or at least show big fat warning when using it this way to make sure that I know what am I doing?</p>
3
2016-09-22T20:19:52Z
39,648,475
<p>You could try creating adding something like this to your <code>.bashrc</code></p> <pre><code>pip() { if [ -n "$VIRTUAL_ENV" ]; then # Run pip install else echo "You're not in a virtualenv" fi } </code></pre> <p>My knowledge of bash isn't the greatest but this should put you on the right path I think.</p>
1
2016-09-22T20:38:52Z
[ "python", "pip", "virtualenv" ]
Python matrix indexing
39,648,251
<p>I have the following code</p> <pre><code>l = len(time) #time is a 300 element list ll = len(sample) #sample has 3 sublists each with 300 elements w, h = ll, l Matrix = [[0 for x in range(w)] for y in range(h)] for n in range(0,l): for m in range(0,ll): x=sample[m] Matrix[m][n]= x </code></pre> <p>When I run the code to fill the matrix I get an error message saying "list index out of range" I put in a print statement to see where the error happens and when m=0 and n=3 the matrix goes out of index.</p> <p>from what I understand on the fourth line of the code I initialize a 3X300 matrix so why does it go out of index at 0X3 ?</p>
0
2016-09-22T20:23:55Z
39,648,289
<p>You need to change <code>Matrix[m][n]= x</code> to <code>Matrix[n][m]= x</code></p>
4
2016-09-22T20:26:33Z
[ "python", "arrays", "list", "matrix", "indexing" ]
Python matrix indexing
39,648,251
<p>I have the following code</p> <pre><code>l = len(time) #time is a 300 element list ll = len(sample) #sample has 3 sublists each with 300 elements w, h = ll, l Matrix = [[0 for x in range(w)] for y in range(h)] for n in range(0,l): for m in range(0,ll): x=sample[m] Matrix[m][n]= x </code></pre> <p>When I run the code to fill the matrix I get an error message saying "list index out of range" I put in a print statement to see where the error happens and when m=0 and n=3 the matrix goes out of index.</p> <p>from what I understand on the fourth line of the code I initialize a 3X300 matrix so why does it go out of index at 0X3 ?</p>
0
2016-09-22T20:23:55Z
39,648,320
<p>The indexing of nested lists happens from the outside in. So for your code, you'll probably want:</p> <pre><code>Matrix[n][m] = x </code></pre> <p>If you prefer the other order, you can build the matrix differently (swap <code>w</code> and <code>h</code> in the list comprehensions).</p> <p>Note that if you're going to be doing mathematical operations with this matrix, you may want to be using <code>numpy</code> arrays instead of Python lists. They're almost certainly going to be much more efficient at doing math operations than anything you can write yourself in pure Python.</p>
2
2016-09-22T20:28:44Z
[ "python", "arrays", "list", "matrix", "indexing" ]
Python matrix indexing
39,648,251
<p>I have the following code</p> <pre><code>l = len(time) #time is a 300 element list ll = len(sample) #sample has 3 sublists each with 300 elements w, h = ll, l Matrix = [[0 for x in range(w)] for y in range(h)] for n in range(0,l): for m in range(0,ll): x=sample[m] Matrix[m][n]= x </code></pre> <p>When I run the code to fill the matrix I get an error message saying "list index out of range" I put in a print statement to see where the error happens and when m=0 and n=3 the matrix goes out of index.</p> <p>from what I understand on the fourth line of the code I initialize a 3X300 matrix so why does it go out of index at 0X3 ?</p>
0
2016-09-22T20:23:55Z
39,648,372
<p>Note that indexing in nested lists in Python happens from outside in, and so you'll have to change the order in which you index into your array, as follows:</p> <pre><code>Matrix[n][m] = x </code></pre> <p>For mathematical operations and matrix manipulations, using <code>numpy</code> two-dimensional arrays, is almost always a better choice. You can read more about them <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.array.html" rel="nofollow">here</a>.</p>
1
2016-09-22T20:31:57Z
[ "python", "arrays", "list", "matrix", "indexing" ]
Can't Get Browsers To Close At The End Of Automation Script
39,648,326
<p>I've been struggling with this for a while. So I'm using parametrize in pytest for cross browser testing written in Python. I was able to start up all 3 instances but at the end of the test only the Chrome instance closes but Safari and Firefox stay open. This is my script:</p> <pre><code>@pytest.mark.parametrize("browser", [ ("chrome"), ("firefox"), ("safari")] ) def test_eval(browser): print browser if browser == "chrome": driver = webdriver.Chrome() elif browser == "firefox": caps = DesiredCapabilities.FIREFOX caps["marionette"] = True caps["binary"] = "/Applications/Firefox.app/Contents/MacOS/firefox-bin" driver = webdriver.Firefox(capabilities=caps) elif browser == "safari": os.environ["SELENIUM_SERVER_JAR"] = "selenium-server-standalone-3.0.0-beta2.jar" driver = webdriver.Safari() driver.get("https://www.google.com") driver.quit() </code></pre> <p>Thanks in advance for the help!</p>
0
2016-09-22T20:28:50Z
39,649,129
<p>This may help, <a href="http://stackoverflow.com/questions/15067107/difference-between-webdriver-dispose-close-and-quit">Difference between webdriver.Dispose(), .Close() and .Quit()</a></p> <p>They suggest to use driver.close() for ones that arent chrome</p>
1
2016-09-22T21:26:19Z
[ "python", "selenium-webdriver", "py.test" ]
Unable to loop the files to perform diff in python
39,648,365
<p>I am new to python. I am writing a python script to find the diff between 2 html file1: beta.vidup.me-log-2016-09-21-17:43:28.html and file2: beta.vidup.me-log-2016-09-21-17:47:48.html.</p> <p>To give an idea about my file organization: I have 2 directories 2016-09-21 and 2016-09-22. file1: beta.vidup.me-log-2016-09-21-17:43:28.html is present in dir1 and file2: beta.vidup.me-log-2016-09-21-17:47:48.html is present in dir2. </p> <p>Below is my snippet:</p> <pre><code>dir1 = raw_input("Enter date of Archive folder to compare with in format yyyy-mm-dd----&gt;\n") dir2 = raw_input("Enter date of folder to compare in format yyyy-mm-dd-----&gt;\n") now = datetime.now() folder_output = '/home/diff_output/{}'.format(now.strftime('%Y-%m-%d')) mkdir(folder_output) fname1 = '/home/output/%s/beta.vidup.me-log-2016-09-21-17:43:28.html'%dir1 fname2 = '/home/output/%s/beta.vidup.me-log-2016-09-21-17:47:48.html'%dir2 # Open file for reading in text mode (default mode) f1 = open(fname1) f2 = open(fname2) cmd = "diff "+fname1+'\t'+fname2 curl = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE) file_data = curl.stdout.read() print file_data fname1.close() fname2.close() </code></pre> <p>I wish to perform diff using the subprocess module only.</p> <p>I want my code to take fname1 from dir1 and fname2 from dir2 and perform the diff and output it to a folder and Loop back to pick the next file in dir1 for fname1 and next file from dir2 for fname2 and perform the diff again.</p> <p>Thanks for your time and advice in advance. </p>
0
2016-09-22T20:31:29Z
39,648,399
<p>Below are the functions you need with examples. Merge them using the logic with <code>for</code> loop. </p> <p>You can use <a href="https://docs.python.org/2/library/subprocess.html#subprocess.check_output" rel="nofollow"><code>subprocess.check_output()</code></a> to get output from the command. Try:</p> <pre><code>cmd = ["diff", fname1, +fname2] output = subprocess.check_output(cmd) print output </code></pre> <p>if you want to write this to file:</p> <pre><code>with open('/paht/to/file', 'w+') as f: f.write(output) </code></pre> <p>In order to get list of files in directory, use <code>listdir()</code>, <code>isfile</code> and <code>join</code> functions of <a href="https://docs.python.org/2/library/os.html" rel="nofollow"><code>os</code></a> module. For example:</p> <pre><code>from os import listdir from os.path import isfile, join only_files = [f for f in listdir('path') if isfile(join('path', f))] # only_files will contain list of all files in 'path' path </code></pre> <hr> <p>As you mentioned, you don't have much idea on loop. To give you the basic idea on how your loop should work. Below is the example (instead of copying, try to understand each line. it'll be helpful for you in future):</p> <pre><code>for f1, f2 in zip(file_list_1, file_list_2): # takes first, second, etc files corresponding to each list output = subprocess.check_output(['diff', f1, f2]) # generate diff of both file with open('diff-{}-{}'.format(f1, f2), 'w+') as f: f.write(output) # write the diff to third file </code></pre> <p>Modify the above logic as per your requirement. </p>
0
2016-09-22T20:34:26Z
[ "python", "subprocess", "diff" ]
How can I correctly format dates using openpyxl?
39,648,413
<p>I am attempting to save dates in an existing Excel workbook using openpyxl but they are not formatted correctly in the cells when I open the workbook.</p> <p>The dates are formatted in a list as such: <code>mylist = ["09/01/2016","01/29/2016"]</code></p> <p>The cells in which dates are being saved are formatted in the workbook as Date "*m/d/yyyy". When viewing the workbook, the dates are normally displayed in this format: 9/1/2016 1/29/2016</p> <p>Using this code in Python:</p> <pre><code>SheetName.cell(row=2,column=1).value = mylist[0] </code></pre> <p>inserts the date formatted as 09/01/2016 and appears to be formatted as text (left justified).</p> <p>If you click on the cell containing the date, then click on the formula bar, then press Enter, Excel formats and displays the date as 9/1/2016 (right justified).</p> <p>I could spend time rewriting the code to strip leading zeros out of the month and day but this wouldn't address the formatting issue in Excel.</p> <p>Is there a way to control the formatting of the cell when the date is added to a cell?</p>
1
2016-09-22T20:35:40Z
39,648,982
<p>openpyxl supports <a href="https://docs.python.org/2/library/datetime.html#datetime-objects" rel="nofollow"><code>datetime</code></a> objects, which convieniently provide a way to convert from a string. </p> <pre class="lang-python prettyprint-override"><code>import datetime for i in len(mylist): dttm = datetime.datetime.strptime(mylist[i], "%m/%d/%Y") SheetName.cell(row=i,column=1).value = dttm </code></pre>
1
2016-09-22T21:14:10Z
[ "python", "openpyxl" ]
corenlp sentiment Java program via Py4j in Python, raises errors
39,648,414
<p>I made a Java sentiment analysis program to be used in Python via Py4j. I can create the Java object in Python, but try to access the method, it gives java.lang.NullPointerException. Could you help please? Thanks.</p> <p><strong>Java code</strong>: it compiles correctly, runs without errors.</p> <pre><code>import java.util.List; import java.util.Properties; import edu.stanford.nlp.ling.CoreAnnotations; import edu.stanford.nlp.neural.rnn.RNNCoreAnnotations; import edu.stanford.nlp.pipeline.Annotation; import edu.stanford.nlp.pipeline.StanfordCoreNLP; import edu.stanford.nlp.sentiment.SentimentCoreAnnotations.SentimentAnnotatedTree; import edu.stanford.nlp.trees.Tree; import edu.stanford.nlp.util.ArrayCoreMap; import edu.stanford.nlp.util.CoreMap; import py4j.GatewayServer; import org.ejml.simple.SimpleMatrix; public class CoreNLPSentiScore { static StanfordCoreNLP pipeline; public static void init() { Properties props = new Properties(); props.setProperty("annotators", "tokenize, ssplit, parse, sentiment"); pipeline = new StanfordCoreNLP(props); } public static void main(String[] args) { CoreNLPSentiScore app = new CoreNLPSentiScore(); // app is now the gateway.entry_point GatewayServer server = new GatewayServer(app); server.start(); } //public static void main(String tweet) { //public static String findSentiment(String tweet) { public String findSentiment(String tweet) { //String SentiReturn = "2"; //String[] SentiClass ={"very negative", "negative", "neutral", "positive", "very positive"}; //Sentiment is an integer, ranging from 0 to 4. //0 is very negative, 1 negative, 2 neutral, 3 positive and 4 very positive. //int sentiment = 2; SimpleMatrix senti_score = new SimpleMatrix(); if (tweet != null &amp;&amp; tweet.length() &gt; 0) { Annotation annotation = pipeline.process(tweet); List&lt;CoreMap&gt; sentences = annotation.get(CoreAnnotations.SentencesAnnotation.class); if (sentences != null &amp;&amp; sentences.size() &gt; 0) { ArrayCoreMap sentence = (ArrayCoreMap) sentences.get(0); //Tree tree = sentence.get(SentimentAnnotatedTree.class); Tree tree = sentence.get(SentimentAnnotatedTree.class); senti_score = RNNCoreAnnotations.getPredictions(tree); //SentiReturn = SentiClass[sentiment]; } } //System.out.println(senti_score); return senti_score.toString(); //System.out.println(senti_score); } } </code></pre> <p><strong>Python code</strong>:</p> <pre><code>from py4j.java_gateway import JavaGateway gateway = JavaGateway() app = gateway.entry_point test = 'i like this product' app.findSentiment(test) </code></pre> <p><strong>NullPointerException</strong></p> <pre><code>Traceback (most recent call last): File "&lt;ipython-input-1-cefdf18ada67&gt;", line 5, in &lt;module&gt; app.findSentiment(test) File "C:\Anaconda3\envs\sandbox\lib\site-packages\py4j\java_gateway.py", line 1026, in __call__ answer, self.gateway_client, self.target_id, self.name) File "C:\Anaconda3\envs\sandbox\lib\site-packages\py4j\protocol.py", line 316, in get_return_value format(target_id, ".", name), value) Py4JJavaError: An error occurred while calling t.findSentiment.: java.lang.NullPointerException at CoreNLPSentiScore.findSentiment(CoreNLPSentiScore.java:43) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:237) at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357) at py4j.Gateway.invoke(Gateway.java:280) at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132) at py4j.commands.CallCommand.execute(CallCommand.java:79) at py4j.GatewayConnection.run(GatewayConnection.java:214) at java.lang.Thread.run(Unknown Source) </code></pre>
0
2016-09-22T20:35:43Z
39,657,615
<p>I believe you forgot to call init().</p> <p>This seems to be line #43 (see your stack trace):</p> <pre><code>Annotation annotation = pipeline.process(tweet); </code></pre> <p>pipeline is likely to be null because it is instantiated in init() and init() is not called in the main() method or from Python.</p>
1
2016-09-23T09:42:58Z
[ "java", "python", "corenlp", "py4j" ]
ValueError: could not convert string to float: 'critical'
39,648,673
<pre><code>import pandas as pd from sklearn import cross_validation from sklearn.tree import DecisionTreeRegressor from sklearn.metrics import mean_squared_error names = ['dyastolic blood pressure','heart rate','pulse oximetry', 'respiratory rate','systolic blood pressure', 'temperature', 'class'] data = pd.read_csv("vitalsign1.csv", names = names) array = data.values X = array[:,0:6] y = array[:,6] X_train, X_test, y_train, y_test = cross_validation.train_test_split(X,y,test_size=.5) estimator = DecisionTreeRegressor(criterion = "mse", max_leaf_nodes = 6) estimator.fit(X_train,y_train) y_pred = estimator.predict(X_test) score = mean_squared_error(y_test,y_pred) </code></pre> <p>For the above code, I am receiving a value error:</p> <pre><code>ValueError: could not convert a string to float: 'critical' </code></pre> <p>which i do understand that on my "class" column i have two class called <code>critical</code> and <code>excellent</code> rather it should have a number such as <code>0</code> and <code>1</code>. but i want to keep the class as it is.</p> <p>how to solve this? my data looks like this :</p> <pre><code>115 77 99 18 148 35 critical 99 61 97 14 147 37 excellent </code></pre>
-4
2016-09-22T20:51:44Z
39,650,003
<p>Add a converter to <code>pandas.read_csv</code> to transform the symbols <code>critical</code> and <code>excellent</code> to <code>0</code> and <code>1</code> respectively.</p> <p>Something like the following:</p> <pre><code>&gt;&gt;&gt; data = pd.read_csv( "vitalsign1.csv", names=names, converters={ "class": lambda x: dict(critical=0, excellent=1)[x] } ) </code></pre> <p>This will result in a dataset like the following:</p> <pre><code>&gt;&gt;&gt; data dyastolic blood pressure heart rate pulse oximetry respiratory rate systolic blood pressure temperature class 0 115 77 99 18 148 35 0 1 99 61 97 14 147 37 1 </code></pre>
0
2016-09-22T22:47:03Z
[ "python", "machine-learning", "scikit-learn", "decision-tree" ]
how fix No module named parse in python3.4
39,648,718
<p>I am trying to run scripte python from github</p> <p>but i have problem</p> <pre><code>from urllib.parse import urlparse ImportError: No module named parse </code></pre> <p>i need install this module for python3.4 on kali linux</p>
-1
2016-09-22T20:55:05Z
39,648,754
<p>On python3 this will work</p> <pre><code>from urllib.parse import urlparse </code></pre> <p>On python2 it's this</p> <pre><code>from urlparse import urlparse </code></pre> <p>Double-check your python version in <code>sys.version_info.major</code>. </p>
1
2016-09-22T20:58:03Z
[ "python", "python-3.x", "module" ]
Special order of a list
39,648,737
<p>I have the following problem. It starts with a list which I get. Let's say for example I got the list: <code>A=['1-00', '10--']</code> (The list can be longer or even shorter e.g. <code>B=['01-1', '1-00', '0-01']</code>). It can also have more entries than four or less. Now I first have to sort for the rank. The rank is defined as the number of digits, that you see.</p> <p>In A I have one string of rank two <code>'10--'</code> and one of rank three <code>'1-00'</code>. (In B I have three of rank three) Now I need to get the number of four binary digits numbers which I get with all of the lowest rank strings first. </p> <p>Here I have only one rank two string <code>'10--'</code>I can produce: <code>'1000', '1001', '1010', '1011'</code>. So I get <strong>4</strong> binary numbers for rank two. With <code>'1-00'</code> I get <code>'1100'</code> and <code>'1000'</code>. But I already got the second one by the rank two string. So the number I should get is <strong>5</strong> for rank three. That is the number of distinct strings I get with rank two and rank three.</p> <p>I think its a tough problem but guess there are some commands which I don't know that could help. Hope you can give me some hints :) </p>
-1
2016-09-22T20:56:33Z
39,649,029
<p>If I understand your question, you want to sort by the number of fixed digits ("rank") first, then compute the total number of unique possible bit strings at or below each rank. So for <code>A</code>, you'd want it sorted to <code>['10--', '1-00']</code> (putting lower rank first), and you'd want to get the number of unique patterns for all rank 2 and lower patterns (in this case, there is only one), then for all rank 3 and lower patterns (again, in this case, only one), etc.</p> <p>If that understanding is correct, the first step is sorting:</p> <pre><code>A.sort(key=lambda x: x.count('0') + x.count('1')) # Or if all patterns are of length 4, the slightly simpler: A.sort(key=lambda x: 4 - x.count('-')) </code></pre> <p>After that, you process by ranks using <a href="https://docs.python.org/3/library/itertools.html#itertools.groupby" rel="nofollow"><code>itertools.groupby</code></a>, generating unique outputs with <a href="https://docs.python.org/3/library/itertools.html#itertools.product" rel="nofollow"><code>itertools.product</code></a> and storing them in a <code>set</code> so you remove duplicates:</p> <pre><code>from __future__ import print_function # For consistent print on Py2/Py3 from future_builtins import map # Only on Py2, to get Py3 generator based map from itertools import groupby, product uniquebits = set() for rank, pats in groupby(A, key=lambda x: x.count('0') + x.count('1')): for pat in pats: # product can be abused to sub 0, then 1 for each wildcarded space patpieces = [let if let != '-' else '01' for let in pat] # Generate all patterns (using ''.join reduces storage by converting # tuples back to str) updating the set to get unique values seen so far uniquebits.update(map(''.join, product(*patpieces))) print("For rank", rank, "and below,", len(uniquebits), "unique bit strings") </code></pre> <p>Which for your <code>A</code> would output:</p> <pre class="lang-none prettyprint-override"><code>For rank 2 and below, 4 unique bit strings For rank 3 and below, 5 unique bit strings </code></pre> <p>If you want to avoid gaps, and output for all ranks out to the maximum length of the patterns, it's slightly more complicated (since <code>groupby</code> only produces groups when there is at least one input with that "key", in this case, at least one input of a given rank):</p> <pre><code>lastrank = None # Change to 1 or 2 to force ranks prior to lowest rank to output for rank, pats in groupby(A, key=lambda x: x.count('0') + x.count('1')): if lastrank is not None and lastrank + 1 != rank: for fillrank in range(lastrank + 1, rank): print("For rank", fillrank, "and below,", len(uniquebits), "unique bit strings") lastrank = rank for pat in pats: # product can be abused to sub 0, then 1 for each wildcarded space patpieces = [let if let != '-' else '01' for let in pat] # Generate all patterns (using ''.join reduces storage by converting # tuples back to str) updating the set to get unique values seen so far uniquebits.update(map(''.join, product(*patpieces))) print("For rank", rank, "and below,", len(uniquebits), "unique bit strings") # Or len(max(A, key=len))+1 if uneven lengths for rank in range(lastrank + 1, len(A[0]) + 1): print("For rank", rank, "and below,", len(uniquebits), "unique bit strings") </code></pre>
1
2016-09-22T21:17:05Z
[ "python", "list" ]
Python trouble with looping through dictionary and replacing xml attribute
39,648,744
<p>I am having trouble looping through Python list below and replacing xml attribute with all <strong>ADSType</strong> values. </p> <p><strong>Python Dictionary</strong></p> <pre><code>{'ADSType': ['HS11N', 'HS11V'], 'Type': ['Bond', 'Cash']} </code></pre> <p><strong>XML</strong></p> <p>I'd like to replace <strong>sid</strong> values on each line in XML with ADS values. </p> <pre><code>&lt;req Times="1" action="get" chunklimit="1000" lang="ENU" msg="1" rank="1" rnklst="1" runuf="0"&gt; &lt;flds&gt; &lt;f end="2016-02-29" freq="m" i="bond(long) hff" sid="abc" start="2016-02-29" /&gt; &lt;f end="2016-02-29" freq="m" i="bond(short) ggg" sid="abc" start="2016-02-29" /&gt; &lt;/flds&gt; &lt;dat&gt; &lt;r CalculationType="3" ForceCalculate="1" i="123" /&gt; &lt;/dat&gt; &lt;/req&gt; </code></pre> <p><strong>Python Code so far:</strong></p> <pre><code>data_list = {'ADSType': ['HS11N', 'HS11V'], 'Type': ['Bond', 'Cash']} xml_file = './test.xml' tree1 = ET.ElementTree(file=xml_file) root1 = tree1.getroot() for x in root1.iter('flds'): for y in x.iter('f'): y.set('sid', y.get('sid').replace("123", "abc")) # print(ET.tostring(root1).decode("UTF-8")) print "test" # print(ET.tostring(root1).decode("UTF-8")) tree1.write("./test.xml") </code></pre> <p>I am stuck how to iterate over list, extract values, feed in replace method dynamically and update xml. Please help! Following is the desired output I am trying to achieve.</p> <pre><code>&lt;req Times="1" action="get" chunklimit="1000" lang="ENU" msg="1" rank="1" rnklst="1" runuf="0"&gt; &lt;flds&gt; &lt;f end="2016-02-29" freq="m" i="bond(long) hff" sid="HS11N" start="2016-02-29" /&gt; &lt;f end="2016-02-29" freq="m" i="bond(short) ggg" sid="HS11V" start="2016-02-29" /&gt; &lt;/flds&gt; &lt;dat&gt; &lt;r CalculationType="3" ForceCalculate="1" i="123" /&gt; &lt;/dat&gt; &lt;/req&gt; </code></pre>
1
2016-09-22T20:56:49Z
39,649,164
<p>This is a quick and dirty way of doing it.</p> <pre><code>for x in root1.iter('flds'): f = x.iter('f') for idx,y in enumerate(x): if y &lt; len(f): y.set('sid', y.get('sid').replace("abc",data_list['ADSType'][y])) </code></pre> <p>Simply use enumerate to get the index of f within XML. This is then used for the index within the data_list ADSType.</p> <p>Not added any verification of XML to make sure the attribute to replace exists. Nor have I took into consideration multiple 'flds' tags. Writing on a tablet so awkward to add more robust code. I'll try and update with something less quick and dirty when back at laptop</p>
-2
2016-09-22T21:28:53Z
[ "python", "xml", "loops", "dictionary" ]
Python trouble with looping through dictionary and replacing xml attribute
39,648,744
<p>I am having trouble looping through Python list below and replacing xml attribute with all <strong>ADSType</strong> values. </p> <p><strong>Python Dictionary</strong></p> <pre><code>{'ADSType': ['HS11N', 'HS11V'], 'Type': ['Bond', 'Cash']} </code></pre> <p><strong>XML</strong></p> <p>I'd like to replace <strong>sid</strong> values on each line in XML with ADS values. </p> <pre><code>&lt;req Times="1" action="get" chunklimit="1000" lang="ENU" msg="1" rank="1" rnklst="1" runuf="0"&gt; &lt;flds&gt; &lt;f end="2016-02-29" freq="m" i="bond(long) hff" sid="abc" start="2016-02-29" /&gt; &lt;f end="2016-02-29" freq="m" i="bond(short) ggg" sid="abc" start="2016-02-29" /&gt; &lt;/flds&gt; &lt;dat&gt; &lt;r CalculationType="3" ForceCalculate="1" i="123" /&gt; &lt;/dat&gt; &lt;/req&gt; </code></pre> <p><strong>Python Code so far:</strong></p> <pre><code>data_list = {'ADSType': ['HS11N', 'HS11V'], 'Type': ['Bond', 'Cash']} xml_file = './test.xml' tree1 = ET.ElementTree(file=xml_file) root1 = tree1.getroot() for x in root1.iter('flds'): for y in x.iter('f'): y.set('sid', y.get('sid').replace("123", "abc")) # print(ET.tostring(root1).decode("UTF-8")) print "test" # print(ET.tostring(root1).decode("UTF-8")) tree1.write("./test.xml") </code></pre> <p>I am stuck how to iterate over list, extract values, feed in replace method dynamically and update xml. Please help! Following is the desired output I am trying to achieve.</p> <pre><code>&lt;req Times="1" action="get" chunklimit="1000" lang="ENU" msg="1" rank="1" rnklst="1" runuf="0"&gt; &lt;flds&gt; &lt;f end="2016-02-29" freq="m" i="bond(long) hff" sid="HS11N" start="2016-02-29" /&gt; &lt;f end="2016-02-29" freq="m" i="bond(short) ggg" sid="HS11V" start="2016-02-29" /&gt; &lt;/flds&gt; &lt;dat&gt; &lt;r CalculationType="3" ForceCalculate="1" i="123" /&gt; &lt;/dat&gt; &lt;/req&gt; </code></pre>
1
2016-09-22T20:56:49Z
39,649,518
<p>You don't need to replace anything, just use <em>set</em> with the new value which will overwrite:</p> <pre><code>from xml.etree import ElementTree as ET xml_file = "./test.xml" tree = ET.parse(xml_file) root1 = tree.getroot() data_list = {'ADSType':['HS11N', 'HS11V'], 'Type': ['Bond', 'Cash']} # make iterator so we just call next(sids) to pull each value sids = iter(data_list['ADSType']) for flds in root1.iter('flds'): for f in flds.iter('f'): # set to new value f.set("sid", next(sids)) # write tree.write("./test.xml") </code></pre> <p>That does exactly what you want although I am not sure how the full dict fits into your question:</p> <p>test.xml:</p> <pre><code>In [3]: !cat test.xml &lt;req Times="1" action="get" chunklimit="1000" lang="ENU" msg="1" rank="1" rnklst="1" runuf="0"&gt; &lt;flds&gt; &lt;f end="2016-02-29" freq="m" i="bond(long) hff" sid="abc" start="2016-02-29" /&gt; &lt;f end="2016-02-29" freq="m" i="bond(short) ggg" sid="abc" start="2016-02-29" /&gt; &lt;/flds&gt; &lt;dat&gt; &lt;r CalculationType="3" ForceCalculate="1" i="123" /&gt; &lt;/dat&gt; &lt;/req&gt; </code></pre> <p>Run the code:</p> <pre><code>In [4]: from xml.etree import ElementTree as ET In [5]: xml_file = "./test.xml" In [6]: tree = ET.parse(xml_file) In [7]: root1 = tree.getroot() In [8]: data_list = {'ADSType': iter(['HS11N', 'HS11V']), 'Type': iter(['Bond', 'Cash'])} In [9]: sids = iter(data_list['ADSType']) In [10]: for flds in root1.iter('flds'): ....: for f in x.iter('f'): ....: f.set("sid", next(sids)) ....: tree.write("./test.xml") ....: </code></pre> <p>New test.xml:</p> <pre><code>In [11]: !cat test.xml &lt;req Times="1" action="get" chunklimit="1000" lang="ENU" msg="1" rank="1" rnklst="1" runuf="0"&gt; &lt;flds&gt; &lt;f end="2016-02-29" freq="m" i="bond(long) hff" sid="HS11N" start="2016-02-29" /&gt; &lt;f end="2016-02-29" freq="m" i="bond(short) ggg" sid="HS11V" start="2016-02-29" /&gt; &lt;/flds&gt; &lt;dat&gt; &lt;r CalculationType="3" ForceCalculate="1" i="123" /&gt; &lt;/dat&gt; &lt;/req&gt; </code></pre> <p>If you have multiple f's inside multiple fld's and want to cycle the values, use <em>itertools.cycle</em> in place of iter:</p> <pre><code>from itertools import cycle sids = cycle(data_list['ADSType']) </code></pre>
2
2016-09-22T21:58:44Z
[ "python", "xml", "loops", "dictionary" ]
Convert MongoDB Date format to String in Python (without using dateToString)
39,648,747
<p>I would like to convert a MongoDB Date Object to a string.</p> <p><strong>However, I am unable to use the "dateToString" operator because I am running MongoDB 2.6 and do not have the option to upgrade at this time.</strong></p> <p>What should I use instead?</p> <p>Query:</p> <pre><code>computer = db['cmp_host'].aggregate([ {"$project":{ "u_ipv4": "$addresses.ipv4", #"u_updated_timestamp": "$last_seen", #"u_updated_timestamp": { $dateToString: { format: "%Y-%m-%d", date: "$last_seen" } } } } ]) </code></pre> <p>Current MongoDB Date format (needs to be converted to human readable string):</p> <pre><code>datetime.datetime(2016, 9, 2, 12, 5, 18, 521000) </code></pre>
0
2016-09-22T20:57:04Z
39,650,845
<p>The <code>datetime.datetime(2016, 9, 2, 12, 5, 18, 521000)</code> is a Python datetime type, not MongoDB's.</p> <p>To convert it into a string, you can use Python datetime's <code>strftime()</code> method. For example:</p> <pre><code>&gt;&gt;&gt; d = datetime.datetime(2016, 9, 2, 12, 5, 18, 521000) &gt;&gt;&gt; d.strftime('%Y-%m-%d') '2016-09-02' &gt;&gt;&gt; d.strftime('%c') 'Fri Sep 2 12:05:18 2016' </code></pre> <p>The full description of <code>strftime()</code> is here: <a href="https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior" rel="nofollow">https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior</a></p>
1
2016-09-23T00:34:29Z
[ "python", "mongodb", "date" ]
Creating SQLAlchemy model instance raises "TypeError: __init__() takes exactly 1 argument"
39,648,772
<p>I have defined a model with Flask-SQLAlchemy and want to insert a row with it in a Flask view. When I try to create the instance, I get <code>TypeError: __init__() takes exactly 1 argument (5 given)</code>. I think the issue has to do with the constructor but the <a href="http://flask-sqlalchemy.pocoo.org/2.1/queries/" rel="nofollow">docs</a> don't really explain what is required. How do I create an instance of my model while passing data to it?</p> <pre><code>class Update(db.Model): id = db.Column(db.Integer, primary_key=True) tracking_number = db.Column(db.Integer) date = db.Column(db.DateTime) status = db.Column(db.String(80)) location = db.Column(db.String(80)) @app.route('/put_update') def put_update(): update = Update('trackingid', '2016-08-30 22:48:00', 'status', 'location') db.session.add(update) db.session.commit() </code></pre>
1
2016-09-22T20:59:01Z
39,648,933
<p>SQLAlchemy provides a default constructor that takes keyword arguments and assigns them to the instance.</p> <pre><code>Update(trackingnumber='trackingid', ...) </code></pre> <p>This is typically all you need, and is convenient for uses like unpacking data you get from a form (as long as the field names match up).</p> <p>If you don't want to pass keywords, you can override <code>__init__</code> to take whatever arguments in whatever order you want. For example, if <code>Update</code> always needs <code>trackingnumber</code> and you want to pass it as the first positional argument:</p> <pre><code>class Update(db.Model): ... def __init__(self, trackingnumber, **kwargs): self.trackingnumber = trackingnumber super().__init__(**kwargs) </code></pre> <p>This can be useful in some situations but typically you should just stick with the default of passing keyword arguments.</p>
1
2016-09-22T21:11:04Z
[ "python", "flask", "sqlalchemy", "flask-sqlalchemy" ]
TypeError: unsupported operand type(s) for -: 'str' and 'int'
39,648,779
<p>Right now my code will create a text file including the positions of each word in a sentence in a list, and each word in a list - like so: </p> <p><a href="http://i.stack.imgur.com/UeqOs.png" rel="nofollow"><img src="http://i.stack.imgur.com/UeqOs.png" alt="file content"></a></p> <p>My code then opens back up the file and should be able to recreate the sentence using those positions and the words in the text file, but it doesn't seem to work with with the readlines code for some reason.</p> <pre><code>openfilename = open(openfilename,"r") readlines = openfilename.readlines() wordslist = readlines[0] positionslist = readlines[1] print(positionslist) print(wordslist) originalsentence = " ".join([wordslist[x-1] for x in positionslist]) print(originalsentence) </code></pre> <p>For example this comes up with wordslist and positionslist coming out as:</p> <pre><code>[1, 2, 3, 2] ['test123', ',', '.'] </code></pre> <p>Where as if I were to use:</p> <pre><code>positionslist = [1, 2, 3, 2] wordslist = ['test123', ',', '.'] originalsentence = " ".join([wordslist[x-1] for x in positionslist]) print(originalsentence) </code></pre> <p>It would work, and I have no idea why because, as a newcomer to python, you'd think they'd work the same. Looking at other people's post with the same error I'm supposedly missing a </p> <pre><code>(int(...) </code></pre> <p>line of code somewhere but I'm not sure where, or if that's even the problem.</p>
-1
2016-09-22T20:59:31Z
39,648,810
<p>EDIT: this answer assumes a "raw" format. It won't work here. It <em>would</em> work if <code>readlines[1]</code> was already a list of strings obtained by splitting a line like <code>"1 4 5 6 7"</code>, which isn't the case here since line contains a python list written as a <code>str(list)</code>. <code>ast.literal.eval</code> is the right choice in that case, <em>if</em> the input format is satisfying and not a mistake in the first place.</p> <p>when you do:</p> <pre><code>positionslist = readlines[1] </code></pre> <p>there's no way you get something other than a list of strings containing integers. You have to convert them for example like this:</p> <pre><code>positionslist = [int(x) for x in readlines[1]] </code></pre> <p>In your hardcoded example, you're using integers directly and it works.</p> <p>Note: as cricket_007 suggested, since you just iterate on <code>positionslist</code>, you can use</p> <pre><code>positionslist = map(int,readlines[1]) </code></pre> <p>It applies the <code>int</code> function to each item of <code>readlines[1]</code>, returns an iterable (returns <code>list</code> in Python 2, so not that much different from the list comprehension above in that case).</p> <p>In Python 3, that avoids to create/allocate a list that you don't need since you don't use indexes (if you want to debug it you can't since you can iterate only once on it), so it is more performant.</p> <p>of course, if some line is not a digit it will crash with an explicit error <code>ValueError: invalid literal for int() with base 10</code></p>
2
2016-09-22T21:02:06Z
[ "python" ]
TypeError: unsupported operand type(s) for -: 'str' and 'int'
39,648,779
<p>Right now my code will create a text file including the positions of each word in a sentence in a list, and each word in a list - like so: </p> <p><a href="http://i.stack.imgur.com/UeqOs.png" rel="nofollow"><img src="http://i.stack.imgur.com/UeqOs.png" alt="file content"></a></p> <p>My code then opens back up the file and should be able to recreate the sentence using those positions and the words in the text file, but it doesn't seem to work with with the readlines code for some reason.</p> <pre><code>openfilename = open(openfilename,"r") readlines = openfilename.readlines() wordslist = readlines[0] positionslist = readlines[1] print(positionslist) print(wordslist) originalsentence = " ".join([wordslist[x-1] for x in positionslist]) print(originalsentence) </code></pre> <p>For example this comes up with wordslist and positionslist coming out as:</p> <pre><code>[1, 2, 3, 2] ['test123', ',', '.'] </code></pre> <p>Where as if I were to use:</p> <pre><code>positionslist = [1, 2, 3, 2] wordslist = ['test123', ',', '.'] originalsentence = " ".join([wordslist[x-1] for x in positionslist]) print(originalsentence) </code></pre> <p>It would work, and I have no idea why because, as a newcomer to python, you'd think they'd work the same. Looking at other people's post with the same error I'm supposedly missing a </p> <pre><code>(int(...) </code></pre> <p>line of code somewhere but I'm not sure where, or if that's even the problem.</p>
-1
2016-09-22T20:59:31Z
39,648,841
<p>The issue is, when you read from the file, the values are of <code>str</code> type by default. And when you try to do <code>x-1</code> in <code>[wordslist[x-1] for x in positionslist]</code>, you get error because you try to <code>subtract</code> 1 from string. In order to fix this, convert <code>positionslist</code> to list of int's as:</p> <pre><code>positionslist = readlines[1] positionslist = map(int, positionslist) # &lt;-- add this line in your code </code></pre> <p>and your code will work. Check <a href="https://docs.python.org/2/library/functions.html#map" rel="nofollow"><code>map()</code></a> to know about it.</p>
0
2016-09-22T21:04:30Z
[ "python" ]
TypeError: unsupported operand type(s) for -: 'str' and 'int'
39,648,779
<p>Right now my code will create a text file including the positions of each word in a sentence in a list, and each word in a list - like so: </p> <p><a href="http://i.stack.imgur.com/UeqOs.png" rel="nofollow"><img src="http://i.stack.imgur.com/UeqOs.png" alt="file content"></a></p> <p>My code then opens back up the file and should be able to recreate the sentence using those positions and the words in the text file, but it doesn't seem to work with with the readlines code for some reason.</p> <pre><code>openfilename = open(openfilename,"r") readlines = openfilename.readlines() wordslist = readlines[0] positionslist = readlines[1] print(positionslist) print(wordslist) originalsentence = " ".join([wordslist[x-1] for x in positionslist]) print(originalsentence) </code></pre> <p>For example this comes up with wordslist and positionslist coming out as:</p> <pre><code>[1, 2, 3, 2] ['test123', ',', '.'] </code></pre> <p>Where as if I were to use:</p> <pre><code>positionslist = [1, 2, 3, 2] wordslist = ['test123', ',', '.'] originalsentence = " ".join([wordslist[x-1] for x in positionslist]) print(originalsentence) </code></pre> <p>It would work, and I have no idea why because, as a newcomer to python, you'd think they'd work the same. Looking at other people's post with the same error I'm supposedly missing a </p> <pre><code>(int(...) </code></pre> <p>line of code somewhere but I'm not sure where, or if that's even the problem.</p>
-1
2016-09-22T20:59:31Z
39,649,251
<p>Another solution is to use <a href="https://docs.python.org/3/library/ast.html#ast.literal_eval" rel="nofollow"><code>ast.literal_eval()</code></a> to convert your string <code>u'[1, 2, 3, 2]</code> directly into a list of interger:</p> <pre><code>import ast with open(openfilename, "r") as f: positionslist = ast.literal_eval(f.readline()) wordslist = ast.literal_eval(f.readline()) print(" ".join([wordslist[x-1] for x in positionslist])) </code></pre> <p>Also, the <a href="https://docs.python.org/3/reference/compound_stmts.html#the-with-statement" rel="nofollow"><code>with</code></a> statement replace a try and catch. It also automatically close the file after the block.</p>
2
2016-09-22T21:35:31Z
[ "python" ]
Best way to share a variable with multiple instances of the same python script
39,648,803
<p>I'm making a simple home automation system with my Beagle Bone, raspberry pi and a hand full of components. I have a simple interface on a webpage and i'm currently trying to remotely toggle a relay. Right now I have a button on the webpage that uses php to call a python script that either turns the relay on or off depending on a boolean. </p> <p>I'm having trouble figuring out the best way to share this boolean. Is there any way to pass a php varible into the python script? or is there anyway to have the python interpreter "keep/save" the state of the variable in-betweeen instances of the script. Or is the best way just to have it write/read from a common file? any help would be awesome</p>
1
2016-09-22T21:01:41Z
39,649,062
<p>I am unfamiliar with php, but could you have php write to a temporary text file, and then when that python script gets called, it simply reads in that text file to store the boolean value?</p>
0
2016-09-22T21:21:25Z
[ "php", "python", "linux", "apache", "beagleboneblack" ]
How to split delimited values in a SQLite column into multiple columns
39,648,820
<p>How can I parse comma separated values in <code>Fruit Basket</code> and move them to other columns. </p> <p>For example, I want this</p> <pre><code>Fruit Basket Fruit1 Fruit2 Fruit3 ------------ -------- -------- -------- Apple Banana, Pear Lemon, Peach, Apricot </code></pre> <p>to becomes this</p> <pre><code>Fruit Basket Fruit1 Fruit2 Fruit3 ------------ -------- -------- -------- Apple Apple Banana, Pear Banana Pear Lemon, Pea... Lemon Peach Apricot </code></pre> <p>If I cannot do this with a pure SQLite statement, how can I do it using Python?</p>
0
2016-09-22T21:02:48Z
39,648,921
<p>Check the man page : </p> <pre><code>man sqlite3 | less +/-csv </code></pre> <p>Then use </p> <pre><code>sqlite ... -csv | ... </code></pre> <p>the output will be quit more easy to parse</p>
0
2016-09-22T21:10:26Z
[ "python", "sqlite" ]
How to split delimited values in a SQLite column into multiple columns
39,648,820
<p>How can I parse comma separated values in <code>Fruit Basket</code> and move them to other columns. </p> <p>For example, I want this</p> <pre><code>Fruit Basket Fruit1 Fruit2 Fruit3 ------------ -------- -------- -------- Apple Banana, Pear Lemon, Peach, Apricot </code></pre> <p>to becomes this</p> <pre><code>Fruit Basket Fruit1 Fruit2 Fruit3 ------------ -------- -------- -------- Apple Apple Banana, Pear Banana Pear Lemon, Pea... Lemon Peach Apricot </code></pre> <p>If I cannot do this with a pure SQLite statement, how can I do it using Python?</p>
0
2016-09-22T21:02:48Z
39,649,093
<p>Pulling apart the one column is be pretty simple for Python (not sure about SQLite). This simplifies your DB row into an array of strings and should be similar for the SQLite return.</p> <pre><code>text = [ 'Apple', 'Banana, Pear', 'Lemon, Peach, Apricot' ] for line in text: cols = [c.strip() for c in line.split(',')] print(cols) </code></pre> <p>Should output an array for each string line:</p> <pre><code>['Apple'] ['Banana', 'Pear'] ['Lemon', 'Peach', 'Apricot'] </code></pre> <p><strong>edit:</strong></p> <p>Here's a full Python script to do what you're looking for to SQLite:</p> <pre><code>import sqlite3 conn = sqlite3.connect('test.db') c = conn.cursor() c.execute( '''SELECT * FROM Fruits WHERE Fruit_Basket IS NOT NULL''' ) rows = c.fetchall() for row in rows: fruit_basket = row[0] fruits = [f.strip() for f in fruit_basket.split(',')] while (len(fruits) &lt; 3): fruits.append('') print(fruits) update = '''UPDATE Fruits SET Fruit1 = ?, Fruit2 = ?, Fruit3 = ? WHERE Fruit_Basket = ?''' c.execute(update, fruits + [fruit_basket,]) conn.commit() conn.close() </code></pre>
0
2016-09-22T21:22:49Z
[ "python", "sqlite" ]
How to split delimited values in a SQLite column into multiple columns
39,648,820
<p>How can I parse comma separated values in <code>Fruit Basket</code> and move them to other columns. </p> <p>For example, I want this</p> <pre><code>Fruit Basket Fruit1 Fruit2 Fruit3 ------------ -------- -------- -------- Apple Banana, Pear Lemon, Peach, Apricot </code></pre> <p>to becomes this</p> <pre><code>Fruit Basket Fruit1 Fruit2 Fruit3 ------------ -------- -------- -------- Apple Apple Banana, Pear Banana Pear Lemon, Pea... Lemon Peach Apricot </code></pre> <p>If I cannot do this with a pure SQLite statement, how can I do it using Python?</p>
0
2016-09-22T21:02:48Z
39,649,531
<p>Got it</p> <pre><code>def returnFruitName(string, index): #Split string and remove white space return [x.strip() for x in string.split(',')][index] cur.create_function("returnFruitName", 2, returnFruitName) cur.execute("UPDATE t SET Fruit1 = returnFruitName(FruitBasket,0) WHERE FruitBasket IS NOT NULL;") cur.execute("UPDATE t SET Fruit2 = returnFruitName(FruitBasket,1) WHERE FruitBasket IS NOT NULL;") cur.execute("UPDATE t SET Fruit3 = returnFruitName(FruitBasket,1) WHERE FruitBasket IS NOT NULL;") </code></pre>
0
2016-09-22T21:59:51Z
[ "python", "sqlite" ]
AttributeError: module 'mypandas' has no attribute 'print_pandas_df'
39,648,822
<p>I have the following python program <code>test_pandas.py</code>.</p> <pre><code># !/usr/bin/env python3.4 # -*- coding: utf-8 -*- import pprint import pandas as pd import mypandas.mypandas df = pd.read_csv('AllStarFull.csv') mypandas.print_pandas_df(df,50,8) # groupby 'player ID' print('Grouping by Player ID') gb = df.groupby(['playerID']) pprint.pprint(list(gb)) # groupby 'yearID' print('Grouping by Year ID') gb = df.groupby(['yearID']) pprint.pprint(list(gb)) </code></pre> <p>My folder structure is as follows.</p> <pre><code>--python --concepts --mypandas --mypandas.py --__init__.py --test_pandas.py </code></pre> <p>When I run the <code>test_pandas.py</code> I get the following error.</p> <pre><code> UserWarning) Traceback (most recent call last): File "C:/Cubic/playpen/python/concepts/pandas/test_pandas.py", line 11, in &lt;module&gt; mypandas.print_pandas_df(df,50,8) AttributeError: module 'mypandas' has no attribute 'print_pandas_df' </code></pre> <p><code>mypandas.py</code> has the function <code>print_pandas_df</code></p> <pre><code>import pandas as pd import pprint def print_pandas_df(df, rows, columns): with pd.option_context('display.max_rows', rows, 'display.max_columns', columns): pprint.pprint(df) </code></pre>
0
2016-09-22T21:02:55Z
39,648,981
<p>You need to put the full path: directory.filename.methodname:</p> <pre><code>mypandas.mypandas.print_pandas_df(df,50,8) </code></pre> <p>You can also say</p> <pre><code>from mypandas import mypandas </code></pre> <p>and then write your code as is.</p>
1
2016-09-22T21:14:08Z
[ "python", "pandas" ]
How To Find The Position Of A Word In A List Made By The User
39,648,836
<p>Code: (Python 3.5.2)</p> <pre><code>import time import sys def Word_Position_Finder(): Chosen_Sentence = input("Make a simple sentence: ").upper() print(Chosen_Sentence) Sentence_List = Chosen_Sentence.split() if len(Chosen_Sentence) == 0: print("Your Sentence has no words! Restarting Program.") time.sleep(1) Restarting_Program() print(Sentence_List) time.sleep(1) Users_Choice = input("Do you want to make a new sentence (press 1) or keep current sentence (press 2): ") if Users_Choice == "1": print("Restarting Program.") time.sleep(1) Restarting_Program() elif Users_Choice == "2": #Lines Under Here Don't Work As Wanted print("'" + Chosen_Sentence + "'" + ". This is your sentence.") Chosen_Word = input("Which word in your sentence do you want to find the position of? ").upper() for Users_List in Sentence_List: if Users_List == Chosen_Word.upper(): print("Your word appears in the number " + str((Users_List.index(Chosen_Word) +1)) + " slot of this sentence") #Lines Above Here Don't Work As Wanted else: print("That isn't a valid answer") Choose_To_Restart() def Choose_To_Restart(): time.sleep(1) loop = input("Want to try again, Y/N?") if loop.upper() == "Y" or loop.upper() == "YES": print("Restarting Program") time.sleep(1) Restarting_Program() elif loop.upper() == "N" or loop.upper() == "NO": print("Ending Program") time.sleep(1) sys.exit("Program Ended") else: print("Ok.") time.sleep(1) sys.exit("Program Ended") def Restarting_Program(): Word_Position_Finder() Word_Position_Finder() </code></pre> <p><strong>What The Code Is Trying To Achieve</strong></p> <ul> <li>The code above takes a string made by the user, turns it into a list, asks the user if they're happy with this string, then asks the user what word in the list they just made they want to know the position of and pastes the position of that chosen word in the users list.</li> </ul> <p><strong>The Question</strong></p> <ul> <li>In the code I have put two hashtags, "#The code below this line doesn't work" and "#The code above this line doesn't work". Everything else is fine and doesn't need to be changed, with these four lines I want the user to choose a word and I want to loop through the users pre-made list to find the location(s) of their chosen word. However, what the code currently does is when it gets to the four lines, it will ask the user for the word they want to find in their premade list and always print, "print("Your word appears in the number ""1"" slot of this sentence"). The code will always say it has appeared in slot one, or restart itself. Basically, I just want to know if anyone can try to fix this code because I have spent a solid four hours now messing with these four lines trying to get it to work as wanted.</li> </ul>
1
2016-09-22T21:04:14Z
39,648,913
<pre><code>normalized_list = [word.upper() for word in Sentence_List] try: index= normalized_list.index(Chosen_Word.upper()) except: print "Not Found! %s NOT in %s"%(Chosen_Word,Sentence_List) else: print "%s @ %s"%(Chosen_Word, index) </code></pre> <p>as a totally unrelated aside you should read the python pep8 especially the bit about variable names ...</p>
2
2016-09-22T21:09:59Z
[ "python" ]
How To Find The Position Of A Word In A List Made By The User
39,648,836
<p>Code: (Python 3.5.2)</p> <pre><code>import time import sys def Word_Position_Finder(): Chosen_Sentence = input("Make a simple sentence: ").upper() print(Chosen_Sentence) Sentence_List = Chosen_Sentence.split() if len(Chosen_Sentence) == 0: print("Your Sentence has no words! Restarting Program.") time.sleep(1) Restarting_Program() print(Sentence_List) time.sleep(1) Users_Choice = input("Do you want to make a new sentence (press 1) or keep current sentence (press 2): ") if Users_Choice == "1": print("Restarting Program.") time.sleep(1) Restarting_Program() elif Users_Choice == "2": #Lines Under Here Don't Work As Wanted print("'" + Chosen_Sentence + "'" + ". This is your sentence.") Chosen_Word = input("Which word in your sentence do you want to find the position of? ").upper() for Users_List in Sentence_List: if Users_List == Chosen_Word.upper(): print("Your word appears in the number " + str((Users_List.index(Chosen_Word) +1)) + " slot of this sentence") #Lines Above Here Don't Work As Wanted else: print("That isn't a valid answer") Choose_To_Restart() def Choose_To_Restart(): time.sleep(1) loop = input("Want to try again, Y/N?") if loop.upper() == "Y" or loop.upper() == "YES": print("Restarting Program") time.sleep(1) Restarting_Program() elif loop.upper() == "N" or loop.upper() == "NO": print("Ending Program") time.sleep(1) sys.exit("Program Ended") else: print("Ok.") time.sleep(1) sys.exit("Program Ended") def Restarting_Program(): Word_Position_Finder() Word_Position_Finder() </code></pre> <p><strong>What The Code Is Trying To Achieve</strong></p> <ul> <li>The code above takes a string made by the user, turns it into a list, asks the user if they're happy with this string, then asks the user what word in the list they just made they want to know the position of and pastes the position of that chosen word in the users list.</li> </ul> <p><strong>The Question</strong></p> <ul> <li>In the code I have put two hashtags, "#The code below this line doesn't work" and "#The code above this line doesn't work". Everything else is fine and doesn't need to be changed, with these four lines I want the user to choose a word and I want to loop through the users pre-made list to find the location(s) of their chosen word. However, what the code currently does is when it gets to the four lines, it will ask the user for the word they want to find in their premade list and always print, "print("Your word appears in the number ""1"" slot of this sentence"). The code will always say it has appeared in slot one, or restart itself. Basically, I just want to know if anyone can try to fix this code because I have spent a solid four hours now messing with these four lines trying to get it to work as wanted.</li> </ul>
1
2016-09-22T21:04:14Z
39,648,937
<pre><code>if Users_List == Chosen_Word.upper(): # &lt;-- .upper() with Choosen_word ..something.. str((Users_List.index(Chosen_Word) +1)) # &lt;-- without ".upper()" </code></pre> <p>Make it consistent at both the places. Add/remove <code>.upper()</code> based on you want case-insensitive/sensitive search.</p>
0
2016-09-22T21:11:27Z
[ "python" ]
How To Find The Position Of A Word In A List Made By The User
39,648,836
<p>Code: (Python 3.5.2)</p> <pre><code>import time import sys def Word_Position_Finder(): Chosen_Sentence = input("Make a simple sentence: ").upper() print(Chosen_Sentence) Sentence_List = Chosen_Sentence.split() if len(Chosen_Sentence) == 0: print("Your Sentence has no words! Restarting Program.") time.sleep(1) Restarting_Program() print(Sentence_List) time.sleep(1) Users_Choice = input("Do you want to make a new sentence (press 1) or keep current sentence (press 2): ") if Users_Choice == "1": print("Restarting Program.") time.sleep(1) Restarting_Program() elif Users_Choice == "2": #Lines Under Here Don't Work As Wanted print("'" + Chosen_Sentence + "'" + ". This is your sentence.") Chosen_Word = input("Which word in your sentence do you want to find the position of? ").upper() for Users_List in Sentence_List: if Users_List == Chosen_Word.upper(): print("Your word appears in the number " + str((Users_List.index(Chosen_Word) +1)) + " slot of this sentence") #Lines Above Here Don't Work As Wanted else: print("That isn't a valid answer") Choose_To_Restart() def Choose_To_Restart(): time.sleep(1) loop = input("Want to try again, Y/N?") if loop.upper() == "Y" or loop.upper() == "YES": print("Restarting Program") time.sleep(1) Restarting_Program() elif loop.upper() == "N" or loop.upper() == "NO": print("Ending Program") time.sleep(1) sys.exit("Program Ended") else: print("Ok.") time.sleep(1) sys.exit("Program Ended") def Restarting_Program(): Word_Position_Finder() Word_Position_Finder() </code></pre> <p><strong>What The Code Is Trying To Achieve</strong></p> <ul> <li>The code above takes a string made by the user, turns it into a list, asks the user if they're happy with this string, then asks the user what word in the list they just made they want to know the position of and pastes the position of that chosen word in the users list.</li> </ul> <p><strong>The Question</strong></p> <ul> <li>In the code I have put two hashtags, "#The code below this line doesn't work" and "#The code above this line doesn't work". Everything else is fine and doesn't need to be changed, with these four lines I want the user to choose a word and I want to loop through the users pre-made list to find the location(s) of their chosen word. However, what the code currently does is when it gets to the four lines, it will ask the user for the word they want to find in their premade list and always print, "print("Your word appears in the number ""1"" slot of this sentence"). The code will always say it has appeared in slot one, or restart itself. Basically, I just want to know if anyone can try to fix this code because I have spent a solid four hours now messing with these four lines trying to get it to work as wanted.</li> </ul>
1
2016-09-22T21:04:14Z
39,649,011
<p>So this will find the position of the word in a list, you can easily modify it for your code.</p> <pre><code>Users_List = ['foo', 'boo', 'myword', 'fdjasi'] Chosen_Word = 'myword' word_index = 0 for word in Users_List: if word == Chosen_Word: print("Your word appears in the number " + str((word_index)) + " slot of this sentence") else: word_index += 1 </code></pre> <p>Note that this is the index, and indexes in python start from 0, not 1. If you wanted a more human representation, just add one to the count like this.</p> <pre><code>Users_List = ['foo', 'boo', 'myword', 'fdjasi'] Chosen_Word = 'myword' word_index = 0 for word in Users_List: if word == Chosen_Word: print("Your word appears in the number " + str((word_index + 1)) + " slot of this sentence") else: word_index += 1 </code></pre>
0
2016-09-22T21:16:07Z
[ "python" ]
How To Find The Position Of A Word In A List Made By The User
39,648,836
<p>Code: (Python 3.5.2)</p> <pre><code>import time import sys def Word_Position_Finder(): Chosen_Sentence = input("Make a simple sentence: ").upper() print(Chosen_Sentence) Sentence_List = Chosen_Sentence.split() if len(Chosen_Sentence) == 0: print("Your Sentence has no words! Restarting Program.") time.sleep(1) Restarting_Program() print(Sentence_List) time.sleep(1) Users_Choice = input("Do you want to make a new sentence (press 1) or keep current sentence (press 2): ") if Users_Choice == "1": print("Restarting Program.") time.sleep(1) Restarting_Program() elif Users_Choice == "2": #Lines Under Here Don't Work As Wanted print("'" + Chosen_Sentence + "'" + ". This is your sentence.") Chosen_Word = input("Which word in your sentence do you want to find the position of? ").upper() for Users_List in Sentence_List: if Users_List == Chosen_Word.upper(): print("Your word appears in the number " + str((Users_List.index(Chosen_Word) +1)) + " slot of this sentence") #Lines Above Here Don't Work As Wanted else: print("That isn't a valid answer") Choose_To_Restart() def Choose_To_Restart(): time.sleep(1) loop = input("Want to try again, Y/N?") if loop.upper() == "Y" or loop.upper() == "YES": print("Restarting Program") time.sleep(1) Restarting_Program() elif loop.upper() == "N" or loop.upper() == "NO": print("Ending Program") time.sleep(1) sys.exit("Program Ended") else: print("Ok.") time.sleep(1) sys.exit("Program Ended") def Restarting_Program(): Word_Position_Finder() Word_Position_Finder() </code></pre> <p><strong>What The Code Is Trying To Achieve</strong></p> <ul> <li>The code above takes a string made by the user, turns it into a list, asks the user if they're happy with this string, then asks the user what word in the list they just made they want to know the position of and pastes the position of that chosen word in the users list.</li> </ul> <p><strong>The Question</strong></p> <ul> <li>In the code I have put two hashtags, "#The code below this line doesn't work" and "#The code above this line doesn't work". Everything else is fine and doesn't need to be changed, with these four lines I want the user to choose a word and I want to loop through the users pre-made list to find the location(s) of their chosen word. However, what the code currently does is when it gets to the four lines, it will ask the user for the word they want to find in their premade list and always print, "print("Your word appears in the number ""1"" slot of this sentence"). The code will always say it has appeared in slot one, or restart itself. Basically, I just want to know if anyone can try to fix this code because I have spent a solid four hours now messing with these four lines trying to get it to work as wanted.</li> </ul>
1
2016-09-22T21:04:14Z
39,649,222
<p>In this line</p> <pre><code>print("Your word appears in the number " + str((Users_List.index(Chosen_Word) +1)) + " slot of this sentence") </code></pre> <p>you are trying to get the index of the Chosen_Word in <em>one</em> of the words of the sentence. You want the index in the sentence. Problem is that</p> <pre><code>print("Your word appears in the number " + str((Sentence_List.index(Chosen_Word) +1)) + " slot of this sentence") </code></pre> <p>isn't working either when Chosen_Word appears more than once in the sentence. So it is better to reformulate the loop with <em>enumerate</em>:</p> <pre><code>for i, Users_List in enumerate(Sentence_List): if Users_List == Chosen_Word: print("Your word appears in the number " + str(i+1) + " slot of this sentence") </code></pre> <p>Note, that I also removed one <em>upper</em> call. You already called <em>upper</em> when the word is input.</p> <p>Also note, that you do not get an output when the word is not in the sentence. You may want to add a special output in this case.</p>
0
2016-09-22T21:33:32Z
[ "python" ]
Need to create a Pandas dataframe by reading csv file with random columns
39,648,855
<p>I have the following csv file with records:</p> <ul> <li>A 1, B 2, C 10, D 15</li> <li>A 5, D 10, G 2</li> <li>D 6, E 7</li> <li>H 7, G 8</li> </ul> <p>My column headers/names are: A, B, C, D, E, F, G</p> <p>So my initial dataframe after using "read_csv" becomes: </p> <pre><code>A B C D E F G A 1 B 2 C 10 D 15 NaN NaN NaN A 5 D 10 G 2 NaN NaN NaN NaN D 6 E 7 NaN NaN NaN NaN NaN H 7 G 8 NaN NaN NaN NaN Nan </code></pre> <p>The value can be separate into [column name][column value], so A 1 means col=A and value=1, and D 15 means col=D and value=15, etc...</p> <p>What I want is to assign the numeric value to the appropriate column based on the and have a dataframe that looks like this:</p> <pre><code>A B C D E F G A 1 B 2 C 10 D 15 NaN NaN NaN A 5 Nan NaN D 10 NaN NaN G 2 NaN NaN NaN D 6 E 7 NaN NaN NaN NaN NaN NaN NaN NaN G 8 </code></pre> <p>And even better, just the values alone:</p> <pre><code>A B C D E F G 1 2 10 15 NaN NaN NaN 5 Nan NaN 10 NaN NaN 2 NaN NaN NaN 6 7 NaN NaN NaN NaN NaN NaN NaN NaN 8 </code></pre>
0
2016-09-22T21:05:24Z
39,649,250
<p>You can loop through rows with <code>apply</code> function(<code>axis = 1</code>) and construct a pandas series for each row based on the key value pairs after the splitting, and the newly constructed series will be automatically aligned by their index, just notice here there is no <code>F</code> column but an extra <code>H</code>, not sure if it is what you need. But removing the <code>H</code> and adding an extra NaN <code>F</code> column should be straight forward: </p> <pre><code>df.apply(lambda r: pd.Series({x[0]: x[1] for x in r.str.split(' ') if isinstance(x, list) and len(x) == 2}), axis = 1) # A B C D E G H #0 1 2 10 15 NaN NaN NaN #1 5 NaN NaN 10 NaN 2 NaN #2 NaN NaN NaN 6 7 NaN NaN #3 NaN NaN NaN NaN NaN 8 7 </code></pre>
1
2016-09-22T21:35:26Z
[ "python", "csv", "pandas" ]
Need to create a Pandas dataframe by reading csv file with random columns
39,648,855
<p>I have the following csv file with records:</p> <ul> <li>A 1, B 2, C 10, D 15</li> <li>A 5, D 10, G 2</li> <li>D 6, E 7</li> <li>H 7, G 8</li> </ul> <p>My column headers/names are: A, B, C, D, E, F, G</p> <p>So my initial dataframe after using "read_csv" becomes: </p> <pre><code>A B C D E F G A 1 B 2 C 10 D 15 NaN NaN NaN A 5 D 10 G 2 NaN NaN NaN NaN D 6 E 7 NaN NaN NaN NaN NaN H 7 G 8 NaN NaN NaN NaN Nan </code></pre> <p>The value can be separate into [column name][column value], so A 1 means col=A and value=1, and D 15 means col=D and value=15, etc...</p> <p>What I want is to assign the numeric value to the appropriate column based on the and have a dataframe that looks like this:</p> <pre><code>A B C D E F G A 1 B 2 C 10 D 15 NaN NaN NaN A 5 Nan NaN D 10 NaN NaN G 2 NaN NaN NaN D 6 E 7 NaN NaN NaN NaN NaN NaN NaN NaN G 8 </code></pre> <p>And even better, just the values alone:</p> <pre><code>A B C D E F G 1 2 10 15 NaN NaN NaN 5 Nan NaN 10 NaN NaN 2 NaN NaN NaN 6 7 NaN NaN NaN NaN NaN NaN NaN NaN 8 </code></pre>
0
2016-09-22T21:05:24Z
39,655,035
<p>Here is the code:</p> <pre><code>res = pd.DataFrame(index=df.index, columns=list('ABCDEFGH')) def classifier(row): cols = row.str.split().str[0].dropna().tolist() vals = row.str.split().str[1].dropna().tolist() res.loc[row.name, cols] = vals df.apply(classifier, axis=1) </code></pre> <hr> <p>Input:</p> <pre><code>from io import StringIO import pandas as pd import numpy as np data = """A 1, B 2, C 10, D 15 A 5, D 10, G 2 D 6, E 7 H 7, G 8""" df = pd.read_csv(StringIO(data), header=None) print("df:\n", df) res = pd.DataFrame(index=df.index, columns=list('ABCDEFGH')) def classifier(row): cols = row.str.split().str[0].dropna().tolist() vals = row.str.split().str[1].dropna().tolist() res.loc[row.name, cols] = vals df.apply(classifier, axis=1) print("\nres:\n", res) </code></pre> <p>Output:</p> <pre><code>df: 0 1 2 3 0 A 1 B 2 C 10 D 15 1 A 5 D 10 G 2 NaN 2 D 6 E 7 NaN NaN 3 H 7 G 8 NaN NaN res: A B C D E F G H 0 1 2 10 15 NaN NaN NaN NaN 1 5 NaN NaN 10 NaN NaN 2 NaN 2 NaN NaN NaN 6 7 NaN NaN NaN 3 NaN NaN NaN NaN NaN NaN 8 7 </code></pre>
0
2016-09-23T07:26:28Z
[ "python", "csv", "pandas" ]
Need to create a Pandas dataframe by reading csv file with random columns
39,648,855
<p>I have the following csv file with records:</p> <ul> <li>A 1, B 2, C 10, D 15</li> <li>A 5, D 10, G 2</li> <li>D 6, E 7</li> <li>H 7, G 8</li> </ul> <p>My column headers/names are: A, B, C, D, E, F, G</p> <p>So my initial dataframe after using "read_csv" becomes: </p> <pre><code>A B C D E F G A 1 B 2 C 10 D 15 NaN NaN NaN A 5 D 10 G 2 NaN NaN NaN NaN D 6 E 7 NaN NaN NaN NaN NaN H 7 G 8 NaN NaN NaN NaN Nan </code></pre> <p>The value can be separate into [column name][column value], so A 1 means col=A and value=1, and D 15 means col=D and value=15, etc...</p> <p>What I want is to assign the numeric value to the appropriate column based on the and have a dataframe that looks like this:</p> <pre><code>A B C D E F G A 1 B 2 C 10 D 15 NaN NaN NaN A 5 Nan NaN D 10 NaN NaN G 2 NaN NaN NaN D 6 E 7 NaN NaN NaN NaN NaN NaN NaN NaN G 8 </code></pre> <p>And even better, just the values alone:</p> <pre><code>A B C D E F G 1 2 10 15 NaN NaN NaN 5 Nan NaN 10 NaN NaN 2 NaN NaN NaN 6 7 NaN NaN NaN NaN NaN NaN NaN NaN 8 </code></pre>
0
2016-09-22T21:05:24Z
39,656,046
<p><strong>Apply</strong> solution:</p> <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.split.html" rel="nofollow"><code>split</code></a> by whitespace, remove <code>NaN</code> rows by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.dropna.html" rel="nofollow"><code>dropna</code></a>, <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="nofollow"><code>set_index</code></a> and convert one column <code>DataFrame</code> to <code>Series</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.squeeze.html" rel="nofollow"><code>DataFrame.squeeze</code></a>. Last <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reindex.html" rel="nofollow"><code>reindex</code></a> by new column names:</p> <pre><code>print (df.apply(lambda x: x.str.split(expand=True) .dropna() .set_index(0) .squeeze(), axis=1) .reindex(columns=list('ABCDEFGH'))) A B C D E F G H 0 1 2 10 15 NaN NaN NaN NaN 1 5 NaN NaN 10 NaN NaN 2 NaN 2 NaN NaN NaN 6 7 NaN NaN NaN 3 NaN NaN NaN NaN NaN NaN 8 7 </code></pre> <p><strong>Stack</strong> solution:</p> <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.html" rel="nofollow"><code>stack</code></a> for creating <code>Series</code>, <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.split.html" rel="nofollow"><code>split</code></a> by whitespace and create new columns, append column with new column names (<code>A</code>, <code>B</code>...) to <code>index</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="nofollow"><code>set_index</code></a>, convert one column <code>DataFrame</code> to <code>Series</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.squeeze.html" rel="nofollow"><code>DataFrame.squeeze</code></a>, remove index values with old column names by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html" rel="nofollow"><code>reset_index</code></a>, <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.unstack.html" rel="nofollow"><code>unstack</code></a>, <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reindex.html" rel="nofollow"><code>reindex</code></a> by new column names (it add missing columns filled by <code>NaN</code>),convert values to <code>float</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.astype.html" rel="nofollow"><code>astype</code></a> and last remove column name by <a href="http://pandas.pydata.org/pandas-docs/stable/whatsnew.html#changes-to-rename" rel="nofollow"><code>rename_axis</code></a> (new in <code>pandas</code> <code>0.18.0</code>):</p> <pre><code>print (df.stack() .str.split(expand=True) .set_index(0, append=True) .squeeze() .reset_index(level=1, drop=True) .unstack() .reindex(columns=list('ABCDEFGH')) .astype(float) .rename_axis(None, axis=1)) A B C D E F G H 0 1.0 2.0 10.0 15.0 NaN NaN NaN NaN 1 5.0 NaN NaN 10.0 NaN NaN 2.0 NaN 2 NaN NaN NaN 6.0 7.0 NaN NaN NaN 3 NaN NaN NaN NaN NaN NaN 8.0 7.0 </code></pre>
1
2016-09-23T08:22:23Z
[ "python", "csv", "pandas" ]
How do I make all the docstring using triple double quotes instead of triple single quotes?
39,648,917
<p>I have a long source code in python, and many functions are documented with <code>'''xxx'''</code>, How do I replace them with <code>"""xxx"""</code> quickly? in any text editor ? pycharm / sublime </p> <pre><code>def my_func(): ''' yeah a doc string ''' pass </code></pre> <p>desired result:</p> <pre><code>def my_func(): """ yeah a doc string """ pass </code></pre> <p>edit: Found the solution in pycharm ( or every other text editor) search for <code>'''(\n.*\n\s*)'''\n</code> and replace with <code>"""$1"""\n</code></p> <p>ps: I can not just do a simple search for <code>'''</code>,and replace it with <code>"""</code>, because in the code multi line strings are everywhere, not just in the docstring.</p>
-2
2016-09-22T21:10:12Z
39,648,950
<p>In vi:</p> <pre><code>:%s/'''/"""/g *&lt;return&gt;* </code></pre>
0
2016-09-22T21:12:22Z
[ "python", "pycharm", "sublimetext", "docstring" ]
How do I make all the docstring using triple double quotes instead of triple single quotes?
39,648,917
<p>I have a long source code in python, and many functions are documented with <code>'''xxx'''</code>, How do I replace them with <code>"""xxx"""</code> quickly? in any text editor ? pycharm / sublime </p> <pre><code>def my_func(): ''' yeah a doc string ''' pass </code></pre> <p>desired result:</p> <pre><code>def my_func(): """ yeah a doc string """ pass </code></pre> <p>edit: Found the solution in pycharm ( or every other text editor) search for <code>'''(\n.*\n\s*)'''\n</code> and replace with <code>"""$1"""\n</code></p> <p>ps: I can not just do a simple search for <code>'''</code>,and replace it with <code>"""</code>, because in the code multi line strings are everywhere, not just in the docstring.</p>
-2
2016-09-22T21:10:12Z
39,649,081
<pre><code>python -c "import sys;with open(sys.argv[1],'rb') as f: tmp = f.read();with open(sys.argv[1],'wb') as f:f.write(tmp.replace(\"'''\",'\"\"\"')" </code></pre>
0
2016-09-22T21:22:12Z
[ "python", "pycharm", "sublimetext", "docstring" ]
How do I make all the docstring using triple double quotes instead of triple single quotes?
39,648,917
<p>I have a long source code in python, and many functions are documented with <code>'''xxx'''</code>, How do I replace them with <code>"""xxx"""</code> quickly? in any text editor ? pycharm / sublime </p> <pre><code>def my_func(): ''' yeah a doc string ''' pass </code></pre> <p>desired result:</p> <pre><code>def my_func(): """ yeah a doc string """ pass </code></pre> <p>edit: Found the solution in pycharm ( or every other text editor) search for <code>'''(\n.*\n\s*)'''\n</code> and replace with <code>"""$1"""\n</code></p> <p>ps: I can not just do a simple search for <code>'''</code>,and replace it with <code>"""</code>, because in the code multi line strings are everywhere, not just in the docstring.</p>
-2
2016-09-22T21:10:12Z
39,649,126
<p>Turning my comment into an asnwer. Regular expressions are your friend if you have lots of files. From a GNU/Linux terminal, you can write:</p> <pre><code>find path/to/dir -name '*.py' -exec perl -p -i -e \'s/'''/"""/g\' {} \; </code></pre>
0
2016-09-22T21:25:49Z
[ "python", "pycharm", "sublimetext", "docstring" ]
How do I make all the docstring using triple double quotes instead of triple single quotes?
39,648,917
<p>I have a long source code in python, and many functions are documented with <code>'''xxx'''</code>, How do I replace them with <code>"""xxx"""</code> quickly? in any text editor ? pycharm / sublime </p> <pre><code>def my_func(): ''' yeah a doc string ''' pass </code></pre> <p>desired result:</p> <pre><code>def my_func(): """ yeah a doc string """ pass </code></pre> <p>edit: Found the solution in pycharm ( or every other text editor) search for <code>'''(\n.*\n\s*)'''\n</code> and replace with <code>"""$1"""\n</code></p> <p>ps: I can not just do a simple search for <code>'''</code>,and replace it with <code>"""</code>, because in the code multi line strings are everywhere, not just in the docstring.</p>
-2
2016-09-22T21:10:12Z
39,654,982
<p>You can achieve it by three methods,</p> <h3>Method 1: Inspect whole project</h3> <p>Go to <code>Code &gt; Inspect Code</code>. PyCharm will scan your code (this may take some time) and will show you the inspection results.</p> <p>In the inspection results, under Python It will show <code>Single Quoted docstrings</code> <a href="http://i.stack.imgur.com/FDA0d.png" rel="nofollow"><img src="http://i.stack.imgur.com/FDA0d.png" alt="enter image description here"></a></p> <ol> <li><p><strong>To change all the files at once</strong> <br> Select <code>Single quoted docstring</code> from the left pane and click <code>Convert docstring to the triple double quoted string form</code>. Now all the files will be changed to triple double quotes.</p></li> <li><p><strong>To change for individual files</strong> <br> Select individual files under <code>Single quoted docstring</code> and for each file click <code>Convert docstring to the triple double quoted string form</code>.</p></li> </ol> <h3>Method 2: Replace Code with <code>Replace in Path</code></h3> <p>In PyCharm, right click on the project and select <strong><code>Replace in Path</code></strong> or <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>R</kbd>. <a href="http://i.stack.imgur.com/7h93g.png" rel="nofollow"><img src="http://i.stack.imgur.com/7h93g.png" alt="enter image description here"></a> <a href="http://i.stack.imgur.com/U823M.png" rel="nofollow"><img src="http://i.stack.imgur.com/U823M.png" alt="enter image description here"></a></p> <p>In the <code>Text to find</code> field, enter <code>'''</code> and in <code>Replace with</code> field, enter <code>"""</code>. click find. PyCharm will scan through the files and ask you whether to replace single occurrence, or all occurences at once.</p> <h3>Method 3: Use terminal tools or Python to read lines and replace.</h3> <p>As others mentioned, this method will do the job.</p> <blockquote> <p><strong>I recommend method 1</strong> Since PyCharm is intelligent, it can change doctrings without changing multi-line strings (if you are using it) which is prone to replacement in other methods.</p> </blockquote>
0
2016-09-23T07:23:30Z
[ "python", "pycharm", "sublimetext", "docstring" ]
Pandas dataframe pivot - Memory Error
39,648,991
<p>I have a dataframe <code>df</code> with the following structure:</p> <pre><code> val newidx Code Idx 0 1.0 1220121127 706 1 1.0 1220121030 706 2 1.0 1620120122 565 </code></pre> <p>It has 1000000 lines. In total we have 600 unique <code>Code</code> value and 200000 unique <code>newidx</code> values.</p> <p>If I perform the following operation</p> <pre><code>df.pivot_table(values='val', index='newidx', columns='Code', aggfunc='max') </code></pre> <p>I get a <code>MemoryError</code> . but this sounds strange as the size of the resulting dataframe should be sustainable: 200000x600.</p> <p>How much memory requires such operation? Is there a way to fix this memory error?</p>
0
2016-09-22T21:14:24Z
39,654,124
<p>Try to see if this fits in your memory:</p> <pre><code>df.groupby(['newidx', 'Code'])['val'].max().unstack() </code></pre> <p><code>pivot_table</code> is unfortunately very memory intensive as it may make multiple copies of data.</p> <hr> <p>If the <code>groupby</code> does not work, you will have to split your DataFrame into smaller pieces. Try not to assign multiple times. For example, if reading from csv:</p> <pre><code>df = pd.read_csv('file.csv').groupby(['newidx', 'Code'])['val'].max().unstack() </code></pre> <p>avoids multiple assignments.</p>
1
2016-09-23T06:37:05Z
[ "python", "pandas", "dataframe" ]
Pandas dataframe pivot - Memory Error
39,648,991
<p>I have a dataframe <code>df</code> with the following structure:</p> <pre><code> val newidx Code Idx 0 1.0 1220121127 706 1 1.0 1220121030 706 2 1.0 1620120122 565 </code></pre> <p>It has 1000000 lines. In total we have 600 unique <code>Code</code> value and 200000 unique <code>newidx</code> values.</p> <p>If I perform the following operation</p> <pre><code>df.pivot_table(values='val', index='newidx', columns='Code', aggfunc='max') </code></pre> <p>I get a <code>MemoryError</code> . but this sounds strange as the size of the resulting dataframe should be sustainable: 200000x600.</p> <p>How much memory requires such operation? Is there a way to fix this memory error?</p>
0
2016-09-22T21:14:24Z
39,656,318
<p>I've had a very similar problem when carrying out a merge between 4 dataframes recently.</p> <p>What worked for me was disabling the index during the groupby, then merging.</p> <p>if @Kartiks answer doesn't work, try this before chunking the DataFrame.</p> <pre><code>df.groupby(['newidx', 'Code'], as_index=False)['val'].max().unstack() </code></pre>
0
2016-09-23T08:35:56Z
[ "python", "pandas", "dataframe" ]
Importing csv file with line breaks to R or Python Pandas
39,649,218
<p>I have a csv file that includes line breaks within columns:</p> <pre><code>"id","comment","x" 1,"ABC\"xyz",123 2,"xyz\"abc",543 3,"abc xyz",483 </code></pre> <p>ID 3, for example contains such a line break.</p> <p>How can this be imported into python or R? Also, I don't mind if those line breaks were to be replaced by a space, for example.</p>
-1
2016-09-22T21:33:11Z
39,649,405
<p>Python has built-in CSV reader which handles that for you. See <a href="https://docs.python.org/2/library/csv.html" rel="nofollow">csv documentation</a>.</p> <pre><code>import csv with open(filename) as f: reader = csv.reader(f) csv_rows = list(reader) </code></pre>
1
2016-09-22T21:48:55Z
[ "python", "csv" ]
Importing csv file with line breaks to R or Python Pandas
39,649,218
<p>I have a csv file that includes line breaks within columns:</p> <pre><code>"id","comment","x" 1,"ABC\"xyz",123 2,"xyz\"abc",543 3,"abc xyz",483 </code></pre> <p>ID 3, for example contains such a line break.</p> <p>How can this be imported into python or R? Also, I don't mind if those line breaks were to be replaced by a space, for example.</p>
-1
2016-09-22T21:33:11Z
39,654,404
<p>the problem seemed to be not the line breaks, but rather the escaped upper quotes within the columns: <code>\"</code>.</p> <p>Python: zvone's answer worked fine!</p> <pre><code>import csv with open(filename) as f: reader = csv.reader(f) csv_rows = list(reader) </code></pre> <p>R: <code>readr::read_csv</code> worked without having to change any of the defaults.</p>
1
2016-09-23T06:53:04Z
[ "python", "csv" ]
Python - IOError: [Errno 13] Permission denied
39,649,225
<p>Im trying to get a local directory from argv and iterate through the folder and print the contents of each file within. However i am getting a [Errno] 13 saying permission denied. Ive tried researching the problem but have come up empty handed.</p> <pre><code>#!/usr/bin/python import os import sys path = open(sys.argv[1],'r') #'inputs/' path to working input dir file_list = os.listdir(path) #create list of filenames in path dir for fn in file_list: file = open(path+'/'+fn) #open each file in dir for manipulation for line in file: print(line) </code></pre>
-3
2016-09-22T21:33:42Z
39,649,610
<p><a href="https://docs.python.org/3/library/os.html#os.listdir" rel="nofollow"><code>os.listdir()</code></a>, as its name implies, returns a list of all occupants of the given directory, including both files and directories (and, if you're on Unix/Linux, other stuff like symlinks and devices and whatnot). You are then blindly trying to <a href="https://docs.python.org/3/library/functions.html#open" rel="nofollow"><code>open()</code></a> each item in the list and <code>print()</code> its contents. Unfortunately, <code>open()</code> only works on file-like objects, and specifically does <em>not</em> work on directories, hence Errno 13, Permission Denied.</p> <p>An alternative is to use <a href="https://docs.python.org/3/library/os.html#os.scandir" rel="nofollow"><code>os.scandir()</code></a>, which works a little bit differently. Instead of returning a flat list that you can read immediately, <code>os.scandir()</code> returns a <a href="http://stackoverflow.com/questions/1756096/understanding-generators-in-python">generator</a> which essentially gives you objects as you ask for them, instead of giving them all to you at once. In fact, the following code adapted from the docs is a good starting place for what you need:</p> <pre><code>for entry in os.scandir(path): if entry.is_file(): print(entry.name) </code></pre> <p><code>os.scandir()</code> is returning <a href="https://docs.python.org/3/library/os.html#os.DirEntry" rel="nofollow"><code>DirEntry</code></a> objects. Simply use <a href="https://docs.python.org/3/library/os.path.html#os.path.join" rel="nofollow"><code>os.path.join()</code></a> to create a full pathname out of the <code>path</code> argument you pass to <code>os.listdir()</code> in your original code, and <code>entry.name</code> from the code above, and then, using the <a href="https://docs.python.org/3/reference/compound_stmts.html#the-with-statement" rel="nofollow"><code>with</code></a> context manager, <code>open()</code> the file and display its contents:</p> <pre><code>for entry in os.scandir(path): if entry.is_file(): with open(os.path.join(path, entry), "r") as f: for line in f: print(line) </code></pre> <p>One of the advantages of using <code>with</code> is that you don't have to remember to close the file handle that is assigned when you use something like this:</p> <pre><code>f = open("myfile.txt, "r") # do stuff with f ... f.close() </code></pre> <p>Otherwise, you have a dangling file handle that <em>could</em> potentially cause problems, depending on how many there are and what you've done with them. It's just a good practice to <code>close()</code> what you <code>open()</code>. With <code>with</code>, you don't have to worry about it - the file handle is closed as soon as you exit the block.</p>
0
2016-09-22T22:07:31Z
[ "python" ]
How can I make my python binary converter pass these tests
39,649,370
<p>My python code is supposed to take decimal numbers from 0 to 255 as arguments and convert them to binary, return invalid when the parameter is less than 0 or greater than 255</p> <pre><code>def binary_converter(x): if (x &lt; 0) or (x &gt; 255): return "invalid input" try: return int(bin(x)[2:] except ValueError: pass </code></pre> <p>The Test</p> <pre><code>import unittest class BinaryConverterTestCases(unittest.TestCase): def test_conversion_one(self): result = binary_converter(0) self.assertEqual(result, '0', msg='Invalid conversion') def test_conversion_two(self): result = binary_converter(62) self.assertEqual(result, '111110', msg='Invalid conversion') def test_no_negative_numbers(self): result = binary_converter(-1) self.assertEqual(result, 'Invalid input', msg='Input below 0 not allowed') def test_no_numbers_above_255(self): result = binary_converter(300) self.assertEqual(result, 'Invalid input', msg='Input above 255 not allowed') </code></pre>
-3
2016-09-22T21:46:20Z
39,649,653
<p>You already know how to check the range of the input argument, and how to return values. Now it's a simple matter of returning what the assignment requires.</p> <p>In checking for valid input, all you've missed is to capitalize "Invalid". </p> <p>For legal conversions, you just need to pass back the binary representation without the leading "0b", which you've almost done (remove that integer conversion, as two commenters have already noted).</p>
0
2016-09-22T22:10:48Z
[ "python" ]
How can I make my python binary converter pass these tests
39,649,370
<p>My python code is supposed to take decimal numbers from 0 to 255 as arguments and convert them to binary, return invalid when the parameter is less than 0 or greater than 255</p> <pre><code>def binary_converter(x): if (x &lt; 0) or (x &gt; 255): return "invalid input" try: return int(bin(x)[2:] except ValueError: pass </code></pre> <p>The Test</p> <pre><code>import unittest class BinaryConverterTestCases(unittest.TestCase): def test_conversion_one(self): result = binary_converter(0) self.assertEqual(result, '0', msg='Invalid conversion') def test_conversion_two(self): result = binary_converter(62) self.assertEqual(result, '111110', msg='Invalid conversion') def test_no_negative_numbers(self): result = binary_converter(-1) self.assertEqual(result, 'Invalid input', msg='Input below 0 not allowed') def test_no_numbers_above_255(self): result = binary_converter(300) self.assertEqual(result, 'Invalid input', msg='Input above 255 not allowed') </code></pre>
-3
2016-09-22T21:46:20Z
39,650,117
<p>So this is the final working code</p> <pre><code>def binary_converter(x): if (x &lt; 0) or (x &gt; 255): return "Invalid input" try: return (bin(x)[2:]) except ValueError: pass </code></pre>
0
2016-09-22T22:59:29Z
[ "python" ]
Python codecs encoding not working
39,649,424
<p>I have this code</p> <pre><code>import collections import csv import sys import codecs from xml.dom.minidom import parse import xml.dom.minidom String = collections.namedtuple("String", ["tag", "text"]) def read_translations(filename): #Reads a csv file with rows made up of 2 columns: the string tag, and the translated tag with codecs.open(filename, "r", encoding='utf-8') as csvfile: csv_reader = csv.reader(csvfile, delimiter=",") result = [String(tag=row[0], text=row[1]) for row in csv_reader] return result </code></pre> <p>The CSV file I'm reading contains Brazilian portuguese characters. When I try to run this, I get an error: </p> <pre><code>'utf8' codec can't decode byte 0x88 in position 21: invalid start byte </code></pre> <p>I'm using Python 2.7. As you can see, I'm encoding with codecs, but it doesn't work. </p> <p>Any ideas?</p>
0
2016-09-22T21:50:42Z
39,649,777
<p>The idea of this line:</p> <pre><code>with codecs.open(filename, "r", encoding='utf-8') as csvfile: </code></pre> <p>is to say "This file was saved as utf-8. Please make appropriate conversions when reading from it."</p> <p>That works fine if the file was actually saved as utf-8. If some other encoding was used, then it is bad.</p> <p><strong>What then?</strong></p> <p>Determine which encoding was used. Assuming the information cannot be obtained from the software which created the file - guess.</p> <p>Open the file normally and print each line:</p> <pre><code>with open(filename, 'rt') as f: for line in f: print repr(line) </code></pre> <p>Then look for a character which is not ASCII, e.g. ñ - this letter will be printed as some code, e.g.:</p> <pre><code>'espa\xc3\xb1ol' </code></pre> <p>Above, ñ is represented as <code>\xc3\xb1</code>, because that is the utf-8 sequence for it.</p> <p>Now, you can check what various encodings would give and see which is right:</p> <pre><code>&gt;&gt;&gt; ntilde = u'\N{LATIN SMALL LETTER N WITH TILDE}' &gt;&gt;&gt; &gt;&gt;&gt; print repr(ntilde.encode('utf-8')) '\xc3\xb1' &gt;&gt;&gt; print repr(ntilde.encode('windows-1252')) '\xf1' &gt;&gt;&gt; print repr(ntilde.encode('iso-8859-1')) '\xf1' &gt;&gt;&gt; print repr(ntilde.encode('macroman')) '\x96' </code></pre> <p>Or print all of them:</p> <pre><code>for c in encodings.aliases.aliases: try: encoded = ntilde.encode(c) print c, repr(encoded) except: pass </code></pre> <p>Then, when you have guessed which encoding it is, use that, e.g.:</p> <pre><code>with codecs.open(filename, "r", encoding='iso-8859-1') as csvfile: </code></pre>
-1
2016-09-22T22:22:16Z
[ "python", "python-2.7" ]
Python - Multiprocessing changes socket's value
39,649,447
<p>I'm trying to program an MD5 decryptor which uses LAN to decrypt, and using all the available CPU on each PC. The client code:</p> <pre><code>import socket import multiprocessing as mp import select import re import hashlib import sys def decryptCall(list,text): rangeNums = int(list[1]) - int(list[0]) + 1 for i in range(len(list)): print my_socket print "ok" decrypt(list[i], int(list[i]) + rangeNums, text) #p = mp.Process(target=decrypt,args=(list[i], int(list[i]) + rangeNums, text)) #p.start() #processes.append(p) def end(): for p in processes: p.join() print my_socket print "goodbye" sys.exit() def decrypt(low,high,text): counter = int(low) high = int(high) while counter &lt;= high: m = hashlib.new('md5') m.update(str(counter)) if str(m.hexdigest()).lower() == str(text.lower()): print "final: " + str(counter) my_socket.send(str(counter)) end() counter+=1 if __name__ == "__main__": processes = [] dataList = [] q = mp.Queue() ADDR = ('127.0.0.1', 1337) my_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) my_socket.connect(ADDR) my_socket.send(str(mp.cpu_count())) while True: rlist, wlist, xlist = select.select([my_socket], [my_socket], []) for current_socket in rlist: data = current_socket.recv(1024) if not re.search('[a-zA-Z]', data): dataList.append(data) else: md5hash = data print md5hash print dataList print my_socket decryptCall(dataList,md5hash) </code></pre> <p>The server code:</p> <pre><code>import time import hashlib import socket import select import msvcrt import sys open_client_sockets=[] def decrypt(cpus2,text,): seperated = [] place = 0 low = 1000000 high = 9999999 numbers = high-low numbers /= cpus2 for g in range(cpus2): seperated.append(low + numbers*g) print open_client_sockets[0] for g in range(len(open_client_sockets)): print str(g) + ": " + str(cpus.get(open_client_sockets[g])) for h in range(int(cpus.get(open_client_sockets[g]))): time.sleep(0.01) open_client_sockets[g].send(str(seperated[place])) place+=1 open_client_sockets[g].send(text) test() def test(): print open_client_sockets[0].recv(10000) if __name__ == "__main__": md5hash2 = "fcea920f7412b5da7be0cf42b8c93759" messages_to_send=[] input = '' addresses = {} cpus = {} cpus_count=0 server_socket = socket.socket() server_socket.bind(('0.0.0.0', 1337)) server_socket.listen(5) while True: rlist, wlist, xlist = select.select( [server_socket] + open_client_sockets, open_client_sockets,[]) for current_socket in rlist: if current_socket is server_socket: (new_socket, address) = server_socket.accept() addresses[new_socket] = address open_client_sockets.append(new_socket) #print addresses else: data = current_socket.recv(1024) cpus_count += int(data) cpus[current_socket] = data if msvcrt.kbhit(): key = msvcrt.getch() sys.stdout.write(key) if key == '\r' and input != "": print "\nok" print cpus_count decrypt(cpus_count,md5hash2) input += key </code></pre> <p>The problem is, when I try to use multiprocessing:</p> <pre><code> decrypt(list[i], int(list[i]) + rangeNums, text) p = mp.Process(target=decrypt,args=(list[i], int(list[i]) + rangeNums, text)) p.start() processes.append(p) </code></pre> <p>The data isn't sent, because the socket's value changes. Example:</p> <pre><code>&lt;socket._socketobject object at 0x029CAB58&gt; -&gt; &lt;socket._socketobject object at 0x02941AE8&gt;. </code></pre> <p>While trying to figure it out, I noticed something weird. Every time the program creates a new process, the socket's value changes. When I use the normal call to function without multiprocessing, the socket stays as it is and the data is sent.</p>
0
2016-09-22T21:52:06Z
39,650,023
<p>I don't have a fully formed answer( I'd leave a comment if my reputation was higher). I believe what you are seeing is a result of trying to use a socket in a fork()d child that was established in a parent process (it's still open in the parent). In this case you're probably getting a copy of the parent. </p> <p>Some solutions: You could establish a new socket in the child.<br> You could close the connection in the parent right after fork (or process start in this case).</p> <p>For more reading lookup fork and socket, or multiprocessing and socket.</p>
1
2016-09-22T22:48:52Z
[ "python", "sockets", "encryption", "multiprocessing", "md5" ]
Python 3 Sockets - Receiving more then 1 character
39,649,551
<p>So when I open up the CMD and create a telnet connection with:</p> <p>telnet localhost 5555</p> <p>It will apear a "Welcome", as you can see on the screen below. After that every single character I type into the CMD will be printed out/send immediately. My Question is: Is it, and if yes, how is it possible to type in messages and then send them so I receive them as 1 sentence and not char by char. <a href="http://i.stack.imgur.com/kexib.png" rel="nofollow"><img src="http://i.stack.imgur.com/kexib.png" alt="enter image description here"></a></p> <pre><code>import socket import sys from _thread import * host = "" port = 5555 s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) try: s.bind((host,port)) except socket.error as e: print(str(e)) s.listen(5) #Enable a server to accept connections. print("Waiting for a connection...") def threaded_client(conn): conn.send(str.encode("Welcome\n")) while True: # for m in range (0,20): #Disconnects after x chars data = conn.recv(2048) #Receive data from the socket. reply = "Server output: "+ data.decode("utf-8") print(data) if not data: break conn.sendall(str.encode(reply)) conn.close() while True: conn, addr = s.accept() print("connected to: "+addr[0]+":"+str(addr[1])) start_new_thread(threaded_client,(conn,)) </code></pre>
0
2016-09-22T22:01:32Z
39,649,669
<p>You need to keep reading until the stream ends:</p> <pre><code>string = "" while True: # for m in range (0,20): #Disconnects after x chars data = conn.recv(1) #Receive data from the socket. if not data: reply = "Server output: "+ string conn.sendall(str.encode(reply)) break else: string += data.decode("utf-8") conn.close() </code></pre> <p>By the way, using that method you'll read one char at a time. You may adapt it to the way your server is sending the data.</p>
1
2016-09-22T22:12:03Z
[ "python", "sockets", "python-3.x" ]
Python 3 Sockets - Receiving more then 1 character
39,649,551
<p>So when I open up the CMD and create a telnet connection with:</p> <p>telnet localhost 5555</p> <p>It will apear a "Welcome", as you can see on the screen below. After that every single character I type into the CMD will be printed out/send immediately. My Question is: Is it, and if yes, how is it possible to type in messages and then send them so I receive them as 1 sentence and not char by char. <a href="http://i.stack.imgur.com/kexib.png" rel="nofollow"><img src="http://i.stack.imgur.com/kexib.png" alt="enter image description here"></a></p> <pre><code>import socket import sys from _thread import * host = "" port = 5555 s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) try: s.bind((host,port)) except socket.error as e: print(str(e)) s.listen(5) #Enable a server to accept connections. print("Waiting for a connection...") def threaded_client(conn): conn.send(str.encode("Welcome\n")) while True: # for m in range (0,20): #Disconnects after x chars data = conn.recv(2048) #Receive data from the socket. reply = "Server output: "+ data.decode("utf-8") print(data) if not data: break conn.sendall(str.encode(reply)) conn.close() while True: conn, addr = s.accept() print("connected to: "+addr[0]+":"+str(addr[1])) start_new_thread(threaded_client,(conn,)) </code></pre>
0
2016-09-22T22:01:32Z
39,649,684
<p>you could try something like: (pseudo code)</p> <pre><code>temp = conn.recv(2048) data.concatenate(temp) # maybe data = data + temp ???? little rusty if data[-1] == '\n': print 'message: ' + data etc... </code></pre>
0
2016-09-22T22:13:12Z
[ "python", "sockets", "python-3.x" ]