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)<...
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...
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)<...
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 ...
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
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 ...
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 ...
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...
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'...
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 ...
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.gr...
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]: d...
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.gr...
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'...
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.gr...
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.val...
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 ...
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): s...
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 ...
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 operation...
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 ...
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() ...
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 ...
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)) ...
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 ...
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)) ...
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 ...
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 t...
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 ...
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> <...
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 ...
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(outsi...
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; compil...
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 Si...
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 whe...
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 CC...
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><st...
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 De...
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</stron...
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;ipyth...
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 s...
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.pbkd...
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> <p...
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.s...
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>...
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>...
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 pa...
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> <...
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 = [(...
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> <...
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' ...
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.Fl...
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...
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 sou...
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 f...
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&g...
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 = {} #...
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&g...
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 No...
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,va...
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...
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...
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_o...
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()<...
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-0...
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.DataFra...
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;...
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 ...
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 ...
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) ...
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 ...
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((...
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.Straight...
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...
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 bott...
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...
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 al...
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 numb...
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="Figu...
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 po...
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 loo...
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-packag...
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...
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...
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...
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 =...
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...
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...
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...
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: ...
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...
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>I...
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 un...
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'].uns...
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...
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 o...
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 '0...
-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 '0...
-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>...
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 th...
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 righ...
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 </cod...
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 </cod...
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 goi...
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 </cod...
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 alm...
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.parametriz...
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-0...
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><cod...
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...
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 = datetim...
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 ...
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(...
-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={ ...
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 ran...
-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 o...
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>...
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. T...
-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>...
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...
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']....
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...
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/querie...
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)....
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 ...
-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.litera...
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 ...
-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...
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 ...
-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 = a...
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 ...
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> <pr...
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> <pr...
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...
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> <pr...
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;")...
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')...
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 Prog...
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 pytho...
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 Prog...
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 Prog...
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)) ...
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 Prog...
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>...
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 ...
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...
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 ...
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:<...
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 ...
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" r...
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> ...
-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> ...
-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> ...
-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> ...
-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...
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 ...
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 ...
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 ...
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)...
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 replac...
-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 replac...
-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</c...
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...
-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 the...
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:] ...
-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 repre...
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:] ...
-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 tran...
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, ...
-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 ...
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...
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...
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 els...
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...
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" ]