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
Find range of arguments that return the same result for a linear function
39,948,543
<p>Consider the <code>y = round(300000/x**2)</code>. I would like to find the ranges of <code>x</code> that return the same <code>y</code> for <code>100 &lt; x &lt; 40000</code>.</p> <p>How would I do that with python/numpy?</p>
2
2016-10-09T21:07:20Z
39,949,136
<p>First of all: the credit of this solution should go to <a href="http://stackoverflow.com/a/39948612/1029516">@CoryKramer</a>, even after the fix in the question.</p> <pre><code>from itertools import groupby groups = groupby(range(100, 40000), key=lambda x: round(300000/x**2)) </code></pre> <p>Anyway there is somet...
2
2016-10-09T22:21:38Z
[ "python", "numpy" ]
Non-blocking file read
39,948,588
<p>How can I read the contents of a binary or a text file in a non-blocking mode?</p> <p>For binary files: when I <code>open(filename, mode='rb')</code>, I get an instance of <code>io.BufferedReader</code>. The documentation fort <code>io.BufferedReader.read</code> <a href="https://docs.python.org/3.5/library/io.html#...
0
2016-10-09T21:12:11Z
39,948,643
<p>I suggest using aiofile. <a href="https://pypi.python.org/pypi/aiofiles/0.2.1" rel="nofollow">https://pypi.python.org/pypi/aiofiles/0.2.1</a></p> <pre><code>f = yield from aiofiles.open('filename', mode='r') try: contents = yield from f.read() finally: yield from f.close() print(contents) 'My file contents'...
-1
2016-10-09T21:19:28Z
[ "python", "python-3.x", "io" ]
Non-blocking file read
39,948,588
<p>How can I read the contents of a binary or a text file in a non-blocking mode?</p> <p>For binary files: when I <code>open(filename, mode='rb')</code>, I get an instance of <code>io.BufferedReader</code>. The documentation fort <code>io.BufferedReader.read</code> <a href="https://docs.python.org/3.5/library/io.html#...
0
2016-10-09T21:12:11Z
39,948,796
<p>File operations are blocking. There is no non-blocking mode.</p> <p>But you can create a thread which reads the file in the background. In Python 3, <a href="https://docs.python.org/3.4/library/concurrent.futures.html#module-concurrent.futures" rel="nofollow"><code>concurrent.futures</code> module</a> can be useful...
1
2016-10-09T21:36:18Z
[ "python", "python-3.x", "io" ]
One line python code to remove all the strings that doesn't start with T or t and if they contain number greater then 6
39,948,626
<p>Eg:</p> <pre><code>List=["tata1","tata2","Tata3","mdkjd","djhdj","Tata8","t9","t2"] </code></pre> <p>Output should be:<code>["tata1","tata2","Tata3","t2"]</code></p> <p>I tried :</p> <pre><code>content = [item for item in List if terminal.lower().startswith('t')] </code></pre> <p>My doubt if I can append one mo...
0
2016-10-09T21:18:05Z
39,948,666
<p>You can use <code>and</code> to test multiple conditions.</p> <pre><code>&gt;&gt;&gt; [i for i in l if i and i[0] in 'tT' and all(j not in i for j in '789')] ['tata1', 'tata2', 'Tata3', 't2'] </code></pre> <p>So from left to right this will test:</p> <ul> <li>non empty string</li> <li>starts with <code>'t</code>'...
2
2016-10-09T21:21:09Z
[ "python", "python-2.7", "python-3.x", "for-loop", "filter" ]
One line python code to remove all the strings that doesn't start with T or t and if they contain number greater then 6
39,948,626
<p>Eg:</p> <pre><code>List=["tata1","tata2","Tata3","mdkjd","djhdj","Tata8","t9","t2"] </code></pre> <p>Output should be:<code>["tata1","tata2","Tata3","t2"]</code></p> <p>I tried :</p> <pre><code>content = [item for item in List if terminal.lower().startswith('t')] </code></pre> <p>My doubt if I can append one mo...
0
2016-10-09T21:18:05Z
39,948,731
<p>Matching your required output requires using <code>all</code> and <code>not in</code> to check that none of the <code>'789'</code> characters are contained in your input string while also checking for the starting characters:</p> <pre><code>res = [s for s in List if s[0] in ('tT') and all(j not in s for j in '789')...
0
2016-10-09T21:28:38Z
[ "python", "python-2.7", "python-3.x", "for-loop", "filter" ]
One line python code to remove all the strings that doesn't start with T or t and if they contain number greater then 6
39,948,626
<p>Eg:</p> <pre><code>List=["tata1","tata2","Tata3","mdkjd","djhdj","Tata8","t9","t2"] </code></pre> <p>Output should be:<code>["tata1","tata2","Tata3","t2"]</code></p> <p>I tried :</p> <pre><code>content = [item for item in List if terminal.lower().startswith('t')] </code></pre> <p>My doubt if I can append one mo...
0
2016-10-09T21:18:05Z
39,950,542
<pre><code>import re print filter(lambda x: re.match(r'^[Tt].*[0-6]',x),l) </code></pre>
0
2016-10-10T02:29:31Z
[ "python", "python-2.7", "python-3.x", "for-loop", "filter" ]
What does the star in the field_name input mean in the Python str.format() docs?
39,948,673
<p>In "6.1.3. Format String Syntax" in the Python 3.5.2 docs, the <code>field_name</code> for the replacement field grammar for <code>str.format()</code> is written like this:</p> <pre><code>field_name ::= arg_name ("." attribute_name | "[" element_index "]")* </code></pre> <p>What does the star at the very r...
0
2016-10-09T21:21:41Z
39,948,891
<p><a href="https://docs.python.org/3/reference/introduction.html#notation" rel="nofollow">Python Language Reference, section 1.2.</a> says:</p> <blockquote> <p>The descriptions of lexical analysis and syntax use a modified BNF grammar notation. This uses the following style of definition:</p> <pre><code>name ...
1
2016-10-09T21:48:37Z
[ "python", "documentation" ]
Django Template - Cannot iterate throught this list
39,948,719
<p>I am passing this object to my template from my view with the name <code>student_collection</code></p> <pre><code>&lt;class 'list'&gt;: [[31, 'John', ‘Jacob', '1'], [31, 'Jeffrey', ‘Mark', '2'], [39, ‘Borris', ‘Hammer', '1']] </code></pre> <p>And accessing it as such in my template:</p> <pre><code>{% for ...
1
2016-10-09T21:27:23Z
39,948,755
<blockquote> <p>I was expecting to iterate through <code>31,John,Jacob,1</code></p> </blockquote> <p>Then you wouldn't need that second inner loop. The first loop gives you each sublist/row in the list of rows, while the inner loop iterates through each row, producing each of the items/entries:</p> <pre><code>{% fo...
2
2016-10-09T21:31:29Z
[ "python", "django" ]
Reading and Wrtiting Fifo Files between C and Python
39,948,721
<p>In general, I am creating two fifo queues to be read and written to by my .c and .py programs. To enable my .c program to interact with python, I have included the <code>&lt;python2.7/Python.h&gt;</code> library. </p> <p>Firstly, my .c program creates a file called CFifo and writes text to it using fprintf. No prob...
0
2016-10-09T21:27:31Z
39,949,691
<p>You can't get there from here. From the <code>mkfifo</code> man page...</p> <blockquote> <p>Once you have created a FIFO special file in this way, any process can open it for reading or writing, in the same way as an ordinary file. However, it has to be open at both ends simultaneously before you can ...
1
2016-10-09T23:50:50Z
[ "python", "c", "file-io", "fifo" ]
How to fix django send mail?
39,948,749
<p>I'm trying to send mail in django project for several days.I've got documentation from djangoproject.com, but that's not working for me. my settings.py contains these lines of code for sending mail:</p> <pre><code>EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_PASSWORD = '*********...
0
2016-10-09T21:30:47Z
39,950,691
<p>Here is an implementation for gmail using standard <code>email</code> and <code>smtplib</code> packages (note different port and host in settings):</p> <pre><code>//settings.py EMAIL_HOST = 'smtp.googlemail.com' #XXX EMAIL_PORT = 465 #XXX EMAIL_HOST_PASSWORD = '**********' EMAIL_HOST_USER = '***@...
0
2016-10-10T02:53:05Z
[ "python", "django", "email" ]
Is there any way to take the user's input in one variable and use that input in another variable?
39,948,754
<p>Is there any way to take the user's input in one variable and use that input in another variable?</p> <p>For example:</p> <pre><code>def user_input(): numb = input("Please input the number ") numb_process() def numb_process(): if numb == '1': print("Good") else: print("Bad") user_...
-5
2016-10-09T21:31:28Z
39,948,823
<p>This is python 101 and the standard <a href="https://docs.python.org/3/tutorial/index.html" rel="nofollow">python tutorial</a> is a good place to learn basic concepts. In your case, simple parameter passing will do.</p> <pre><code>def user_input(): numb = input("Input number ") # bind result of the input functi...
2
2016-10-09T21:38:41Z
[ "python", "python-3.x" ]
Is there any way to take the user's input in one variable and use that input in another variable?
39,948,754
<p>Is there any way to take the user's input in one variable and use that input in another variable?</p> <p>For example:</p> <pre><code>def user_input(): numb = input("Please input the number ") numb_process() def numb_process(): if numb == '1': print("Good") else: print("Bad") user_...
-5
2016-10-09T21:31:28Z
39,948,829
<p>It should work. You can call the numb_process function by giving it an argument "numb" that will move from the function "user_input" to function "numb_process".</p> <pre><code>def user_input(): numb = input("Please input the number ") numb_process(numb) def numb_process(numb): if numb == '1': p...
0
2016-10-09T21:40:12Z
[ "python", "python-3.x" ]
How to delete rows in python pandas DataFrame using regular expressions?
39,948,757
<p>I have a pattern:</p> <pre><code>patternDel = "( \\((MoM|QoQ)\\))"; </code></pre> <p>And I want to delete all rows in pandas dataframe where column <code>df['Event Name']</code> matches this pattern. Which is the best way to do it? There are more than 100k rows in dataframe.</p>
0
2016-10-09T21:31:40Z
39,949,288
<p><a href="http://pandas.pydata.org/pandas-docs/version/0.18.1/generated/pandas.Series.str.contains.html" rel="nofollow">str.contains()</a> returns a Series of booleans that we can use to index our frame</p> <pre><code>patternDel = "( \\((MoM|QoQ)\\))" filter = df['Event Name'].str.contains(patternDel) </code></pre> ...
1
2016-10-09T22:44:42Z
[ "python", "regex", "pandas" ]
How to generate all possible combinations of 0-1 matrix in Python?
39,948,902
<p>How can generate all possible combinations of a 0-1 matrix of size K by N?</p> <p>For example, if I take K=2 and N=2, I get the following combinations.</p> <pre><code>combination 1 [0, 0; 0, 0]; combination 2 [1, 0; 0, 0]; combination 3 [0, 1; 0, 0]; combination 4 [0, 0; 1, 0]; combination 5 [0, 0; 0, 1];...
3
2016-10-09T21:49:24Z
39,948,977
<p>A one-liner solution with <code>numpy</code> and <code>itertools</code>:</p> <pre><code>[np.reshape(np.array(i), (K, N)) for i in itertools.product([0, 1], repeat = K*N)] </code></pre> <p><em>Explanation:</em> the <code>product</code> function returns a Cartesian product of its input. For instance, <code>product([...
4
2016-10-09T22:01:02Z
[ "python", "combinations" ]
How to generate all possible combinations of 0-1 matrix in Python?
39,948,902
<p>How can generate all possible combinations of a 0-1 matrix of size K by N?</p> <p>For example, if I take K=2 and N=2, I get the following combinations.</p> <pre><code>combination 1 [0, 0; 0, 0]; combination 2 [1, 0; 0, 0]; combination 3 [0, 1; 0, 0]; combination 4 [0, 0; 1, 0]; combination 5 [0, 0; 0, 1];...
3
2016-10-09T21:49:24Z
39,949,551
<p>An alternative approach to using <code>itertools.product</code> that is faster:</p> <pre><code>def using_shifts(K, N): shifter = numpy.arange(K*N).reshape( (K, N) ) return [(x &gt;&gt; shifter) % 2 for x in range(2 ** (K*N))] </code></pre> <p>How does this work? We are exploiting that each desired array o...
2
2016-10-09T23:26:03Z
[ "python", "combinations" ]
'AttributeError:' when I try to unpickle dictionary
39,948,903
<p>I have made a program on python 3.5 which you can find out the password linked to a username, make a new password for an existing user and add a new user and password to the dictionary then pickles it so every time I load the program all the usernames and passwords will be there.</p> <p>The error that comes up is a...
0
2016-10-09T21:49:31Z
39,949,156
<p>When you do this</p> <pre><code>LOGG[NewUser] = (NewPass) </code></pre> <p>You are assigning the function <code>NewPass</code> to your dict entry. You are probably intending to assign the password string and therefore it should be.</p> <pre><code>LOGG[NewUser] = Newpass </code></pre> <p>Note: Parenthesis are sup...
2
2016-10-09T22:24:00Z
[ "python", "python-3.x", "dictionary", "pickle" ]
Multiplying pandas dataframe and series, element wise
39,948,935
<p>Lets say I have a pandas series:</p> <pre><code>import pandas as pd x = pd.DataFrame({0: [1,2,3], 1: [4,5,6], 2: [7,8,9] }) y = pd.Series([-1, 1, -1]) </code></pre> <p>I want to multiply x and y in such a way that I get z:</p> <pre><code>z = pd.DataFrame({0: [-1,2,-3], 1: [-4,5,-6], 2: [-7,8,-9] }) </code></pre> ...
0
2016-10-09T21:54:19Z
39,949,068
<p>You can do that:</p> <pre><code>&gt;&gt;&gt; new_x = x.mul(y, axis=0) &gt;&gt;&gt; new_x 0 1 2 0 -1 -4 -7 1 2 5 8 2 -3 -6 -9 </code></pre>
3
2016-10-09T22:12:41Z
[ "python", "pandas" ]
Multiplying pandas dataframe and series, element wise
39,948,935
<p>Lets say I have a pandas series:</p> <pre><code>import pandas as pd x = pd.DataFrame({0: [1,2,3], 1: [4,5,6], 2: [7,8,9] }) y = pd.Series([-1, 1, -1]) </code></pre> <p>I want to multiply x and y in such a way that I get z:</p> <pre><code>z = pd.DataFrame({0: [-1,2,-3], 1: [-4,5,-6], 2: [-7,8,-9] }) </code></pre> ...
0
2016-10-09T21:54:19Z
39,949,077
<p>As Abdou points out, the answer is </p> <pre><code>z = x.apply(lambda col: col*y) </code></pre> <p>Moreover, if you instead have a DataFrame, e.g. </p> <pre><code> y = pandas.DataFrame({"colname": [1,-1,-1]}) </code></pre> <p>Then you can do </p> <pre><code> z = x.apply(lambda z: z*y["colname"]) </code></pre>
1
2016-10-09T22:13:36Z
[ "python", "pandas" ]
Multiplying pandas dataframe and series, element wise
39,948,935
<p>Lets say I have a pandas series:</p> <pre><code>import pandas as pd x = pd.DataFrame({0: [1,2,3], 1: [4,5,6], 2: [7,8,9] }) y = pd.Series([-1, 1, -1]) </code></pre> <p>I want to multiply x and y in such a way that I get z:</p> <pre><code>z = pd.DataFrame({0: [-1,2,-3], 1: [-4,5,-6], 2: [-7,8,-9] }) </code></pre> ...
0
2016-10-09T21:54:19Z
39,949,089
<p>You can multiply the dataframes directly.</p> <pre><code>x * y </code></pre>
0
2016-10-09T22:15:43Z
[ "python", "pandas" ]
Python : Hash extension attack in python
39,949,030
<p>I want to use h to generate the same md5 as b</p> <p>Here is the code:</p> <pre><code>k = "secret" m = "show me the grade" m2 = "show me the grade and change it to 100" x = " and change it to 100" a = md5(k + m) b = md5(k + m2) print "have---&gt; " + a.hexdigest() #9f4bb32ac843d6db979ababa2949cb52 print "want---&g...
0
2016-10-09T22:09:05Z
39,949,464
<p>This is because the hash you expected (aba1..) is the md5 hash of <code>k + m + x</code> while the hash you got (958a..) is the md5 hash of <code>k + m + padding + x</code>.</p> <p>The length extension attack lets you generate a hash <code>h2 = md5(k + m + padding + x)</code> based on only knowing the hash <code>h1...
0
2016-10-09T23:12:54Z
[ "python", "md5" ]
Python function to create an array of particular column of csv file
39,949,206
<p>I need to write a function that, given a CSV file name as a string and a column number, will create an array with the distinct values in that particular column of the file. Assuming my first column is 0 just like in Python lists. This file also has a header and footer row.</p> <pre><code>import csv def facet(file,...
-1
2016-10-09T22:32:26Z
40,127,840
<p>Try the following:</p> <pre><code>import csv def facet(file, column): with open(file, newline='') as f_input: return [row[column] for row in csv.reader(f_input)][1:-1] print(facet('input.csv', 1)) </code></pre> <p>The reads the file as a <code>csv</code> and uses a list comprehension to select only o...
0
2016-10-19T09:49:23Z
[ "python", "arrays", "python-3.x", "csv" ]
Pandas reading from csv file and filling missing values for datetime index
39,949,432
<p>I have data in a csv file which appears as:</p> <pre><code> DateTime Temp 10/1/2016 0:00 20.35491156 10/1/2016 1:00 19.75320845 10/1/2016 4:00 17.62411292 10/1/2016 5:00 18.30190001 10/1/2016 6:00 19.37101638 </code></pre> <p>I am reading this file into csv file as:</p> <pre><code>import numpy as np i...
0
2016-10-09T23:08:09Z
39,949,714
<pre><code>import pandas as pd data = pd.read_csv(r'Curve.csv', index_col='DateTime', parse_dates=['DateTime']) data = data.asfreq('1H', method='ffill') </code></pre> <p>yields</p> <pre><code> Temp DateTime 2016-10-01 00:00:00 20.354912 2016-10-01 01:00:00 19.753208 20...
3
2016-10-09T23:55:02Z
[ "python", "pandas" ]
Specifying custom nested objects in Django Rest Framework ModelSerializer
39,949,434
<p>I have lat, long specified in my DB as:</p> <pre><code>... lat = models.DecimalField(_('Latitude'), max_digits=8, decimal_places=5, null=True, blank=True) lng = models.DecimalField(_('Longitude'), max_digits=8, decimal_places=5, null=True, blank=True) ... </code></pre> <p>I want my ModalSerialization to come out a...
-1
2016-10-09T23:08:49Z
39,950,486
<p>One of the way is you can create a property in a model like below.</p> <pre><code>@property def location_info(self): return dict( lat=self.lat, lng=self.lng ) </code></pre> <p>Then you can create a dict field in your serializer and specify source as your property. Since it is property it ca...
1
2016-10-10T02:19:58Z
[ "python", "django", "django-rest-framework" ]
Flask G variable Simple example
39,949,455
<p>From what i understand a g variable is a temporary storage that last form one single request to the other. For example i was thinking it should work like this. But i can seem to get it to work.</p> <pre><code>from flask import Flask, g, redirect, url_for app = Flask(__name__) @app.route('/') def hello_...
-1
2016-10-09T23:12:03Z
39,955,536
<p>Flask <code>g</code> is available in application context and lasts for the lifetime of the request.</p> <p><code>What is application context?</code></p> <p>As cited on <a href="http://flask.pocoo.org/docs/0.11/appcontext/" rel="nofollow">Application Context Page</a>, flask app is in many states while being execute...
3
2016-10-10T09:45:52Z
[ "python", "flask" ]
Capturing all operators, parentheses and numbers separately in "(3 + 44)* 5 / 7" with Regex
39,949,497
<p>For input string: <code>st = "(3 + 44)* 5 / 7"</code></p> <p>I'm looking to get the following result using only regex: <code>["(", "3", "+", "44", ")", "*", "5", "/", "7"]</code></p> <p>Attempts:</p> <ol> <li><pre><code>&gt;&gt;&gt; re.findall("[()\d+\-*/].?", st) ['(3', '+ ', '44', ')*', '5 ', '/ ', '7'] </code>...
2
2016-10-09T23:18:46Z
39,949,523
<p>You can't use multi-character constructs like <code>\d+</code> in a character class.</p> <p>So you can do it by brute force like this:</p> <pre><code>re.findall(r"\(|\)|\d+|-|\*|/", st) </code></pre> <p>Or you can use a character class for single-character tokens, alternated with other things:</p> <pre><code>re....
3
2016-10-09T23:22:02Z
[ "python", "regex", "tokenize" ]
In Python 2, How to raise a Python error without changing its traceback?
39,949,525
<p>In the following typical try-except block:</p> <pre><code>try: do something except Exception as e: {clean up resources} raise e ^ </code></pre> <p>However, this will print out an error message with traceback pointing to ^, where the error is raised, in contrast to most other languages, where ...
0
2016-10-09T23:22:34Z
39,949,830
<p>To catch an exception, do something with it and then re-raise the same exception:</p> <pre><code>try: do something except Exception as e: {clean up resources} raise # raises the same exception with the same traceback </code></pre> <p>To catch an exception, raise a new exception, but keep the old trac...
3
2016-10-10T00:16:03Z
[ "python", "exception", "exception-handling" ]
How do I suppress printing under certain circumstances in python?
39,949,527
<p>I have written following code in python for a simulation of an ATM:</p> <pre><code>withd = int(input("How much do you want to withdraw? ")) # Withdrawal shown to customer print("Withdrawal: ", withd, " CHF") # 100 bills a = withd // 100 a_rest = withd % 100 # 50 bills b = a_rest // 50 b_rest = a_rest % 50 # 20 ...
-1
2016-10-09T23:22:43Z
39,949,607
<p>The solution is obviously to check <code>if a&gt;0:</code>, <code>if b&gt;0:</code> and so on. But what about throwing in a loop, so you don't have to hardcode the conditions for all the bills?</p> <pre><code>withd = int(input("How much do you want to withdraw? ")) # Withdrawal shown to customer print("Withdrawal:...
0
2016-10-09T23:34:32Z
[ "python" ]
Extracting a data from dictionary in python
39,949,545
<pre><code>list1 = ["a","c","d"] dict1 = {"a":9, "b":2, "c":5, "d":9, "e":6, "f":7 } </code></pre> <p>I want to get only list1's word from dict1.</p> <p>The following is the result I want to get.</p> <pre><code>{"a":9, "c":5, "d":9} </code></pre> <p>What am I supposed to do?</p>
-1
2016-10-09T23:25:22Z
39,949,562
<p>You can use a <em>dictionary comprehension</em> to do this:</p> <pre><code>&gt;&gt;&gt; list1 = ["a","c","d"] &gt;&gt;&gt; dict1 = {"a":9, "b":2, "c":5, "d":9, "e":6, "f":7 } &gt;&gt;&gt; {k: dict1[k] for k in list1} {'c': 5, 'd': 9, 'a': 9} </code></pre> <p>This works as long as the dictionary keys contains all t...
4
2016-10-09T23:27:19Z
[ "python", "list", "dictionary" ]
Can Python "os.environ.get" ever return a non-string?
39,949,587
<p>In this code <a href="https://github.com/chimpler/pyhocon/blob/master/pyhocon/config_parser.py#L291" rel="nofollow">here</a>, they use <code>os.environ</code> to get the value of an environment variable, and then immediately check to see if it is an instance of their custom classes.</p> <pre><code>value = os.enviro...
0
2016-10-09T23:31:04Z
39,949,644
<p>Anything that comes from the <em>outside</em> will be just a string, I guess.</p> <p>On the other hand if you are adding something to the environment from the Python code, then you have just a bit more freedom.</p> <p>Adding anything but a string still fails:</p> <pre><code>&gt;&gt;&gt; os.environ['a'] = 89 Trace...
1
2016-10-09T23:41:44Z
[ "python", "environment-variables" ]
Can Python "os.environ.get" ever return a non-string?
39,949,587
<p>In this code <a href="https://github.com/chimpler/pyhocon/blob/master/pyhocon/config_parser.py#L291" rel="nofollow">here</a>, they use <code>os.environ</code> to get the value of an environment variable, and then immediately check to see if it is an instance of their custom classes.</p> <pre><code>value = os.enviro...
0
2016-10-09T23:31:04Z
39,949,658
<p>The <code>os.environ</code> is just a simple mapping of <code>name: value</code>. It just adds some flavour on top of a dict to interact with the environment. Environment variables do not have type - their plain strings.</p> <p>You can set variable types in bash, but this is not passed on to other programs.</p> <p...
0
2016-10-09T23:43:37Z
[ "python", "environment-variables" ]
pandas read_csv create columns based on value in one of the csv columns
39,949,597
<p>I have csv data that looks like this:</p> <pre><code>1471361094509,doorLowerPosition,-73.3348875 1471361094509,doorUpperPosition,-3.29595 1471361094512,sectionLowerCurrFiltered,-0.2 1471361094512,actuatorLowerFrontDuty,0.0 1471361094515,doorCtrlStatus,5.0 1471361094515,SMState,14.0 1471361094516,lateralAccel,25.55 ...
0
2016-10-09T23:33:05Z
39,949,636
<p>Read the data into a DataFrame using <code>pd.read_csv</code>, and then <a href="http://pandas.pydata.org/pandas-docs/stable/reshaping.html#reshaping-by-pivoting-dataframe-objects" rel="nofollow"><code>pivot</code></a>:</p> <pre><code>import pandas as pd df = pd.read_csv('data', header=None, names=['index','columns...
3
2016-10-09T23:39:25Z
[ "python", "pandas" ]
How do you combine variables to form function in python?
39,949,625
<pre><code>ypos = 1 ypos2 = ypos-1 xpos = 1 xpos2 = 2 </code></pre> <p>Using these variables, that are changed each time the code loops, how do I get it to print the result below?</p> <pre><code>=B(ypos)-B(ypos2) </code></pre> <p>Every time the code loops the ypos increases by one and therefore the ypos2 increases b...
0
2016-10-09T23:37:33Z
39,949,650
<pre><code>print('B({})-B({})'.format(ypos, ypos2)) </code></pre> <p>or</p> <pre><code>print('B(' + str(ypos) + ')-B(' + str(ypos2) + ')') </code></pre> <p>These should work in Python 2.7 or Python 3.x.</p>
2
2016-10-09T23:42:53Z
[ "python", "excel", "string", "python-2.7", "function" ]
How do you combine variables to form function in python?
39,949,625
<pre><code>ypos = 1 ypos2 = ypos-1 xpos = 1 xpos2 = 2 </code></pre> <p>Using these variables, that are changed each time the code loops, how do I get it to print the result below?</p> <pre><code>=B(ypos)-B(ypos2) </code></pre> <p>Every time the code loops the ypos increases by one and therefore the ypos2 increases b...
0
2016-10-09T23:37:33Z
39,949,683
<p>This should be it:</p> <pre><code>print 'B({})-B({})'.format(ypos, ypos2) </code></pre> <p>For python2.7 prints are without parentheses, unlike in python3. Check this to verify <a href="https://docs.python.org/2/tutorial/inputoutput.html" rel="nofollow">link</a></p>
1
2016-10-09T23:49:34Z
[ "python", "excel", "string", "python-2.7", "function" ]
Confused by python's unicode regex errors
39,949,679
<p>Can someone explain why the middle code excerpt in python 2.7x throws an error?</p> <pre><code>import re walden = "Waldenström" walden print(walden) s1 = "ö" s2 = "Wal" s3 = "OOOOO" out = re.sub(s1, s3, walden) print(out) out = re.sub("W", "w", walden) print(out) # I need this one to work out = re.sub('W', u'...
1
2016-10-09T23:48:28Z
39,949,732
<p><code>walden</code> is a <code>str</code>:</p> <pre><code>walden = "Waldenström" </code></pre> <p>This code replaces a character with a <code>unicode</code> string:</p> <pre><code>re.sub('W', u'w', walden) </code></pre> <p>The result of that should be <code>u'w' + "aldenström"</code>. This is the part that fai...
2
2016-10-09T23:59:14Z
[ "python", "unicode" ]
Django: python manage.py makemigrations returns IntegrityError: Column 'content_type_id' cannot be null
39,949,719
<p>I hooked up my Django project the the MySQL Database, and I am certain that it is actually connected because when I try to makemigrations. I checked MySQL workbench and all my models are synced into the database. However, the problem is when i try to migrate, I get this error. It is complaining that No migrations to...
2
2016-10-09T23:55:53Z
39,949,904
<blockquote> <p>I am certain that it is actually connected because when I try to makemigrations. I checked MySQL workbench and all my models are synced into the database.</p> </blockquote> <p>It sounds more like you are connecting to a database that was already being used for something, or you have run <code>mig...
0
2016-10-10T00:31:34Z
[ "python", "mysql", "django" ]
How can I use auto increment in my composite unique key in Django?
39,949,728
<p>I have a model class like this:</p> <pre><code>class TestModel(models.Model): class Meta: unique_together = ('prefix', 'number') prefix = models.CharField(max_length=30) number = models.IntegerField() </code></pre> <p>prefix and number together form a natural key for my model, but I don't part...
1
2016-10-09T23:58:09Z
39,967,356
<p>Here is a proof-of-concept approach, it's by no means production ready, but it seems to demonstrate the heavy lifting necessary to achieve this. I don't claim that's a clean or good way.</p> <p>Anyway, here it is:</p> <pre><code>class Subquery(str): query = None class MyIntegerField(models.IntegerField): ...
0
2016-10-10T21:55:44Z
[ "python", "mysql", "django", "database", "sqlite" ]
When accessing dictionary values, how to impute 'NaN' if no value exists for a certain key?
39,949,766
<p>I am looping through dictionaries and accessing the dictionary values to append to a list. </p> <p>Consider one dictionary as an example, <code>example_dict</code>:</p> <pre><code>example_dict = {"first":241, "second": 5234, "third": "Stevenson", "fourth":3.141592...} first_list = [] second_list = [] third_list = ...
0
2016-10-10T00:04:31Z
39,949,782
<p>You can perform a check for values that are not <code>""</code> and simply do something like this:</p> <pre><code>second_list.append(new_dict["second"] if new_dict["second"] != "" else "NaN")) </code></pre> <p>So, if key <code>second</code> exists in <code>new_dict</code> and is an empty string, then <code>NaN</co...
2
2016-10-10T00:06:35Z
[ "python", "python-3.x", "dictionary", null, "key-value" ]
How to make code that's functionally similar to enumerate without actually using enumerate?
39,949,783
<p>I suppose to write a code that prints out the value of a number that occurs twice in the list given, but they don't allow us to use a built in function on python. How would I be able to write it without using enumerate? </p> <pre><code>def find_second_occurrence(xs,v): count = 0 value = None for i, x in...
0
2016-10-10T00:06:42Z
39,949,872
<p><code>enumerate(sequence)</code> is pretty much similar to a construct of the form:</p> <pre><code>for i in range(len(sequence)): # get sequence[i] and return i and sequence[i] for all i's </code></pre> <p>So, in your code, replacing <code>enumerate</code> altogether could be done by:</p> <pre><code>for i in ...
0
2016-10-10T00:24:11Z
[ "python", "list", "function", "python-3.x", "enumerate" ]
How to make code that's functionally similar to enumerate without actually using enumerate?
39,949,783
<p>I suppose to write a code that prints out the value of a number that occurs twice in the list given, but they don't allow us to use a built in function on python. How would I be able to write it without using enumerate? </p> <pre><code>def find_second_occurrence(xs,v): count = 0 value = None for i, x in...
0
2016-10-10T00:06:42Z
39,949,908
<p>Your own enumerate function might be something like this: </p> <pre><code>def my_enumerate(a_list): result = [] counter = 0 for item in a_list: result.append((counter, item)) counter += 1 return result </code></pre> <p>Unlike the built-in <code>enumerate</code>, which is a generator...
0
2016-10-10T00:32:12Z
[ "python", "list", "function", "python-3.x", "enumerate" ]
How to zoom in a histogram in seaborn/matplotlib?
39,949,841
<p>I produced a histogram which looks something like this:</p> <p><a href="http://i.stack.imgur.com/M96Am.png" rel="nofollow"><img src="http://i.stack.imgur.com/M96Am.png" alt="enter image description here"></a></p> <p>Code that I used to produce this plot:</p> <pre><code>sns.countplot(table.column_name) </code></pr...
-1
2016-10-10T00:18:19Z
39,949,881
<p>Looks like the data would be better viewed on a logarithmic scale. On your matplotlib plot axis, <code>ax</code>, use:</p> <pre><code>ax.set_yscale('log') </code></pre>
-1
2016-10-10T00:26:30Z
[ "python", "matplotlib", "histogram", "seaborn" ]
How to direct directory from file to another on Mac
39,949,879
<p>So I am currently trying to install python3 into my Mac and whenever I type in </p> <pre><code>which python3 </code></pre> <p>It gives me the response of </p> <pre><code>/usr/local/bin/python3 </code></pre> <p>However, I want it to point to this directory below:</p> <pre><code>/usr/local/Cellar/python3/3.5.2_2/...
0
2016-10-10T00:26:13Z
39,949,957
<p>When you install <code>python</code> with brew, it will actually create a symlink from <code>/usr/loca/bin/...</code> to <code>/usr/loca/Cellar/...</code>. You can check this for example by running this command:</p> <pre><code>$ ls -l /usr/local/bin/python3 lrwxr-xr-x 1 mfischer admin 35 3 Aug 07:34 /usr/local/...
0
2016-10-10T00:43:13Z
[ "python", "python-3.x", "terminal", "directory" ]
Get the index of the max value using argmax in numpy array
39,949,887
<ol> <li><p>I have allocated about 34G of memory and read the data in: sst = np.empty([365,3600,7200], dtype-np.float32)</p></li> <li><p>using the argmax(sst,axis=0) to get the index of the max value for each pixel. </p></li> <li><p>the memory error problem appeared when running the program.</p></li> </ol> <p>Can anyo...
1
2016-10-10T00:27:12Z
39,950,506
<p><a href="https://github.com/numpy/numpy/blob/v1.11.0/numpy/core/fromnumeric.py#L917-L974" rel="nofollow">This source code</a> shows that argMax returns an array populated by the max on that axis. Instead of doing this, you could say allocate a new array for each axis, and do np.argMax on that array. If you make sure...
0
2016-10-10T02:23:17Z
[ "python", "numpy" ]
Python pandas interpolating series
39,949,897
<p>I have data in a csv file which appears as:</p> <pre><code> DateTime Temp 10/1/2016 0:00 20.35491156 10/1/2016 1:00 19.75320845 10/1/2016 4:00 17.62411292 10/1/2016 5:00 18.30190001 10/1/2016 6:00 19.37101638 </code></pre> <p>I am reading this file from csv file as:</p> <pre><code>import numpy as np i...
1
2016-10-10T00:29:20Z
39,949,953
<p>Use resample with datetime as index and use one of the methods of <a href="http://pandas.pydata.org/pandas-docs/stable/timeseries.html#resampling" rel="nofollow">resampling</a> that fits your need. For instance:</p> <pre><code>df.set_index('DateTime').resample('1H').pad() Out[23]: Temp Da...
2
2016-10-10T00:42:20Z
[ "python", "pandas", "interpolation" ]
Python pandas interpolating series
39,949,897
<p>I have data in a csv file which appears as:</p> <pre><code> DateTime Temp 10/1/2016 0:00 20.35491156 10/1/2016 1:00 19.75320845 10/1/2016 4:00 17.62411292 10/1/2016 5:00 18.30190001 10/1/2016 6:00 19.37101638 </code></pre> <p>I am reading this file from csv file as:</p> <pre><code>import numpy as np i...
1
2016-10-10T00:29:20Z
39,953,120
<p>use the <code>interpolate</code> method after <code>resample</code> on an hourly basis.</p> <pre><code>d2.set_index('DateTime').resample('H').interpolate() </code></pre> <p>If <code>d2</code> is a series then we don't need the set_index</p> <pre><code>d2.resample('H').interpolate() </code></pre> <p><a href="http...
1
2016-10-10T07:23:00Z
[ "python", "pandas", "interpolation" ]
Unable to scrape this movie website using BeautifulSoup
39,949,917
<p>I am trying to scrap a movie website here: <a href="http://www.21cineplex.com/nowplaying" rel="nofollow">http://www.21cineplex.com/nowplaying</a></p> <p>I have uploaded the screenshot with the HTML body as the image in this questions.<a href="http://i.stack.imgur.com/OncE1.png" rel="nofollow">link to screenshot her...
0
2016-10-10T00:33:37Z
39,950,335
<p>This server is checking <code>Referer</code> header. If there is no <code>Referer</code> it sends main page. But it doesn't check text in this header so it can be even empty string.</p> <pre><code>import requests import bs4 headers = { #'Referer': any url (or even random text, or empty string) #'Referer':...
1
2016-10-10T01:50:52Z
[ "python", "html", "web-scraping", "beautifulsoup", "python-requests" ]
beautifulsoup does not find all p with a certain class
39,949,923
<p>I am using beautifulsoup to find all p in a certain html page I saved locally. My code is</p> <pre><code>with open ("./" + str(filename) + ".txt", "r") as myfile: data=myfile.read().replace('\n', '') soup = BeautifulSoup(data) t11 = soup.findAll("p", {"class": "commentsParagraph"}) </code></pre> <p>this codes ...
0
2016-10-10T00:35:04Z
39,950,231
<p>I have downloaded you html and done some tests, the beautifulsoup module could only find out three p nodes. And I guess, that's because there is some iframes in the html, so BS does not work probably. My suggestion is using <code>re</code> module instead of <code>bs</code></p> <p>sample code for your reference:</p>...
-1
2016-10-10T01:32:20Z
[ "python", "beautifulsoup" ]
beautifulsoup does not find all p with a certain class
39,949,923
<p>I am using beautifulsoup to find all p in a certain html page I saved locally. My code is</p> <pre><code>with open ("./" + str(filename) + ".txt", "r") as myfile: data=myfile.read().replace('\n', '') soup = BeautifulSoup(data) t11 = soup.findAll("p", {"class": "commentsParagraph"}) </code></pre> <p>this codes ...
0
2016-10-10T00:35:04Z
39,955,133
<p>There is one p tag with the commentsParagraph2 class in your html which bs4 can find without issue using all three parsers:</p> <pre><code>In [8]: from bs4 import BeautifulSoup ...: soup1 = BeautifulSoup(open("/home/padraic ...: /t.html").read(),"html5lib") ...: soup2 = BeautifulSoup(open("/home/padraic ...
1
2016-10-10T09:23:58Z
[ "python", "beautifulsoup" ]
Kivy: how to reference widgets from python code?
39,949,990
<p>Basic Kivy question. Given this kv file:</p> <pre><code>BoxLayout: MainMenu: MyCanvasWidget: &lt;MainMenu&gt;: Button: on_press: root.do_action() </code></pre> <p>How do I call a method of MyCanvasWidget (for drawing something) from the do_action method when the button in MainMenu is pressed?<...
0
2016-10-10T00:49:40Z
39,956,239
<pre><code>BoxLayout: MainMenu: do_action: mycanvas.method MyCanvasWidget: id: mycanvas &lt;MainMenu&gt;: Button: on_press: root.do_action() </code></pre> <p>Got some inspiration from <a href="http://stackoverflow.com/questions/39807997/how-to-access-some-widget-attribute-from-anot...
0
2016-10-10T10:29:52Z
[ "python", "python-2.7", "kivy", "kivy-language" ]
Get unique entries in list of lists by an item
39,950,042
<p>This seems like a fairly straightforward problem but I can't seem to find an efficient way to do it. I have a list of lists like this:</p> <pre><code>list = [['abc','def','123'],['abc','xyz','123'],['ghi','jqk','456']] </code></pre> <p>I want to get a list of unique entries by the third item in each child list (th...
1
2016-10-10T01:00:45Z
39,950,098
<p>How about this: Create a <code>set</code> that keeps track of ids already seen, and only append sublists where id's where not seen.</p> <pre><code>l = [['abc','def','123'],['abc','xyz','123'],['ghi','jqk','456']] seen = set() new_list = [] for sl in l: if sl[2] not in seen: new_list.append(sl) ...
4
2016-10-10T01:09:29Z
[ "python", "list", "set" ]
Get unique entries in list of lists by an item
39,950,042
<p>This seems like a fairly straightforward problem but I can't seem to find an efficient way to do it. I have a list of lists like this:</p> <pre><code>list = [['abc','def','123'],['abc','xyz','123'],['ghi','jqk','456']] </code></pre> <p>I want to get a list of unique entries by the third item in each child list (th...
1
2016-10-10T01:00:45Z
39,950,105
<p>One approach would be to create an inner loop. within the first loop you iterate over the outer list starting from 1, previously you will need to create an arraylist which will add the first element, inside the inner loop starting from index 0 you will check only if the third element is located as part of the third ...
0
2016-10-10T01:10:13Z
[ "python", "list", "set" ]
How to join two new numeric columns in a dataframe using a separator?
39,950,057
<p>I have the dataframe df: </p> <pre><code>start end 836 845 3341 3350 4647 4661 4932 4942 10088 10098 13679 13690 16888 16954 20202 20225 </code></pre> <p>Now I need a third column "JoinedCol" as</p> <pre><code>836:845 3341:3350 4647:4661 4932:4942 10088:10098 ... ... </code></pre> <p>I don't w...
0
2016-10-10T01:03:03Z
39,950,157
<p>As far as I know, you can't have this type of data in R. If you join the ':' symbol to any number, the new string will always be a factor, a character or a matrix.</p> <p>To retrieve data from that specific column you would have to specify which part you want, lets say with <code>substring()</code>. Otherwise you h...
0
2016-10-10T01:17:43Z
[ "python" ]
How to join two new numeric columns in a dataframe using a separator?
39,950,057
<p>I have the dataframe df: </p> <pre><code>start end 836 845 3341 3350 4647 4661 4932 4942 10088 10098 13679 13690 16888 16954 20202 20225 </code></pre> <p>Now I need a third column "JoinedCol" as</p> <pre><code>836:845 3341:3350 4647:4661 4932:4942 10088:10098 ... ... </code></pre> <p>I don't w...
0
2016-10-10T01:03:03Z
39,957,285
<p>Based on </p> <blockquote> <p>I want to use the new column "JoinedCol" to use in R for further getting the data like 836, 837,838,...844,845,3341,3342........ ..... 10098</p> </blockquote> <p>you actually want this:</p> <pre><code>DF &lt;- read.table(text = "start end 836 845 ...
0
2016-10-10T11:32:01Z
[ "python" ]
how to execute python code with tkinter user input
39,950,082
<p>when user input cluster in this tkinter code (tkintt.py) and click submit button, i want the program execute k-medoids code (example.py) based on how many cluster that user input but it gets some errors. could you help me?</p> <p>tkintt.py</p> <pre><code>import Tkinter from _tkinter import * root = Tkinter.Tk() l...
0
2016-10-10T01:07:37Z
39,965,803
<p>It appears as if that k-medoid does not handle allethe corner cases correctly.</p> <p>Most likely, you have an empty cluster.</p>
0
2016-10-10T19:55:51Z
[ "python", "python-2.7", "tkinter", "pycharm", "cluster-analysis" ]
Recursive sequence generator
39,950,111
<p>Does Python have a recursive sequence generating function? For instance,</p> <pre><code>def generateSequence(seed, f, n): sequence = list(seed) for i in range(n): sequence.append(f(sequence, i)) return sequence </code></pre> <p>Which may be used like so:</p> <pre><code>fibSequence = generateSe...
2
2016-10-10T01:11:33Z
39,950,583
<p>I think the <a href="https://docs.python.org/3/library/itertools.html#itertools.accumulate" rel="nofollow"><code>itertools.accumulate</code></a> may meet your needs, but it's return value may be different from what you expect.</p> <p>For instance:</p> <pre><code>#!/usr/bin/env python3 # -*- coding: utf-8 -*- from...
0
2016-10-10T02:34:46Z
[ "python" ]
How to avoid re-importing modules and re-defining large object every time a script runs
39,950,130
<p>This must have an answer but I cant find it. I am using a quite large python module called quippy. With this module one can define an intermolecular potential to use as a calculator in ASE like so: </p> <pre><code>from quippy import * from ase import atoms pot=Potential("Potential xml_label=gap_h2o_2b_ccsdt_3b_ccs...
2
2016-10-10T01:13:39Z
39,950,290
<p>You can either use raw files or modules such as <code>pickle</code> to store data easily.</p> <pre><code>import cPickle as pickle from quippy import Potential try: # try previously calculated value with open('/tmp/pot_store.pkl') as store: pot = pickle.load(store) except OSError: # fall back to calcul...
0
2016-10-10T01:43:37Z
[ "python", "python-2.7", "optimization", "import", "load" ]
How to avoid re-importing modules and re-defining large object every time a script runs
39,950,130
<p>This must have an answer but I cant find it. I am using a quite large python module called quippy. With this module one can define an intermolecular potential to use as a calculator in ASE like so: </p> <pre><code>from quippy import * from ase import atoms pot=Potential("Potential xml_label=gap_h2o_2b_ccsdt_3b_ccs...
2
2016-10-10T01:13:39Z
39,950,446
<p>I found one solution, but I'm interested in alternatives. You can divide the script into two parts: </p> <p>start.py:</p> <pre><code>from quippy import Potential from ase import atoms pot=Potential(... etc... </code></pre> <p>body.py:</p> <pre><code>for i in range(max_int): print "doing things" # etc... <...
0
2016-10-10T02:11:48Z
[ "python", "python-2.7", "optimization", "import", "load" ]
How to dynamically replace some field in Flask-Admin into Select2?
39,950,182
<p>I have a flask-admin form, where when user select the topmost dropdown field, certain fields in this form must change into Select2 (dropdown) field. This is what I have so far:</p> <pre><code>for(var idx in formData.custom_field_chooser) { var custom_field = $('#' + idx); custom_field.select2();...
0
2016-10-10T01:21:56Z
39,969,300
<p>Finally looking at the trivial error message <code>Uncaught query function not defined for Select2</code>, <a href="http://stackoverflow.com/questions/14483348/query-function-not-defined-for-select2-undefined-error">this post in SO</a> solved my problem. This is how you properly initialized an empty Select2:</p> <p...
0
2016-10-11T01:45:55Z
[ "python", "twitter-bootstrap-3", "select2", "flask-admin" ]
Python to php server Get Data
39,950,201
<p>Ok I'm a little confused here I need to send data to a php server and receive back a response from it example: a raspberry pi sends a unit id and the server returns json file. </p> <p>I have tried this .py code</p> <pre><code>import requests import json url = 'http://localhost/updateContent.php' payload = {"devic...
0
2016-10-10T01:26:43Z
39,971,538
<pre><code>response = requests.post(url, data=json.dumps(payload), headers=headers) </code></pre> <p>To output the result of your post you have to print out <code>response.text</code> <code>print(response.text);</code></p>
0
2016-10-11T06:28:19Z
[ "php", "python", "json", "raspberry-pi" ]
Windchill nested loops python code equation
39,950,205
<p>I started python only a few months ago and I have been given a task to use a nested loops to calculate wind chill.</p> <p>I have most of the code completed (I think), however the equation is not working the way it want it to work.</p> <p>Here is my code at the moment:</p> <pre><code>def main(): temp = 0 wind = 0 ...
0
2016-10-10T01:27:21Z
39,950,234
<p>You must define an actual <em>function</em>. What you have is just an assignment:</p> <pre><code>temp = 0 wind = 0 windChill = 13.12 + (.6215 * temp) - (11.37 * wind ** 770.16) + (.3965 * temp * wind **0.16) print(windChill) # 13.12 </code></pre> <p>Basically, <code>temp</code> and <code>wind</code> are used with...
1
2016-10-10T01:33:08Z
[ "python" ]
"PermissionError: [Errno 13] Permission denied: '/usr/lib/python3.5/site-packages'" installing Django
39,950,254
<p>I cannot install basic django packages on ubuntu. I just deleted virtualenv and remade it. <code>pip3install</code> = <code>pip3 install -r requirements.txt</code></p> <pre><code>[mything] cchilders@cchilders-desktop:~/projects/mything (master) $ cat requirements.txt Django==1.10.1 django-filter djangorestframewo...
1
2016-10-10T01:37:07Z
39,950,376
<p>Try using <code>sudo pip install django</code> when installing django. This will work if you have root privileges, otherwise you may need to use virtualenv. The django documentation and installation guides can be found <a href="https://docs.djangoproject.com/en/1.10/" rel="nofollow" > Here </a></p>
1
2016-10-10T01:59:22Z
[ "python", "django", "pip", "virtualenv", "django-1.10" ]
"PermissionError: [Errno 13] Permission denied: '/usr/lib/python3.5/site-packages'" installing Django
39,950,254
<p>I cannot install basic django packages on ubuntu. I just deleted virtualenv and remade it. <code>pip3install</code> = <code>pip3 install -r requirements.txt</code></p> <pre><code>[mything] cchilders@cchilders-desktop:~/projects/mything (master) $ cat requirements.txt Django==1.10.1 django-filter djangorestframewo...
1
2016-10-10T01:37:07Z
39,950,544
<p>You could accidentally recreate virtualenv with Python2 by forgetting to put path to Python3 interpreter so when you execute pip3 it refers to system Python3. </p> <p>Make sure that you use correct Python in your virtualenv and also make sure that you create virtualenv with pip (yes it's the default option but we d...
1
2016-10-10T02:29:38Z
[ "python", "django", "pip", "virtualenv", "django-1.10" ]
Tkinter filedialog reading in a file path
39,950,322
<p>I have searched around and have not really found the answer to my problem yet. </p> <p>I am trying to browse through files to take in an image file and a use its path as a variable to pass into my qr function, but when using file dialog it gives me this </p> <p>&lt;_io.TextIOWrapper name='C:/Users/Elias/Desktop/Ne...
0
2016-10-10T01:49:20Z
39,950,353
<p>You are using <code>filedialog.askopenfile()</code>. This gives you a file <em>handle</em>. If you just want the file <em>name</em>, use <code>filedialog.askopenfilename()</code>.</p>
2
2016-10-10T01:54:25Z
[ "python", "tkinter", "filedialog" ]
list comprehension in python with if and else
39,950,416
<p>after i test,</p> <pre><code>len_stat = [len(x) if len(x) &gt; len_stat[i] else len_stat[i] for i, x in enumerate(a_list)] </code></pre> <p>is same with </p> <pre><code>for i, x in enumerate(a_list): if len(x) &gt; len_stat[i]: len_stat[i] = len(x) </code></pre> <p>of course, but,</p> <pre><code>len...
0
2016-10-10T02:06:57Z
39,950,484
<p>This list comprehension:</p> <pre><code>len_stat = [len(x) if len(x) &gt; len_stat[a_list.index(x)] else len_stat[a_list.index(x)] for x in a_list] </code></pre> <p>Is equivalent to:</p> <pre><code>temp = [] for x in a_list: temp.append(len(x) if len(x) &gt; len_stat[a_list.index(x)] else len_stat[a_list.inde...
0
2016-10-10T02:19:55Z
[ "python" ]
How do I find the max integer of a string of integer without using a list?
39,950,481
<p>I must use a for loop, no list allowed. May assume string is non-empty. What I have:</p> <pre><code>def max_numbers(s): n_string = '' for char in s: if char.isdigit(): n_string += char return max(n_string) max_numbers('22 53 123 54 243') 5 expected 243 </code></pre> <p>Please don'...
-1
2016-10-10T02:19:36Z
39,950,517
<p>If @IvanCai's answer is too advanced try:</p> <pre><code>def max_numbers(s): top=0 curr=0 for char in s: if char.isdigit(): curr*=10 curr+=int(char) if curr&gt;top: top=curr elif char==' ' or char=='\n': curr=0 return to...
-2
2016-10-10T02:25:20Z
[ "python" ]
How do I find the max integer of a string of integer without using a list?
39,950,481
<p>I must use a for loop, no list allowed. May assume string is non-empty. What I have:</p> <pre><code>def max_numbers(s): n_string = '' for char in s: if char.isdigit(): n_string += char return max(n_string) max_numbers('22 53 123 54 243') 5 expected 243 </code></pre> <p>Please don'...
-1
2016-10-10T02:19:36Z
39,950,580
<p>Not going to write any code for you because doing it the way you have specified is just boring. Also since you have not indicated what version of python you are using, I will just assume version 2.</p> <p>Here are a few things you will need:</p> <ul> <li><a href="https://docs.python.org/2/library/stdtypes.html#str...
1
2016-10-10T02:34:24Z
[ "python" ]
How do I find the max integer of a string of integer without using a list?
39,950,481
<p>I must use a for loop, no list allowed. May assume string is non-empty. What I have:</p> <pre><code>def max_numbers(s): n_string = '' for char in s: if char.isdigit(): n_string += char return max(n_string) max_numbers('22 53 123 54 243') 5 expected 243 </code></pre> <p>Please don'...
-1
2016-10-10T02:19:36Z
39,950,607
<pre><code>def max_numbers(s): # biggest number we've seen so far. init to a very small number so # it will get replaced immediately by real input data biggest = -999 # accumulate digit characters from input n_string = '' # loop through each input character for char in s: # is it...
1
2016-10-10T02:38:45Z
[ "python" ]
How do I find the max integer of a string of integer without using a list?
39,950,481
<p>I must use a for loop, no list allowed. May assume string is non-empty. What I have:</p> <pre><code>def max_numbers(s): n_string = '' for char in s: if char.isdigit(): n_string += char return max(n_string) max_numbers('22 53 123 54 243') 5 expected 243 </code></pre> <p>Please don'...
-1
2016-10-10T02:19:36Z
39,950,621
<p>The idea is to separate out the integers from the string (as you are already doing, but a bit wrongly), and keep track of the max so far. When a character is not digit, you convert the <code>n_string</code> to <code>int</code> and compare with <code>max_</code> which keeps track of maximum int found so far, and then...
4
2016-10-10T02:42:16Z
[ "python" ]
Inserting generated Matplotlib plots into Flask with python3
39,950,522
<p>I am using Python 3 and Flask with Matplotlib and numpy.</p> <p>I wish to load pages that generate many plots which are embedded into the page.</p> <p>I have tried following suggestions made in other places, such as this <a href="http://stackoverflow.com/questions/20107414/passing-a-matplotlib-figure-to-html-flask...
-1
2016-10-10T02:25:58Z
39,951,208
<p>The code taken from this <a href="http://stackoverflow.com/questions/20107414/passing-a-matplotlib-figure-to-html-flask?rq=1">stackoverflow question</a> which is used in the above question contains the following:</p> <pre><code> import StringIO ... fig = draw_polygons(cropzonekey) img = StringIO() ...
1
2016-10-10T04:10:56Z
[ "python", "python-3.x", "numpy", "matplotlib", "flask" ]
Python for maximum pairwise product
39,950,568
<pre><code>n = int(input("Enter the number of elements in the array (2-200,000):")) a = [int(x) for x in input("Enter all numbers of the sequence with only non-negative intergers not exceeding 100,000:").split()] c = list()3 for i in range(0,n): for j in range (1,n): if a[i] != a[j]: m = a[i]*a...
0
2016-10-10T02:33:01Z
39,950,700
<pre><code>def MaxPairwiseProduct(n,a,c): for i in range(0,n): for j in range (1,n): if a[i] != a[j]: m = a[i]*a[j] c.append(m) else: continue Product = max(c) return Product n = int(input("Enter the number of elements in the...
1
2016-10-10T02:55:01Z
[ "python", "product" ]
Python for maximum pairwise product
39,950,568
<pre><code>n = int(input("Enter the number of elements in the array (2-200,000):")) a = [int(x) for x in input("Enter all numbers of the sequence with only non-negative intergers not exceeding 100,000:").split()] c = list()3 for i in range(0,n): for j in range (1,n): if a[i] != a[j]: m = a[i]*a...
0
2016-10-10T02:33:01Z
39,965,104
<pre><code># Uses python3 def MaxPairwiseProduct(n,a,c): for i in range(0,n): for j in range (1,n): if a[i] != a[j]: m = a[i]*a[j] c.append(m) else: continue Product1 = max(c) return Product1 def MaxPairwiseProductFast(n,a): ...
1
2016-10-10T19:06:00Z
[ "python", "product" ]
Using different dbs on production and test environment
39,950,769
<p>I want to use a test db on my test environment, and the production db on production environment in my Python application.</p> <p>How should I handle routing to two dbs? Should I have an untracked <code>config.yml</code> file that has the test db's connection string on my test server, and the production db's connect...
0
2016-10-10T03:06:16Z
39,951,058
<p>Let's take Linux environment for example. Often, the user level configuration of an application is placed under your home folder as a dot file. So what you can do is like this:</p> <ol> <li>In your git repository, track a sample configure file, e.g., <code>config.sample.yaml</code>, and put the configuration struct...
0
2016-10-10T03:50:35Z
[ "python", "github", "configuration", "travis-ci", "configuration-files" ]
How to assign the elements of a list as file names in python?
39,950,794
<p>I am trying to assign the elements of a list as names for some files that live in a directory, so far I created a function that recover the name of a each file from a directory and returns them in a list:</p> <pre><code>def retrive(directory_path): path_names = [] for filename in sorted(glob.glob(os.path.jo...
1
2016-10-10T03:10:30Z
39,951,319
<p>You’re almost there:</p> <pre><code>for path_name in path_names: path = os.path.join(new_dir_path, "list%s.txt" % path_name) #This is the path of each new file: #print(path) with codecs.open(path, "w", encoding='utf8') as f: for item in [a_list]: f.write(item+"\n") </code></pre...
1
2016-10-10T04:28:47Z
[ "python", "python-2.7", "python-3.x", "io", "python-3.5" ]
python XML get text inside <p>...</p> tag
39,950,810
<p>I guys, I have an xml structure which looks somewhat like this.</p> <pre><code>&lt;abstract&gt; &lt;p id = "p-0001" num = "0000"&gt; blah blah blah &lt;/p&gt; &lt;/abstract&gt; </code></pre> <p>I would like to extract the <code>&lt;p&gt;</code> tag inside the <code>&lt;abstract&gt;</code> tag only.</p> <...
1
2016-10-10T03:14:12Z
39,950,858
<p>You can use an <em>XPath expression</em> to search for <code>p</code> elements specifically inside the <code>abstract</code>:</p> <pre><code>for p in xroot.xpath(".//abstract//p"): print(p.text.strip()) </code></pre> <p>Or, if using <code>iter()</code> you may have a nested loop:</p> <pre><code>for abstract i...
2
2016-10-10T03:21:14Z
[ "python", "xml" ]
Extract results from a dictionary
39,950,856
<p>I have a dictionary as follows:</p> <pre><code> D = { "America": { "Washington": { "Seattle": ('park', 'museum'), "Kent": ("market",) }, 'Colorado': { "Boulder": ("hiking",) } } } </code></pre> <p>how can I make the following results using that dictionary.</p> <pre><code>America Wahington Seattle park America Wa...
1
2016-10-10T03:20:56Z
39,950,903
<p>Here is a solution almost entirely based on the <a href="http://stackoverflow.com/a/6027615/771848">"recursive"-approach answer</a> for the "flattening the dictionary" problem:</p> <pre><code>import collections def flatten(d, parent_key='', sep=' '): items = [] for k, v in d.items(): new_key = par...
0
2016-10-10T03:28:15Z
[ "python", "python-2.7", "dictionary" ]
Extract results from a dictionary
39,950,856
<p>I have a dictionary as follows:</p> <pre><code> D = { "America": { "Washington": { "Seattle": ('park', 'museum'), "Kent": ("market",) }, 'Colorado': { "Boulder": ("hiking",) } } } </code></pre> <p>how can I make the following results using that dictionary.</p> <pre><code>America Wahington Seattle park America Wa...
1
2016-10-10T03:20:56Z
39,950,906
<p>Recursion is your friend...</p> <pre><code>D = { "America": { "Washington": { "Seattle": ('park', 'museum'), "Kent": ("market",) }, 'Colorado': { "Boulder": ("hiking",) } } } def printOut(d,s): if(type(d)==dict): for k in d.keys(): printOut(d[k],s+" "+str(k)) # add the key to a string and p...
0
2016-10-10T03:29:27Z
[ "python", "python-2.7", "dictionary" ]
Extract results from a dictionary
39,950,856
<p>I have a dictionary as follows:</p> <pre><code> D = { "America": { "Washington": { "Seattle": ('park', 'museum'), "Kent": ("market",) }, 'Colorado': { "Boulder": ("hiking",) } } } </code></pre> <p>how can I make the following results using that dictionary.</p> <pre><code>America Wahington Seattle park America Wa...
1
2016-10-10T03:20:56Z
39,950,961
<p>This versions should be more readable for you. But they are not so universal like other versions.</p> <pre><code>for country in D: for state in D[country]: for city in D[country][state]: for place in D[country][state][city]: print(country, state, city, place) for country, A...
1
2016-10-10T03:36:16Z
[ "python", "python-2.7", "dictionary" ]
Extract results from a dictionary
39,950,856
<p>I have a dictionary as follows:</p> <pre><code> D = { "America": { "Washington": { "Seattle": ('park', 'museum'), "Kent": ("market",) }, 'Colorado': { "Boulder": ("hiking",) } } } </code></pre> <p>how can I make the following results using that dictionary.</p> <pre><code>America Wahington Seattle park America Wa...
1
2016-10-10T03:20:56Z
39,950,977
<p>I would suggest recursive solution to work with your different kind of data:</p> <pre><code>def printX(data, prefix=''): if isinstance(data, dict): for itemKey, itemValue in data.iteritems(): newPrefix = '{} {}'.format(prefix, itemKey) printX(itemValue, newPrefix) elif isins...
0
2016-10-10T03:38:16Z
[ "python", "python-2.7", "dictionary" ]
Building a LSTM Cell using Keras
39,950,872
<p>I'm trying to build a RNN for text generation. I'm stuck at building my LSTM cell. The data is shaped like this- X is the input sparse matrix of dim(90809,2700) and Y is the output matrix of dimension(90809,27). The following is my code for defining the LSTM Cell-</p> <pre><code>model = Sequential() model.add(LSTM(...
0
2016-10-10T03:23:43Z
40,013,716
<p>You should read about the difference between <code>input_shape</code>, <code>batch_input_shape</code> and <code>input_dim</code> <a href="https://keras.io/getting-started/sequential-model-guide/#specifying-the-input-shape" rel="nofollow">here</a>.</p> <p>For <code>input_shape</code>, we don't need to define the <co...
0
2016-10-13T06:25:09Z
[ "python", "keras", "recurrent-neural-network", "lstm" ]
Convert string based NaN's to numpy NaN's
39,950,951
<p>I have a dataframe with a part of it shown as below:</p> <pre><code>2016-12-27 NaN 2016-12-28 NaN 2016-12-29 NaN 2016-12-30 NaN 2016-12-31 NaN Name: var_name, dtype: object </code></pre> <p>The column contains NaN as strings/objects. How can I conver...
2
2016-10-10T03:34:26Z
39,951,125
<p>Suppose we have:</p> <pre><code>&gt;&gt;&gt; df=pd.DataFrame({'col':['NaN']*10}) </code></pre> <p>You can use <code>.apply</code> to convert:</p> <pre><code>&gt;&gt;&gt; new_df=df.apply(float, axis=1) &gt;&gt;&gt; type(new_df[0]) &lt;type 'numpy.float64'&gt; </code></pre>
1
2016-10-10T03:58:45Z
[ "python", "pandas", "numpy" ]
Convert string based NaN's to numpy NaN's
39,950,951
<p>I have a dataframe with a part of it shown as below:</p> <pre><code>2016-12-27 NaN 2016-12-28 NaN 2016-12-29 NaN 2016-12-30 NaN 2016-12-31 NaN Name: var_name, dtype: object </code></pre> <p>The column contains NaN as strings/objects. How can I conver...
2
2016-10-10T03:34:26Z
39,951,175
<p>Yes, you can do this when reading the csv file.</p> <pre><code>df = pd.read_csv('test.csv', names=['t', 'v'], dtype={'v':np.float64}) </code></pre> <p>Check the docs of <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow">pandas.read_csv</a>. There are some parameters...
1
2016-10-10T04:06:54Z
[ "python", "pandas", "numpy" ]
Convert string based NaN's to numpy NaN's
39,950,951
<p>I have a dataframe with a part of it shown as below:</p> <pre><code>2016-12-27 NaN 2016-12-28 NaN 2016-12-29 NaN 2016-12-30 NaN 2016-12-31 NaN Name: var_name, dtype: object </code></pre> <p>The column contains NaN as strings/objects. How can I conver...
2
2016-10-10T03:34:26Z
39,951,856
<p>I'd use the <code>converters</code> option in <code>read_csv</code>. In this case, we are aiming to convert the column in question to numeric values and treat everything else as <code>numpy.nan</code> which includes string version of <code>'NaN'</code></p> <pre><code>converter = lambda x: pd.to_numeric(x, 'coerce'...
1
2016-10-10T05:37:55Z
[ "python", "pandas", "numpy" ]
Harden sshd_config via python
39,951,199
<ol> <li>Find line starting with "#PermitRootLogin yes" and replace with "PermitRootLogin no"</li> <li>Append line at the bottom saying "AllowUsers user1@test.com"</li> <li>Restart sshd daemon</li> </ol> <p>(My Code)</p> <pre><code>#!/usr/bin/python3 import fileinput for line in fileinput.input("/etc/ssh/sshd_config...
0
2016-10-10T04:09:30Z
39,951,293
<p>You have a syntax error in your code. Your <code>for</code> loop expression has an erroneous comma:</p> <pre><code>for line in fileinput.input("/etc/ssh/sshd_config", inplace=True), : </code></pre> <p>That means that you're actually iterating over a single-element tuple, containing a <code>fileinput.FileInput</c...
0
2016-10-10T04:24:17Z
[ "python", "python-3.x" ]
SQLAlchemy not finding Postgres table connected with postgres_fdw
39,951,230
<p>Please excuse any terminology typos, don't have a lot of experience with databases other than SQLite. I'm trying to replicate what I would do in SQLite where I could ATTACH a database to a second database and query across all the tables. I wasn't using SQLAlchemy with SQLite</p> <p>I'm working with SQLAlchemy 1.0...
0
2016-10-10T04:16:20Z
39,995,132
<p>In order to map a table <a href="http://docs.sqlalchemy.org/en/latest/faq/ormconfiguration.html#how-do-i-map-a-table-that-has-no-primary-key" rel="nofollow">SQLAlchemy needs there to be at least one column denoted as a primary key column</a>. This does not mean that the column need actually be a primary key column i...
1
2016-10-12T09:28:20Z
[ "python", "postgresql", "sqlalchemy", "postgres-fdw" ]
How to find the starting element name in xml using iterparse
39,951,264
<p>I have the following sample xml</p> <pre><code>&lt;osm version="0.6" generator="CGImap 0.3.3 (28791 thorn-03.openstreetmap.org)" copyright="OpenStreetMap and contributors" attribution="http://www.openstreetmap.org/copyright" license="http://opendatacommons.org/licenses/odbl/1-0/"&gt; &lt;bounds minlat="41.970450...
0
2016-10-10T04:20:15Z
39,953,418
<p>Assuming <code>bounds</code> and <code>node</code> are one level under the root of the XML, this should work:</p> <pre><code>def count_tags(): mytags = {} for event, child in ET.iterparse('example.osm'): if child.tag in ('bounds', 'node'): mytags[child.tag] = child.attrib print mytag...
0
2016-10-10T07:42:29Z
[ "python", "xml", "iterparse" ]
Polygons in Python
39,951,281
<p>I've been trying to figure out how to find an approximation of PI using Polygons' method. And drawing out the polygons that are approximating PI.</p> <p>I've seen multiple ways to approximate PI, but none of them writing out the polygon on screen using Turtle (So you can see the visual aspect of the approximation)...
0
2016-10-10T04:22:35Z
39,964,824
<p>Taking a new approach, I've used turtle graphics to animate <a href="http://www.craig-wood.com/nick/articles/pi-archimedes/" rel="nofollow">Craig Wood's Pi - Archimedes code</a> from his <a href="http://www.craig-wood.com/nick/articles/fun-with-maths-and-python-introduction/" rel="nofollow">Fun with Maths and Pytho...
1
2016-10-10T18:47:20Z
[ "python", "turtle-graphics" ]
How to use for loop to plot figures saved to different files with matplotlib?
39,951,334
<p>I wanted to plot n independent figures by a for loop, with each figure saved to one file. My code is as following:</p> <pre><code>import matplotlib.pyplot as plt import numpy as np for i in range(len(nfile)): #nfile is a list of file names data = np.load(nfile[i]) plt.plot(data[0], data[1]) plt.savefig(...
-2
2016-10-10T04:30:41Z
39,951,449
<p>At the beginning of your loop, add:</p> <pre><code>plt.close() </code></pre>
1
2016-10-10T04:47:56Z
[ "python", "matplotlib", "plot" ]
Python program returning none
39,951,335
<p>The following code (allegedly) returns none.</p> <pre><code>def addTwo(startingvalue): endingvalue = startingvalue + 2 return endingvalue sum1 = addTwo(5) sum2 = addTwo(52) print('The results of adding are ', sum1, sum2) </code></pre>
-3
2016-10-10T04:30:55Z
39,951,382
<p>As people have mentioned in the comments, you had a small typo in one of your function calls which would throw a NameError. But other than that, it works perfectly fine with the following output:</p> <pre><code>The results of adding are 7 54 </code></pre> <p>Okay, here's the problem, the code in the question is p...
2
2016-10-10T04:39:09Z
[ "python", "return" ]
NLTK AssertionError when taking sentences from PlaintextCorpusReader
39,951,340
<p>I'm using a PlaintextCorpusReader to work with some files from Project Gutenberg. It seems to handle word tokenization without issue, but chokes when I request sentences or paragraphs.</p> <p>I start by downloading <a href="http://www.gutenberg.org/cache/epub/345/pg345.txt" rel="nofollow">a Gutenberg book (in UTF-8...
0
2016-10-10T04:31:39Z
39,963,074
<p>That particular file has a UTF-8 Byte Order Mark (EF BB BF) at the start, which is confusing NLTK. Removing those bytes manually, or copy-pasting the entire text into a new file, fixes the problem.</p> <p>I'm not sure why NLTK can't handle BOMs, but at least there's a solution.</p>
0
2016-10-10T16:49:45Z
[ "python", "nlp", "nltk" ]
python, plot triangular function into 2d arrays
39,951,392
<p>I'm new to python, in this case, I want to put my function into 2d arrays, so I can plot the function. Here is my triangle function, I'm using it for fuzzy logic:</p> <pre><code>def triangle (z,a,b,c): if (z&lt;=a) | (z&gt;=c): y = 0 elif (a&lt;=z) &amp; (z&lt;=b): y = (z-a) / (b-a) elif...
1
2016-10-10T04:40:49Z
39,951,997
<p>Looks like <code>a, b, c</code> are constants and <code>z</code> is a <code>np.linspace</code> between <code>a</code>, and <code>c</code>.</p> <p>You can make use of <a href="http://docs.scipy.org/doc/numpy/user/basics.indexing.html#boolean-or-mask-index-arrays" rel="nofollow">Boolean Indexing</a> , <a href="https:...
2
2016-10-10T05:51:19Z
[ "python", "arrays", "numpy", "triangular" ]
I lose my values in the columns
39,951,581
<p>HI~ I wanna ask about my problem I've organized my data using pandas. and I fill my procedure out like below</p> <pre><code>import pandas as pd import numpy as np df1 = pd.read_table(r'E:\빅데이터 캠퍼스\골목상권 프로파일링 - 서울 열린데이터 광장 3.초기-16년5월분1\17.상권-추정매ì¶...
2
2016-10-10T05:06:11Z
39,951,608
<p><a href="http://pandas.pydata.org/pandas-docs/stable/advanced.html#creating-a-multiindex-hierarchical-index-object" rel="nofollow"><code>MultiIndex</code></a> is called first and second columns and if first level has duplicates by default it 'sparsified' the higher levels of the indexes to make the console output a ...
2
2016-10-10T05:09:48Z
[ "python", "pandas" ]
django-if template doesnt work properly
39,951,616
<p>I have a list of stations and I have to display stations from 'start'. start and stop contain station ids. I am trying in this way but when I run all I get is a blank page. showtrain.html :-</p> <pre><code> &lt;table&gt; &lt;tr&gt; {% for st in st_list %} {% if st.station_id &gt;= start %} &lt;td&gt; {{...
-2
2016-10-10T05:11:05Z
39,955,495
<p>as stated by RemcoGerlich the problem lies in mismatched datatype. the value of start returned from form is string type and station_id is integer. if cannot compare them and hence control doesnt enter if statements so nothing gets printed</p>
0
2016-10-10T09:43:50Z
[ "python", "django" ]
Django Integrity Error in Bulk Import via CSV in Admin
39,951,637
<p>I am trying to implement a CSV Import in Django Admin and save bulk data corresponding to the CSV file's rows. I have a model <code>Employee</code> with a <code>OneToOneField</code> to Django's <code>Auth</code> model. I have written a custom Form that accepts a csv file. However, when I call the super().save() meth...
1
2016-10-10T05:14:10Z
39,951,711
<p>Since you’re doing your own save, you don’t need to call save on the Super form. Typically when you have foreign key fields that you need to fill in like this, you use commit=False to get an instance of the unsaved model., but you can do either of these:</p> <pre><code>def save(self, commit=True, *args, **kwar...
3
2016-10-10T05:22:48Z
[ "python", "django", "csv" ]
Python - Create multiple folders from CSV file
39,951,684
<p>I want to create multiple folders/directories (if they don't exist) using information from a CSV file.</p> <p>I have the information from csv as follows:</p> <pre><code> Column0 Column1 Column2 Column3 51 TestName1 0 https://siteAdress//completed/file.txt 53 TestName2 0 https://siteAdress//com...
0
2016-10-10T05:20:00Z
39,952,538
<p>The following approach should help get you started:</p> <ol> <li>Open the CSV file and skip the header row.</li> <li>Read a row, splitting it into named columns.</li> <li>If the <code>file_url</code> contains <code>input</code>, use a sub folder of <code>input</code>, etc.</li> <li>Create a folder based on <code>ou...
0
2016-10-10T06:40:15Z
[ "python", "csv" ]
Python simple interest calculation
39,951,705
<p>I am trying to calculate how much monthly payment in order to pay off a loan in 12 month. use $10 as incremental.</p> <pre><code>Payment = 0 balance = float (1200) interest = float (0.18) MonthlyInt = interest/12.0 while balance &gt; 0 : Payment = Payment + 10 month = 0 while month &lt; 12 and balance...
0
2016-10-10T05:22:09Z
39,952,051
<p>The main things generating the difference are: </p> <ul> <li>The balance should be reset to 1200 before looping through the 12 months again</li> <li>The payment should be deducted from the balance before calculating the interest</li> </ul> <p>A couple smaller python things are:</p> <ul> <li><code>float()</code> i...
3
2016-10-10T05:56:35Z
[ "python" ]
click iteration fails in selenium
39,951,766
<p>Im trying to translate user comments from tripadvisor. So the scraper reads the link, then one by one iterates through each of the comments and translates them. But my code stops after translating the first comment itself.</p> <pre><code>from selenium import webdriver from selenium.webdriver.common.by import By imp...
1
2016-10-10T05:28:07Z
39,951,801
<p>try this:</p> <pre><code>from selenium import webdriver from selenium.webdriver.common.by import By import time from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC driver = webdriver.Chrome() driver.maximize_window() url="https://www.tripadvisor....
1
2016-10-10T05:32:32Z
[ "python", "selenium", "web-scraping" ]
click iteration fails in selenium
39,951,766
<p>Im trying to translate user comments from tripadvisor. So the scraper reads the link, then one by one iterates through each of the comments and translates them. But my code stops after translating the first comment itself.</p> <pre><code>from selenium import webdriver from selenium.webdriver.common.by import By imp...
1
2016-10-10T05:28:07Z
39,952,293
<p>I tried the same code of yours just increased the sleep time and list is getting traversed through the list and comments are also getting translated </p> <p>Note: I tried the program on Firefox</p> <pre><code>from selenium import webdriver from selenium.webdriver.common.by import By import time driver = webdriver...
1
2016-10-10T06:18:29Z
[ "python", "selenium", "web-scraping" ]
Finding subset of dataframe rows that maximize one column sum while limiting sum of another
39,951,768
<p>A beginner to pandas and python, I'm trying to find select the 10 rows in a dataframe such that the following requirements are fulfilled:</p> <ol> <li>Only 1 of each category in a categorical column</li> <li>Maximize sum of a column</li> <li>While keeping sum of another column below a specified threshold</li> </ol>...
0
2016-10-10T05:28:45Z
39,951,826
<p>IIUC you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow"><code>groupby</code></a> with aggregating <code>sum</code>:</p> <pre><code>df1 = df.groupby('category', as_index=False).sum() print (df1) category value cost 0 A 70 2450 1 ...
0
2016-10-10T05:35:12Z
[ "python", "algorithm", "pandas", "numpy", "data-science" ]
Finding subset of dataframe rows that maximize one column sum while limiting sum of another
39,951,768
<p>A beginner to pandas and python, I'm trying to find select the 10 rows in a dataframe such that the following requirements are fulfilled:</p> <ol> <li>Only 1 of each category in a categorical column</li> <li>Maximize sum of a column</li> <li>While keeping sum of another column below a specified threshold</li> </ol>...
0
2016-10-10T05:28:45Z
40,125,521
<p>This is a linear programming problem. For each POS, you're trying to maximize individual OPW while total salary across the entire team is subject to a constraint. You can't solve this with simple pandas operations, but <a href="https://pythonhosted.org/PuLP/" rel="nofollow">PuLP</a> could be used to formulate and so...
1
2016-10-19T08:03:52Z
[ "python", "algorithm", "pandas", "numpy", "data-science" ]
I want to trigger a response at different points in a loop
39,952,000
<p>I have created a task on Psychopy in which beads a drawn from a jar. 50 different beads are drawn and after each bead the participant is asked to make a probability rating. The task is looped from an excel file but it takes too long to do 50 ratings. I was hoping to get ratings for the first 10 beads. Then draw up a...
1
2016-10-10T05:51:40Z
39,952,074
<p>You should loop only once, but perform all checks inside that one loop:</p> <pre><code>for row_index, rows in (beads_params_pinkbluegreyratingparamters.xlsx): if (row_index &lt; 10): rows.ratingscale(0:10) elif (row_index &gt;=10 and row_index &lt;20): rows.ratingscale(12:20:2) rows....
1
2016-10-10T05:59:00Z
[ "python", "excel", "psychopy" ]
Extract specific XML tags Values in python
39,952,139
<p>I have a XML file which contains tags like these. </p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8" standalone="yes"?&gt; &lt;DataFlows&gt; &lt;DataFlow id="ABC"&gt; &lt;Flow name="flow4" type="Ingest"&gt; &lt;Ingest dataSourceName="type1" tableName="table1"&gt; ...
0
2016-10-10T06:04:58Z
39,953,268
<p>First of all check if your XML is well formatted. You are missing a root tag and you got wrong double quotes for example here <code>&lt;Flow name=“flow4" type="Ingest"&gt;</code></p> <p>IN your code you are correctly grabbing the dataflows.</p> <p>You dont need to query the DOMTree again for the flows, you can c...
0
2016-10-10T07:31:05Z
[ "python", "xml" ]