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
Sampling from a pandas dataframe non-repetitively within a loop
38,208,095
<p>I've simplified the code as much as I can but it's still quite long, it should illustrate the problem. </p> <p>I'm sampling weather data from a dataframe:</p> <pre><code>import numpy as np import pandas as pd #dataframe dates = pd.date_range('19510101',periods=16000) data = pd.DataFrame(data=np.random.randint(0,...
1
2016-07-05T16:13:13Z
38,208,490
<p>You could create a second dataframe from your index and then sample it.</p> <pre><code>df_index = pd.DataFrame(index) coldseq = df_index.sample(5) coldseq.apply(lambda x: df.append("Year == '{0}' and Season == '{1}'".format(x[0], x[1])), axis = 1) # or similar to append the query </code></pre>
0
2016-07-05T16:36:39Z
[ "python", "pandas", "dataframe" ]
Sampling from a pandas dataframe non-repetitively within a loop
38,208,095
<p>I've simplified the code as much as I can but it's still quite long, it should illustrate the problem. </p> <p>I'm sampling weather data from a dataframe:</p> <pre><code>import numpy as np import pandas as pd #dataframe dates = pd.date_range('19510101',periods=16000) data = pd.DataFrame(data=np.random.randint(0,...
1
2016-07-05T16:13:13Z
38,242,920
<p>Figured it out, embedded the loops and reset the counters to 0 within the loop:</p> <pre><code>cold_ctr = 0 #variable to count from (1 is winter, 2 spring, 3 summer, 4 autumn) coldseq = [] #blank list df = [] #number of cold years for i in range (5): #change number here for number of cold years for yrlist in c...
0
2016-07-07T10:14:58Z
[ "python", "pandas", "dataframe" ]
Keep only one element of each group of elements who match each other
38,208,108
<p>Suppose I have an object of the structure:</p> <pre><code>class Obj: def match(other): return check_match(self, other) </code></pre> <p>For example, <code>check_match</code> could check for overlap or for equality or for "is friend".</p> <p>Now I'll have a list of those objects:</p> <pre><code>objList = cr...
1
2016-07-05T16:13:53Z
38,208,305
<p>Python has a type of <code>contains</code> method that works with the following syntax: <code>if x in y:</code> Use it to determine if a list contains an obj</p> <pre><code>a = ["a", "b", "c", "d", "d"] b = ["c", "c", "d", "e", "f"] c = [] for member in a: if member in b and member not in c: c.append(member)...
-2
2016-07-05T16:25:21Z
[ "python" ]
Keep only one element of each group of elements who match each other
38,208,108
<p>Suppose I have an object of the structure:</p> <pre><code>class Obj: def match(other): return check_match(self, other) </code></pre> <p>For example, <code>check_match</code> could check for overlap or for equality or for "is friend".</p> <p>Now I'll have a list of those objects:</p> <pre><code>objList = cr...
1
2016-07-05T16:13:53Z
38,208,425
<h2>Regarding: What is the pythonic way to do so?</h2> <p>The pythonic way is to rename your <code>match</code> method to <code>__eq__</code>.</p> <p>Then you can do things like <code>element in list</code> with your custom object.</p> <p>A very pythonic way to make a list contain unique items is then:</p> <pre><co...
3
2016-07-05T16:32:25Z
[ "python" ]
Processing large XLSX file in python
38,208,137
<p>I have a large xlsx Excel file (56mb, 550k rows) from which I tried to read the first 10 rows. I tried using <code>xlrd</code>, <code>openpyxl</code>, and <code>pyexcel-xlsx</code>, but they always take more than 35 mins because it loads the whole file in memory.</p> <p>I unzipped the Excel file and found out that ...
-2
2016-07-05T16:15:13Z
38,208,911
<p>Use <a href="http://openpyxl.readthedocs.io/en/default/optimized.html" rel="nofollow">openpyxl's read-only mode</a> to do this. </p> <p>You'll be able to work with the relevant worksheet instantly.</p>
0
2016-07-05T17:03:48Z
[ "python", "excel", "xlsx", "openpyxl", "xlrd" ]
Processing large XLSX file in python
38,208,137
<p>I have a large xlsx Excel file (56mb, 550k rows) from which I tried to read the first 10 rows. I tried using <code>xlrd</code>, <code>openpyxl</code>, and <code>pyexcel-xlsx</code>, but they always take more than 35 mins because it loads the whole file in memory.</p> <p>I unzipped the Excel file and found out that ...
-2
2016-07-05T16:15:13Z
38,210,167
<p>Here is it, i found a solution. The fastest way to read an xlsx sheet.</p> <p>56mb file with over 500k rows and 4 sheets took 6s to proceed.</p> <pre><code>import zipfile from bs4 import BeautifulSoup paths = [] mySheet = 'Sheet Name' filename = 'xlfile.xlsx' file = zipfile.ZipFile(filename, "r") for name in fil...
0
2016-07-05T18:24:16Z
[ "python", "excel", "xlsx", "openpyxl", "xlrd" ]
Calling python script in web2py framework over webserver
38,208,242
<p>I have NGINX UWSGI and WEB2PY installed on the server. Web2py application performing only one function by accessing the database and printing rows in the table.</p> <pre><code>def fetch(): import psycopg2 conn = psycopg2.connect(database="postgres", user="postgres", ...
0
2016-07-05T16:21:28Z
38,208,461
<p>My guess is that your MySQL service doesn't allow remote access. Could you check your MySQL configuration?</p> <pre><code>vim /etc/mysql/my.cnf </code></pre> <p>Comment out the following lines.</p> <pre><code>#bind-address = 127.0.0.1 #skip-networking </code></pre> <p>If there is no skip-networking lin...
0
2016-07-05T16:34:43Z
[ "python", "nginx", "web2py" ]
Calling python script in web2py framework over webserver
38,208,242
<p>I have NGINX UWSGI and WEB2PY installed on the server. Web2py application performing only one function by accessing the database and printing rows in the table.</p> <pre><code>def fetch(): import psycopg2 conn = psycopg2.connect(database="postgres", user="postgres", ...
0
2016-07-05T16:21:28Z
38,241,797
<p>Forgive the stupid question but have you checked if the module is available on your server?</p> <p>When you say that the error appears in your hello function as soon as you try to import, it's the same directive <code>import psycopg2</code>?</p> <p>Try this: Assuming that fetch() it's defined on <code>controllers/...
0
2016-07-07T09:21:36Z
[ "python", "nginx", "web2py" ]
Determine available memory in pure Python
38,208,351
<p>I am aware of the <a href="https://github.com/giampaolo/psutil" rel="nofollow">psutil</a> package which provides (along with many other things) a way to access information about system memory, including the amount of available memory (<code>psutil.virtual_memory().available</code>). How would I go about querying av...
0
2016-07-05T16:28:33Z
38,208,477
<p>Already sort of answered <a href="http://stackoverflow.com/a/17718729/6151889">here</a>, although this method includes reading the <code>/proc/meminfo</code> file, which comes on <em>most</em> Linux/Unix distributions.</p> <p>As per other operating systems, it looks like psutil is your only option, unless Windows h...
0
2016-07-05T16:35:41Z
[ "python", "memory", "operating-system" ]
How to stream in and manipulate a large data file in python
38,208,389
<p>I have a relatively large (1 GB) text file that I want to cut down in size by summing across categories:</p> <pre><code>Geography AgeGroup Gender Race Count County1 1 M 1 12 County1 2 M 1 3 County1 2 M 2 0 </code></pre> <p>To:</p> <pre><code>Geography Count Count...
3
2016-07-05T16:30:23Z
38,208,600
<p>You can use <a href="http://dask.pydata.org/en/latest/dataframe.html" rel="nofollow"><code>dask.dataframe</code></a>, which is syntactically similar to <code>pandas</code>, but performs manipulations out-of-core, so memory shouldn't be an issue:</p> <pre><code>import dask.dataframe as dd df = dd.read_csv('my_file....
4
2016-07-05T16:43:17Z
[ "python", "pandas", "dataframe", "itertools" ]
How to stream in and manipulate a large data file in python
38,208,389
<p>I have a relatively large (1 GB) text file that I want to cut down in size by summing across categories:</p> <pre><code>Geography AgeGroup Gender Race Count County1 1 M 1 12 County1 2 M 1 3 County1 2 M 2 0 </code></pre> <p>To:</p> <pre><code>Geography Count Count...
3
2016-07-05T16:30:23Z
38,209,038
<p>I do like @root's solution, but i would go bit further optimizing memory usage - keeping only aggregated DF in memory and reading only those columns, that you really need:</p> <pre><code>cols = ['Geography','Count'] df = pd.DataFrame() chunksize = 2 # adjust it! for example --&gt; 10**5 for chunk in (pd.read_csv...
2
2016-07-05T17:11:36Z
[ "python", "pandas", "dataframe", "itertools" ]
QlineEdit::text() not returning the text entered when push button is clicked and the object name of that particular QlineEdit is lineEdit
38,208,402
<p>I have created three <code>LineEdits</code> in my <code>Alert.ui</code> file. My first <code>LineEdit</code> object name is <code>lineEdit</code> from where I need to read the text when the <code>pushButton</code> is clicked. But when I checked by printing a word reach, I understood that it never enters the <code>on...
0
2016-07-05T16:31:03Z
38,210,231
<p>I'm still not sure what's going on in your code, but from first glance I can spot the following issue:</p> <p>You never connect your first QLineEdit to the <code>onClicked</code> method.</p>
0
2016-07-05T18:28:14Z
[ "python", "pyqt4" ]
Colon, None, slice(None) in numpy array indexers
38,208,416
<p>As for <code>a = np.arange(24).reshape(2,3,4)</code></p> <p><code>a[0,:,1]</code> or <code>a[0,slice(None),1]</code> outputs <code>array([1, 5, 9])</code></p> <p>while <code>a[0,None,1]</code> gives <code>array([[4, 5, 6, 7]])</code></p> <p>Could sb explain the latter?</p>
2
2016-07-05T16:32:00Z
38,208,610
<p>Using a raw <code>None</code> (not in <code>slice</code>) is the same thing as using <a href="http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#numpy.newaxis" rel="nofollow"><code>np.newaxis</code></a>, of which it is but an alias.</p> <p>In your case:</p> <ul> <li><code>a[0,None,1]</code> is like a<c...
4
2016-07-05T16:43:56Z
[ "python", "numpy", "indexing" ]
Colon, None, slice(None) in numpy array indexers
38,208,416
<p>As for <code>a = np.arange(24).reshape(2,3,4)</code></p> <p><code>a[0,:,1]</code> or <code>a[0,slice(None),1]</code> outputs <code>array([1, 5, 9])</code></p> <p>while <code>a[0,None,1]</code> gives <code>array([[4, 5, 6, 7]])</code></p> <p>Could sb explain the latter?</p>
2
2016-07-05T16:32:00Z
38,208,615
<p><code>a[0,None,1]</code> is the same as <code>a[0, 1]</code> but with an <strong>extra</strong> axis in the result.</p> <blockquote> <p>The <code>newaxis</code> object can be used in all slicing operations to create an axis of length one. <code>:const: newaxis</code> is an alias for <code>‘None’</code>, and...
1
2016-07-05T16:44:07Z
[ "python", "numpy", "indexing" ]
Efficiently converting numpy array to matrix
38,208,555
<p>I have data in the following format:</p> <pre><code>['FACTOR_1','FACTOR_2",'VALUE"] ['A' ,'A' ,2.0 ] ['A' ,'B' ,3.0 ] ['A' ,'C' ,2.2 ] ['A' ,'D' ,2.6 ] ['B' ,'A' ,2.6 ] ['B' ,'B' ,1.0 ] ['B' ,'C' ,6.0 ] ['B' ...
1
2016-07-05T16:40:29Z
38,215,656
<p>There is an error in your code, which I corrected with the <code>sub_data</code> array line. I also streamlined the code in some obvious ways:</p> <pre><code>def foo(cov_data): factors = np.unique(cov_data['FACTOR_1']) no_of_factors = factors.shape[0] cov_matrix = np.zeros((no_of_factors, no_of_factors...
1
2016-07-06T02:48:08Z
[ "python", "numpy", "scikit-learn" ]
Moved .py file to another folder, now getting TKinter error only in new folder
38,208,578
<p>I am trying to automate a few analysis processes with Python. At the moment, I have a program that only goes through the directory it is located in, count the number of CSVs and XLSX documents, and prompt the user for a password s/he would like to use to encrypt them. The actual encryption will be done by a library ...
0
2016-07-05T16:41:40Z
38,208,693
<p>It's due to having a <code>while True</code> loop around it- you get the contents of <code>pwfield</code>, if they're good you go to your <code>else</code>, and in your <code>else</code> you destroy the root, and by extension all its children. The decimal value is Tcl's identifier for the widget, and since you destr...
1
2016-07-05T16:49:11Z
[ "python", "tkinter" ]
While looping issue in Python 3.5.1
38,208,640
<p>Using Python 3.5.1. </p> <p>I am trying to build a while loop, which iterates a function until a certain number of prime numbers has been appended into a list. I have previously written a function which takes in a number, evaluates whether or not it is a prime and adds it to a list if it is a prime:</p> <pre><code...
1
2016-07-05T16:45:53Z
38,208,789
<p>The problem is that you are not resetting <code>l1</code> after each while loop iteration. Furthermore, you are using <code>numberofprimes</code> as your while loop condition while assigning the number of primes value to <code>numofprimes</code></p> <pre><code>import numpy as NP n=10 l2=[] numberofprimes = 0 while ...
4
2016-07-05T16:55:08Z
[ "python" ]
ryu (SDN) traffic controller from (example) Host 1
38,208,689
<p>I created a simple network in the <code>mininet</code> environment with the following command:</p> <pre><code>$ sudo mn --topo single,3 --mac --controller remote --switch ovsk </code></pre> <p>I want use <code>RYU CONTROLLER</code> to calculate bandwidth traffic on special port of switch. I'm thinking of using an ...
0
2016-07-05T16:49:04Z
39,662,482
<p>You have to add two method in your controller: 1) a method that requests stats 2) a method that captures the answers from switches. </p> <p>The method for answering stats is the following:</p> <pre><code>def send_flow_stats_request(self, datapath): ofp = datapath.ofproto ofp_parser = datapath.ofproto_par...
1
2016-09-23T13:50:13Z
[ "python", "linux", "mininet", "sdn", "ryu" ]
Create pandas timeseries from list of dictionaries with many keys
38,208,697
<p>I have multiple timeseries that are outputs of various algorithms. These algorithms can have various parameters and they produce timeseries as a result:</p> <pre><code>timestamp1=1; value1=5; timestamp2=2; value2=8; timestamp3=3; value3=4; timestamp4=4; value4=12; resultsOfAlgorithms=[ { 'algorithm':'minmax', 'par...
2
2016-07-05T16:49:33Z
38,209,436
<p>So there are two options here, one is to clean up the dict first, then convert it easily to a dataframe, the second is to convert it to a dataframe, then clean up the column that will have nested lists in it. For the first solution, you can just restructure the dict like this:</p> <pre><code>import pandas as pd fr...
1
2016-07-05T17:37:25Z
[ "python", "pandas" ]
Matplotlib Plot Lines with Colors Through Colormap
38,208,700
<p>I am plotting multiple lines on a single plot and I want them to run through the spectrum of a colormap, not just the same 6 or 7 colors. The code is akin to this:</p> <pre><code>for i in range(20): for k in range(100): y[k] = i*x[i] plt.plot(x,y) plt.show() </code></pre> <p>Both with colormap ...
0
2016-07-05T16:49:39Z
38,219,022
<p>The Matplotlib colormaps accept an argument (<code>0..1</code>, scalar or array) which you use to get colors from a colormap. For example:</p> <pre><code>col = pl.cm.jet([0.25,0.75]) </code></pre> <p>Gives you an array with (two) RGBA colors:</p> <blockquote> <p>array([[ 0. , 0.50392157, 1. ...
0
2016-07-06T08:02:29Z
[ "python", "matplotlib" ]
Python write array to float32
38,208,863
<p>Hi this is I suppose a simple question,</p> <p>I have an list of len = 259200, how do I write it to a plain binary file?</p> <p>Many thanks</p>
-3
2016-07-05T17:00:38Z
38,208,902
<p>You can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.tofile.html" rel="nofollow"><code>.tofile</code></a>.</p> <pre><code>with open('whatever', 'w') as f: arr.tofile(f) </code></pre>
3
2016-07-05T17:03:14Z
[ "python", "binary" ]
Invalid syntax when trying to map(lambda..)
38,208,883
<p>I'm writing a function that loops through a list of numbers, and returns a list of the sums of each number's divisors. I'm trying to trim my function down a little, and learn <code>map(lambda..)</code> at the same time.</p> <pre><code>def DoWork(nums): sums = [] for n in nums: divisors = [] ...
1
2016-07-05T17:02:16Z
38,208,952
<p>A python <code>lambda</code> does not work that way. It is should be a simple substitute for a function that takes a value and returns another value. You can not have <code>if</code> conditions floating in it.</p> <pre><code>updated_range = filter(lambda x: not n%x, range(1,n+1)) map(lambda i: divisors.appens(i), ...
2
2016-07-05T17:06:44Z
[ "python", "lambda" ]
Invalid syntax when trying to map(lambda..)
38,208,883
<p>I'm writing a function that loops through a list of numbers, and returns a list of the sums of each number's divisors. I'm trying to trim my function down a little, and learn <code>map(lambda..)</code> at the same time.</p> <pre><code>def DoWork(nums): sums = [] for n in nums: divisors = [] ...
1
2016-07-05T17:02:16Z
38,208,990
<p>Typically, we use <code>map()</code> in situations where we have a sequence of things [1] and want to transform it into another sequence -- of the same length -- by applying a function to each element.</p> <p>You can still use it to find the sum of divisors, but I would argue that it's not the most suitable tool fo...
2
2016-07-05T17:08:47Z
[ "python", "lambda" ]
Invalid syntax when trying to map(lambda..)
38,208,883
<p>I'm writing a function that loops through a list of numbers, and returns a list of the sums of each number's divisors. I'm trying to trim my function down a little, and learn <code>map(lambda..)</code> at the same time.</p> <pre><code>def DoWork(nums): sums = [] for n in nums: divisors = [] ...
1
2016-07-05T17:02:16Z
38,209,099
<p>The syntax error is rising from incomplete 'if not' logic, where an 'else' clause is required.</p> <pre><code>def DoWork(nums): sums = [] for n in nums: divisors = [] map(lambda i: divisors.append(i) if not (n%i) else 1, range(1,n+1)) sums.append(sum(divisors)) return sums </code...
1
2016-07-05T17:16:45Z
[ "python", "lambda" ]
Finding the original positions of words in a sentence when the word occurs more than once
38,209,020
<p>I need to find the positions of words in a sentence the user inputs and if the word occurs more than once, only print the first time that word occurs</p> <p>I have the code so far-</p> <pre><code>sentence=input("Enter a sentence: ") sentence=sentence.lower() words=sentence.split() place=[] for c,a in enumerate(wo...
2
2016-07-05T17:10:28Z
38,209,210
<p>If you are using python 2, then <code>raw_input</code> instead of <code>input</code> else it'll eval. That isn't a problem, just an observation (you're probably using python 3 then, so I'll leave it that way). </p> <p>You could create a dict to track word counts and positions found. This is basically a dict of lis...
2
2016-07-05T17:23:49Z
[ "python" ]
Finding the original positions of words in a sentence when the word occurs more than once
38,209,020
<p>I need to find the positions of words in a sentence the user inputs and if the word occurs more than once, only print the first time that word occurs</p> <p>I have the code so far-</p> <pre><code>sentence=input("Enter a sentence: ") sentence=sentence.lower() words=sentence.split() place=[] for c,a in enumerate(wo...
2
2016-07-05T17:10:28Z
38,209,692
<p>Your code needs some modifications to achieve what you are trying to do:</p> <ul> <li><p><code>if words.count(a)&gt;2</code> : It should be <code>if words.count(a)&gt;1</code> since count would be more than 1 if the word is repeated.</p></li> <li><p><code>place.append(words.index(a+1))</code> : It should be <code>p...
1
2016-07-05T17:54:13Z
[ "python" ]
Finding the original positions of words in a sentence when the word occurs more than once
38,209,020
<p>I need to find the positions of words in a sentence the user inputs and if the word occurs more than once, only print the first time that word occurs</p> <p>I have the code so far-</p> <pre><code>sentence=input("Enter a sentence: ") sentence=sentence.lower() words=sentence.split() place=[] for c,a in enumerate(wo...
2
2016-07-05T17:10:28Z
38,210,983
<p>Split the string</p> <pre><code>&gt;&gt;&gt; s = '''and but far and so la ti but''' &gt;&gt;&gt; s = s.split() &gt;&gt;&gt; s ['and', 'but', 'far', 'and', 'so', 'la', 'ti', 'but'] </code></pre> <p>use <code>set</code> to find the unique words and use the <code>list.index</code> method to find the first position of...
0
2016-07-05T19:14:39Z
[ "python" ]
python how to use dictionary
38,209,025
<p>I am trying to read data from some files and save those into dictionary The file that I am reading looks like below</p> <pre><code>file_1.txt line 1: Given Problem1, Incorrect Answer, Correct Answer, Rule line 2: ___blank___ , Incorrect_Answer line 3: ___blank___ , Incorrect_Answer line 4: Given Problem2, Incorre...
-2
2016-07-05T17:10:41Z
38,209,272
<p>You want to start with a main output result container and a question placeholder:</p> <pre><code>&gt;&gt;&gt; result = {} &gt;&gt;&gt; question = None </code></pre> <p>Then you do your normal processing of each line while watching for question changes, appending incorrect responses:</p> <pre><code>&gt;&gt;&gt; fo...
0
2016-07-05T17:26:47Z
[ "python", "dictionary" ]
python how to use dictionary
38,209,025
<p>I am trying to read data from some files and save those into dictionary The file that I am reading looks like below</p> <pre><code>file_1.txt line 1: Given Problem1, Incorrect Answer, Correct Answer, Rule line 2: ___blank___ , Incorrect_Answer line 3: ___blank___ , Incorrect_Answer line 4: Given Problem2, Incorre...
-2
2016-07-05T17:10:41Z
38,209,384
<p>I will assume that - as you are writing above - the question and answers are separated by commas. </p> <pre><code>alldata = [] # scan through the file, but skip the first two lines # that contain metadata (data headers) for line in open(thatfile.txt,'r').readlines()[2:]: lineparts = line.split(',') # or how el...
0
2016-07-05T17:34:28Z
[ "python", "dictionary" ]
Rasperry pi reboots when running program
38,209,074
<p>My raspberry pi reboots when I run the follow code using: sudo python robot.py My raspberry pi is attached to 4 motors, a pan and tilt assembly and an ultrasonic sensor through a robohat controller ( <a href="http://4tronix.co.uk/store/index.php?rt=product/product&amp;product_id=547/%22robohat%22" rel="nofollow">Rob...
2
2016-07-05T17:14:39Z
38,209,419
<p>Give your RPi a stronger AC adapter. It should have minimally 1.2 A.</p> <p>Also, make sure your servoes aren't powered from RPi, the ground has to be the same and only servo command line connected to RPi pin. There is also a fact that RPi delivers 3.5V output to its GPIO, while most servoes require 5V on power and...
0
2016-07-05T17:36:26Z
[ "python", "raspberry-pi", "raspbian" ]
Unexpected Result with MAP
38,209,092
<p>I was expecting the code under header 'New List with MAP' below to return a list just like the for loop and the list comprehension....but alas, it does not. I get, <code>&lt;map object at 0X000...8C1CD30&gt;</code> instead. How do i go from this to my list?</p> <p><strong>New List with Map</strong></p> <pre><cod...
3
2016-07-05T17:16:06Z
38,209,145
<p><code>map</code> returns an iterator. If you want the values in a list, you have to convert it to a list:</p> <pre><code>new_li = list(map(lambda i: '{0}\n'.format(i), list_a)) </code></pre> <p>or</p> <pre><code>new_li = list(map('{0}\n'.format, list_a)) </code></pre>
3
2016-07-05T17:20:15Z
[ "python", "python-3.x" ]
Coding basics for Cartesian Coordinate Analysis
38,209,148
<p>I am incredibly new to all of this and need to learn some basic info to write a code in Python. Going through tutorials is good and all but I tend to get a little overwhelmed with the possibilities and irrelevant information.</p> <p>The code I need to write must be able to determine the collinearity of three random...
-1
2016-07-05T17:20:30Z
38,209,460
<p>To do this you don't really need any "tools", so to speak. You can check if three points are collinear by making sure that the lines that are created by:</p> <pre><code>Point A to Point B, Point B to Point C, Point A to Point C, </code></pre> <p>have the same slope. </p> <p>To do this, you need to take</p> <pre>...
0
2016-07-05T17:39:33Z
[ "python", "graph", "statistics", "cartesian" ]
if/elif questions not working?
38,209,152
<p>I am very new to Python and preparing to start it as a GCSE. I have been trying to do a capital of France question set in school with different responses for some answers, but it has not been working. The syntax error 'unindent does not match any outer indentation level' comes up after the response for when answers ...
-3
2016-07-05T17:20:44Z
38,209,193
<p>Your indentation was off in the if/elif/else block</p> <p>If you're assigning a variable, it should be one <code>=</code> not <code>==</code> </p> <p>If you want to prompt for the correct answer again, you have to reassign the variable <code>answer</code> (<code>answer = input(....)</code>)</p> <p>Also you may wa...
3
2016-07-05T17:23:07Z
[ "python" ]
if/elif questions not working?
38,209,152
<p>I am very new to Python and preparing to start it as a GCSE. I have been trying to do a capital of France question set in school with different responses for some answers, but it has not been working. The syntax error 'unindent does not match any outer indentation level' comes up after the response for when answers ...
-3
2016-07-05T17:20:44Z
38,209,230
<p>Simple! You have spaces before elif and else, simply remove them and it should be fine! One more thing, when you say</p> <pre><code>answer==input("Enter your answer") </code></pre> <p>it should be</p> <pre><code>answer = input("Enter your answer") </code></pre>
0
2016-07-05T17:24:39Z
[ "python" ]
if/elif questions not working?
38,209,152
<p>I am very new to Python and preparing to start it as a GCSE. I have been trying to do a capital of France question set in school with different responses for some answers, but it has not been working. The syntax error 'unindent does not match any outer indentation level' comes up after the response for when answers ...
-3
2016-07-05T17:20:44Z
38,209,261
<p>You should not use input(), but instead use raw_input().</p>
-1
2016-07-05T17:26:18Z
[ "python" ]
if/elif questions not working?
38,209,152
<p>I am very new to Python and preparing to start it as a GCSE. I have been trying to do a capital of France question set in school with different responses for some answers, but it has not been working. The syntax error 'unindent does not match any outer indentation level' comes up after the response for when answers ...
-3
2016-07-05T17:20:44Z
38,209,267
<p>At first when you want to save something in variable, you just use one = not == of them</p> <p>At second you need to have all elif and if on same place dont use tabulators python is very sensitive on this</p> <p>And for the answer you need to do loop maybe while to repeat until they write the right question</p>
0
2016-07-05T17:26:31Z
[ "python" ]
if/elif questions not working?
38,209,152
<p>I am very new to Python and preparing to start it as a GCSE. I have been trying to do a capital of France question set in school with different responses for some answers, but it has not been working. The syntax error 'unindent does not match any outer indentation level' comes up after the response for when answers ...
-3
2016-07-05T17:20:44Z
38,209,392
<p>In addition to the previous answers, I just wanted to point out that it is better to use a while loop and assign the value to 'answer' within the while loop. This way, you can also insert a 'break' statement, that will terminate the program once you digit the word 'exit' or provide the right answer. Here is the code...
1
2016-07-05T17:34:53Z
[ "python" ]
Creating an Installation Package That Grabs Python Modules From the Web
38,209,343
<p>I am trying to create an installation package for my program that I can send to other people who don't have any programming background and presumably cannot use the command line. The program itself is fairly user friendly, but it requires the installation of several Python packages from the Python Package Index to f...
0
2016-07-05T17:32:01Z
38,213,178
<p>Ultimately, I decided it was simpler to just put all of the source code and directory trees in a ZIP file and give the user careful instructions on how to add those trees to their PATH. Thanks anyway for the help guys.</p>
0
2016-07-05T21:36:12Z
[ "python", "windows", "installation", "iexpress" ]
What do the square brackets around parameters mean in the official documentation?
38,209,396
<p>I don't know how to interpret this notation:</p> <pre><code>timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]]) </code></pre> <p><strong>Source:</strong> <a href="https://docs.python.org/2/library/datetime.html#timedelta-objects" rel="nofollow">https://docs.python.org/2/libra...
1
2016-07-05T17:35:18Z
38,209,463
<p>This notation is described in the documentation <a href="https://docs.python.org/2/reference/introduction.html#notation">introduction</a>:</p> <blockquote> <p>a phrase enclosed in square brackets (<code>[ ]</code>) means zero or one occurrences (in other words, the enclosed phrase is optional).</p> </blockquote> ...
6
2016-07-05T17:39:39Z
[ "python", "python-2.7", "documentation" ]
Query database based on id in django
38,209,529
<p>I have the following Model in django.</p> <pre><code>class Choices(models.Model): question = models.CharField(max_length=200) option1 = models.CharField(max_length=200) option2 = models.CharField(max_length=200) option3 = models.CharField(max_length=200) </code></pre> <p>I would like to display in ...
-1
2016-07-05T17:43:44Z
38,209,642
<p>You should get the <code>Choice</code> inside your view and then pass it to your template. Example:</p> <p><strong>view.py</strong></p> <pre><code>from django.shortcuts import get_object_or_404, render def my_view(request, choice_id): choice = get_object_or_404(Choice, id=choice_id) return render(request,...
0
2016-07-05T17:50:39Z
[ "python", "html", "django", "sqlite" ]
how to avoid removing 0 from msb in python panda dataframe
38,209,540
<p>i have data in column like <code>0123456789</code> after reading from a file it will get like <code>123456789</code> where column name is <code>msisdn</code></p> <p>how to fix this issue</p> <p>am using the pandas script as follows</p> <pre><code>#!/usr/bin/env python import gc import pandas csv1 = pandas.read_...
2
2016-07-05T17:44:36Z
38,209,614
<p>You can cast column <code>msisdn</code> to <code>string</code> by parameter <code>dtype</code> in <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow"><code>read_csv</code></a>:</p> <pre><code>temp=u"""msisdn 0123456789 0123456789""" #after testing replace io.StringIO(...
1
2016-07-05T17:49:08Z
[ "python", "csv", "pandas", "dataframe" ]
how to avoid removing 0 from msb in python panda dataframe
38,209,540
<p>i have data in column like <code>0123456789</code> after reading from a file it will get like <code>123456789</code> where column name is <code>msisdn</code></p> <p>how to fix this issue</p> <p>am using the pandas script as follows</p> <pre><code>#!/usr/bin/env python import gc import pandas csv1 = pandas.read_...
2
2016-07-05T17:44:36Z
38,237,990
<pre><code>csv1 = pandas.read_csv('/home/subin/Desktop/a.txt',dtype=str) csv2 = pandas.read_csv('/home/subin/Desktop/b.txt',dtype={'MSISDN': str}) merged = pandas.merge(csv1, csv2,left_on=['MSISDN'],right_on=['MSISDN'],how='left',suffixes=('#x', '#y'), sort=True).fillna('0') merged.to_csv("/home/subin/Desktop/amergeb_o...
0
2016-07-07T05:19:29Z
[ "python", "csv", "pandas", "dataframe" ]
python numba: how to slice a column from a numpy array?
38,209,574
<p>I understand that numba supports a number of numpy functions in nopython mode: <a href="http://numba.pydata.org/numba-doc/dev/reference/numpysupported.html" rel="nofollow">http://numba.pydata.org/numba-doc/dev/reference/numpysupported.html</a></p> <p>However, is there a way to slice a column or a row from a numpy a...
2
2016-07-05T17:46:34Z
38,209,868
<p>What version of Numba are you using? With 0.26.0, the following works:</p> <pre><code>import numpy as np import numba as nb @nb.jit(nopython=True) def func(x, mycol): y = x[:,mycol] return y x = np.arange(100).reshape((10,10)) mycol = 2 y = func(x, mycol) print np.allclose(x[:,mycol], y) # True </code>...
2
2016-07-05T18:05:44Z
[ "python", "numpy", "numba" ]
Getting additional character while Converting to UTF-8 Python
38,209,646
<p>I am trying to convert the html encode character as part of the input string to UTF8 in Python. I am getting additional character as Ã. How to get rid of it in python.</p> <p>Example: I supposed to get the output as as "SlimRun&#174;". But, I am getting SlimRun®</p> <p>I am using unescape methond from HTMLPars...
-1
2016-07-05T17:50:51Z
38,209,825
<p>UTF8 is a multibyte encoding so you can encode more than 1 million characters. You have to decode the utf8-encoded string:</p> <pre><code>b'SlimRun\xc2\xae'.decode('utf8') </code></pre>
0
2016-07-05T18:03:23Z
[ "python", "utf-8" ]
How to combine unicode subscript with string formatting
38,209,718
<p>I am trying to get unicode subscripts working with string formatting... I know I can do something like this...</p> <pre><code>&gt;&gt;&gt;print('Y\u2081') Y₁ &gt;&gt;&gt;print('Y\u2082') Y₂ </code></pre> <p>But what i really need is something like this since I need the subscript to iterate over a range. Obvio...
1
2016-07-05T17:55:55Z
38,209,791
<p><code>\uhhhh</code> is an <em>escape syntax</em> in the string literal. You'd have to produce a raw string (where the escape syntax is ignored), then <em>re-apply</em> the normal Python parser handling of escapes:</p> <pre><code>import codecs print(codecs.decode(r'Y\u208{0}'.format(1), 'unicode_escape')) </code></...
2
2016-07-05T18:01:21Z
[ "python", "python-3.x", "unicode", "python-unicode" ]
Duplicates end up in list despite "if statement"
38,209,750
<p>Okay, I was working on a code that would give every possible combination of the scrambled letters you input. Here it is:</p> <pre><code>import random, math words = [] original = raw_input("What do you need scrambled? ") def word_scramble(scrambled): original_length = len(scrambled) loops = math.factoria...
2
2016-07-05T17:58:29Z
38,209,867
<pre><code>if new_word not in words: words.append(("".join(str(x) for x in new_word))) loops -= 1 </code></pre> <p><code>new_word</code> is a list of letters, but <code>words</code> contains strings not lists of letters. They're in different formats, so the check will always succeed.</p> <p>For instance, you ...
3
2016-07-05T18:05:44Z
[ "python", "python-3.x" ]
Duplicates end up in list despite "if statement"
38,209,750
<p>Okay, I was working on a code that would give every possible combination of the scrambled letters you input. Here it is:</p> <pre><code>import random, math words = [] original = raw_input("What do you need scrambled? ") def word_scramble(scrambled): original_length = len(scrambled) loops = math.factoria...
2
2016-07-05T17:58:29Z
38,209,952
<p>How about <code>itertools.permutations</code>?</p> <pre><code>import itertools original = raw_input("What do you need scrambled? ") result = [''.join(s) for s in itertools.permutations(original)] </code></pre>
5
2016-07-05T18:11:25Z
[ "python", "python-3.x" ]
Duplicates end up in list despite "if statement"
38,209,750
<p>Okay, I was working on a code that would give every possible combination of the scrambled letters you input. Here it is:</p> <pre><code>import random, math words = [] original = raw_input("What do you need scrambled? ") def word_scramble(scrambled): original_length = len(scrambled) loops = math.factoria...
2
2016-07-05T17:58:29Z
38,209,983
<p><strong>From the <a href="https://docs.python.org/2.7/library/itertools.html#itertools.permutations" rel="nofollow">doc</a>:</strong></p> <blockquote> <p>itertools.permutations(iterable[, r])</p> <p>Return successive r length permutations of elements in the iterable.</p> <p>If r is not specified or is N...
2
2016-07-05T18:13:28Z
[ "python", "python-3.x" ]
Duplicates end up in list despite "if statement"
38,209,750
<p>Okay, I was working on a code that would give every possible combination of the scrambled letters you input. Here it is:</p> <pre><code>import random, math words = [] original = raw_input("What do you need scrambled? ") def word_scramble(scrambled): original_length = len(scrambled) loops = math.factoria...
2
2016-07-05T17:58:29Z
38,210,427
<p>Disregarding your original question, I can provide a better solution for generating all combinations. Just as a reminder, there is a difference between all possible <em>combinations</em> and <em>permutations</em>. </p> <p>A combination is where the ordering of a subset of elements from some set does not matter. For...
0
2016-07-05T18:41:03Z
[ "python", "python-3.x" ]
PySide QPainter.drawRect() with QBrush offset issue
38,209,792
<p>I'm trying to draw my custom push button which has dimensions 20x20 pixels. I created a class that inherits QPushButton and I have overwritten paintEvent method with this code below:</p> <pre><code>painter = QtGui.QPainter(self) x = self.rect().x() y = self.rect().y() width = self.rect().width() height = self.rec...
0
2016-07-05T18:01:25Z
38,222,315
<p>I think your getting confused about what <code>QPainter::drawRect</code> actually does. From the <a href="http://doc.qt.io/qt-5/qpainter.html#drawRect-2" rel="nofollow">QPainter documentation</a></p> <blockquote> <p>Draws the current rectangle with the current pen and brush.</p> </blockquote> <p>The rectangle i...
1
2016-07-06T10:55:44Z
[ "python", "qt", "pyside" ]
Tastypie: implement resouce DELETE on custom url
38,209,831
<p>I want to implement the deletion of a resource using a custom url. So, instead of allowing the DELETE on the default resource Tastypie url, I've defined a new one. The delete works but I'm still getting an error because I'm sure I'm missing something in my code. The function performing the delete is <code>cancel_rid...
0
2016-07-05T18:03:29Z
38,221,414
<p>So I finally found a solution, even tho I'm not sure it's the best approach, so I'm more than happy if somebody wants to comment it. I've implemented a custom Authorization class which has, among the others, the following methods:</p> <pre><code>class UserObjectsOnlyAuthorization(Authorization) def delete_deta...
0
2016-07-06T10:08:57Z
[ "python", "django", "tastypie" ]
How to make "conda" installer look for "PyPi" packages
38,209,848
<p>I was trying to use <a href="http://conda.pydata.org/docs/using/pkgs.html#managing-packages" rel="nofollow">conda</a> package manager to install my Python packages. Recently I encountered that many of the packages that I required were not present in the Anaconda.org repository, and I had to pip install them. Ref: <a...
2
2016-07-05T18:04:18Z
38,211,438
<p>According to conda skeleton, you can first run </p> <pre><code>conda skeleton pypi package </code></pre> <p>It will generate conda recipe for that package if it is available on PyPi, then</p> <pre><code>conda build package conda install --use-local package </code></pre> <p>It will install the package</p> <p>En...
2
2016-07-05T19:41:19Z
[ "python", "anaconda", "conda" ]
How to change font of arabic numerals as markers in matplotlib scatter plots?
38,209,915
<p>I want to have arabic numerals as markers on my scatter plot. Till this point I have been able to get following code template:</p> <pre><code>plt.figure() plt.scatter(20,20,marker ='o', s=20*2**5, facecolors='r',edgecolors='none',alpha=0.75) plt.scatter(20,20,c='k',marker="$"+str(5)+"$",s=5*2**5) </code></pre> <p>...
0
2016-07-05T18:08:50Z
38,216,896
<p>There is a solution that uses TeX backend, if you are fine with that:</p> <pre><code>import matplotlib matplotlib.rcParams['text.usetex'] = True matplotlib.rcParams['text.latex.preamble'] = [ r'\usepackage{sansmath}', r'\sansmath' ] import matplotlib.pyplot as plt plt.figure() plt.scatter(20,20,marke...
0
2016-07-06T05:32:09Z
[ "python", "matplotlib" ]
How to handle OrderedDict with one entry in Python for loop?
38,210,025
<p>I am using a OrderedDict like this:</p> <pre><code>my_data = [OrderedDict([(u'@pageid', u'1108'), (u'@ns', u'0'), (u'@title', u'H\xf6rspiele f\xfcr Studenten')]), OrderedDict([(u'@pageid', u'989'), (u'@ns', u'0'), (u'@title', u'Impact')]), OrderedDict([(u'@pageid', u'580'), (u'@ns', u'0'), (u'@title', u'Impfgegner'...
2
2016-07-05T18:16:02Z
38,210,124
<p>In the first example you are using a list of <code>OrderedDicts</code>, while in the second case you are using a single <code>OrderedDict</code> object.</p> <p>So, in the first case, each of the <code>foo</code> objects from <code>mydata</code> are <code>OrderedDict</code> objects and you can access your data using...
1
2016-07-05T18:21:50Z
[ "python", "arrays", "python-2.7", "for-loop" ]
How to handle OrderedDict with one entry in Python for loop?
38,210,025
<p>I am using a OrderedDict like this:</p> <pre><code>my_data = [OrderedDict([(u'@pageid', u'1108'), (u'@ns', u'0'), (u'@title', u'H\xf6rspiele f\xfcr Studenten')]), OrderedDict([(u'@pageid', u'989'), (u'@ns', u'0'), (u'@title', u'Impact')]), OrderedDict([(u'@pageid', u'580'), (u'@ns', u'0'), (u'@title', u'Impfgegner'...
2
2016-07-05T18:16:02Z
38,210,146
<p>In the first case you have a list of <code>OrderedDict</code> and in the second just an <code>OrderedDict</code>. In oder to get your for loop to work do:</p> <pre><code> my_data = [OrderedDict([(u'@pageid', u'328'), (u'@ns', u'0'), (u'@title', u'UWE')])] </code></pre> <p>which creates a list of <code>OrderedDict<...
1
2016-07-05T18:22:53Z
[ "python", "arrays", "python-2.7", "for-loop" ]
Error using Selenium Webdriver and FireFox
38,210,163
<p>"The browser appears to have exited " selenium.common.exceptions.WebDriverException: Message: The browser appears to have exited before we could connect. If you specified a log_file in the FirefoxBinary constructor, check it for details.</p> <p>I am using </p> <p>Selenium version 2.53.6</p> <p>firefox version 47....
2
2016-07-05T18:24:05Z
38,210,625
<p>Unfortunately Selenium WebDriver 2.53.6 is not compatible with Firefox 47.0.</p> <p>I had the same problem and I download the Firefox (version 45) and everything works perfectly. Try this version : <a href="https://ftp.mozilla.org/pub/firefox/releases/45.0/" rel="nofollow">https://ftp.mozilla.org/pub/firefox/releas...
0
2016-07-05T18:52:39Z
[ "python", "python-3.x", "selenium", "firefox", "selenium-webdriver" ]
Error using Selenium Webdriver and FireFox
38,210,163
<p>"The browser appears to have exited " selenium.common.exceptions.WebDriverException: Message: The browser appears to have exited before we could connect. If you specified a log_file in the FirefoxBinary constructor, check it for details.</p> <p>I am using </p> <p>Selenium version 2.53.6</p> <p>firefox version 47....
2
2016-07-05T18:24:05Z
38,210,999
<p>You may refer to this link. <a href="http://stackoverflow.com/questions/37693106/selenium-2-53-not-working-on-firefox-47">Selenium 2.53 not working on Firefox 47</a></p> <p>You can find a solution to your problem in the above link or you can just simply downgrade your Firefox to version 45.</p>
1
2016-07-05T19:15:15Z
[ "python", "python-3.x", "selenium", "firefox", "selenium-webdriver" ]
How to print a pdf file to stdout using python?
38,210,245
<p>A correct pdf file has been created by a script (whose output can't be directly written to stdout, unfortunately). Say the file's name is 'myfile.pdf'.</p> <p>I want to print the exact pdf content to stdout. (No processing in between).</p> <p>To test this, I have written this short <code>read_pdf.py</code> script:...
4
2016-07-05T18:29:29Z
38,210,736
<p>I think your problem is that you are reading line by line, therefore adding extra carriage returns. I tried and works perfectly on OSX:</p> <pre><code>#!/usr/bin/env python3 # -*- coding: utf-8 -*- with open('myfile.pdf', mode='rb') as pdf_file: print(pdf_file.read()) </code></pre> <p>For the sake of comp...
0
2016-07-05T18:58:58Z
[ "python", "linux", "python-3.x", "pdf", "readfile" ]
How to print a pdf file to stdout using python?
38,210,245
<p>A correct pdf file has been created by a script (whose output can't be directly written to stdout, unfortunately). Say the file's name is 'myfile.pdf'.</p> <p>I want to print the exact pdf content to stdout. (No processing in between).</p> <p>To test this, I have written this short <code>read_pdf.py</code> script:...
4
2016-07-05T18:29:29Z
38,217,056
<p>The answer is actually to use <code>sys.stdout.buffer.write()</code>, instead of <code>print()</code>, and in addition to <code>pdf_file.read()</code>:</p> <pre><code>#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys with open('myfile.pdf', mode='rb') as pdf_file: sys.stdout.buffer.write(pdf_file.read...
0
2016-07-06T05:48:47Z
[ "python", "linux", "python-3.x", "pdf", "readfile" ]
How to import a module and change a variable value inside module and execute it
38,210,269
<p>I have a module which I need to import and change particular variable values inside imported instance of that module and then execute it.</p> <p><strong>Please note that</strong> I can not make a single change to the module being imported due to legacy reasons.</p> <p>Here is what I am trying to do:</p> <p>say th...
5
2016-07-05T18:30:52Z
38,210,769
<p>Here is a concrete implementation of what I proposed in the comments:</p> <pre><code>#File temp.py var1 = 1 var2 = 2 if __name__ == '__main__': print var1+var2 </code></pre> <p>I'm calling it via another file run.py. The key is to have another <code>dict</code> like class that is immune against any changes to...
3
2016-07-05T19:01:04Z
[ "python", "import", "python-import", "python-2.6" ]
How to add a custom flag to IPython's magic commands? (.ipy files)
38,210,320
<p>Is it possible to add a custom flag to IPython's magic command? To be more specific, I want to use the %run command with a homemade flag:</p> <pre><code>%run script.ipy --flag "option" </code></pre> <p>and be able to use "option" inside the script.</p> <p>For .py files, the answer is provided here: <a href="http:...
1
2016-07-05T18:34:07Z
38,211,195
<p>As indicated in the comments, this question isn't just about handling commandline arguments in a Python script. It's about handling them in an <code>.ipy</code> file run via <code>%run</code>.</p> <p>If I create <code>test.ipy</code> as</p> <pre><code>import sys print(sys.argv) </code></pre> <p>and run it from s...
0
2016-07-05T19:27:58Z
[ "python", "ipython", "ipython-magic" ]
Scheduled task runs more often then needed
38,210,413
<p>Here's the schedule I have in my settings file</p> <pre><code>CELERYBEAT_SCHEDULE = { 'remind_to_activate_email': { 'task': 'users.tasks.remind_to_activate_email', 'schedule': datetime.timedelta(days=1), 'kwargs': { 'remind_periods': (2,) } }, } </code></pre> <p>...
0
2016-07-05T18:39:55Z
38,210,796
<p>All Celery tasks are queued in a database. You should free the database at restart, or all remaining tasks will continue to run.</p>
0
2016-07-05T19:02:20Z
[ "python", "django", "celery", "django-celery" ]
Strip blank lines from a text file
38,210,434
<p>I'm trying to remove blank lines from a text file, so if I have for example:</p> <pre><code>line 1 line 2 line 3 line 4 line 5 </code></pre> <p>The result after processing the file should look like this:</p> <pre><code>line 1 line 2 line 3 line 4 line 5 </code></pre> <p>I searched stack overflow and this is w...
1
2016-07-05T18:41:21Z
38,210,565
<p>So firstly, the output is appended to the file because you open the file in <code>r+</code> mode and the file pointer is pointing at the end of the file. You won't want to overwrite the file while you're reading it, though, so you really need two files:</p> <pre><code>with open('infile.txt', 'r', encoding='utf-8') ...
1
2016-07-05T18:48:45Z
[ "python", "file" ]
Strip blank lines from a text file
38,210,434
<p>I'm trying to remove blank lines from a text file, so if I have for example:</p> <pre><code>line 1 line 2 line 3 line 4 line 5 </code></pre> <p>The result after processing the file should look like this:</p> <pre><code>line 1 line 2 line 3 line 4 line 5 </code></pre> <p>I searched stack overflow and this is w...
1
2016-07-05T18:41:21Z
38,211,973
<p>here is a working example that do what you are looking for. I am not sure about performance here but for sure it does not use the memory or temp file</p> <pre><code>writebytecount = 0 readbytecount = 0 with open('file2.txt', 'r+') as file: while 1: line = file.readline() if not line: break ...
1
2016-07-05T20:15:47Z
[ "python", "file" ]
Django get_or_create suppress output to shell
38,210,487
<p>This is just a curiosity, as my script is working and I just want to tidy it up. I'm <a href="https://django-chinese-docs.readthedocs.io/en/latest/ref/models/querysets.html#get-or-create" rel="nofollow">executing the django <code>get_or_create</code> function</a> inside a for loop where I check a rather long list fo...
-1
2016-07-05T18:44:09Z
38,215,481
<p>You can just save the output of the function to variables so that it isn't printed:</p> <pre><code>obj, created = MyModel.objects.get_or_create(...) </code></pre> <p>And then discard those variables.</p>
1
2016-07-06T02:17:28Z
[ "python", "django", "bash", "shell" ]
Explode in PySpark
38,210,507
<p>I would like to transform from a DataFrame that contains lists of words into a DataFrame with each word in its own row.</p> <p>How do I do explode on a column in a DataFrame?</p> <p>Here is an example with some of my attempts where you can uncomment each code line and get the error listed in the following comment....
2
2016-07-05T18:45:39Z
38,210,742
<p><code>explode</code> and <code>split</code> are SQL functions. Both operate on SQL <code>Column</code>. <code>split</code> takes a Java regular expression as a second argument. If you want to separate data on arbitrary whitespace you'll need something like this:</p> <pre><code>df = sqlContext.createDataFrame( [...
1
2016-07-05T18:59:11Z
[ "python", "apache-spark", "pyspark", "apache-spark-sql" ]
Explode in PySpark
38,210,507
<p>I would like to transform from a DataFrame that contains lists of words into a DataFrame with each word in its own row.</p> <p>How do I do explode on a column in a DataFrame?</p> <p>Here is an example with some of my attempts where you can uncomment each code line and get the error listed in the following comment....
2
2016-07-05T18:45:39Z
38,210,764
<p>To split on whitespace and also remove blank lines, add the <code>where</code> clause.</p> <pre><code>DF = sqlContext.createDataFrame([('cat \n\n elephant rat \n rat cat\nmat\n', )], ['word']) &gt;&gt;&gt; (DF.select(explode(split(DF.word, "\s")).alias("word")) .where('word != ""') .show()) +-------...
2
2016-07-05T19:00:35Z
[ "python", "apache-spark", "pyspark", "apache-spark-sql" ]
Simple Python server program to receive an image via http POST from Postman?
38,210,578
<p>Does anybody know of an example Python script to receive an image sent via http POST from Postman? I'd like to write a simple Python server script that could receive an image sent like this:</p> <p><a href="http://i.stack.imgur.com/9q7sz.png" rel="nofollow"><img src="http://i.stack.imgur.com/9q7sz.png" alt="enter ...
0
2016-07-05T18:49:17Z
38,210,797
<p>Here's a good example that uses the built in BaseHTTPServer package for receiving GET/POST requests in python: <a href="http://joelinoff.com/blog/?p=1658" rel="nofollow">http://joelinoff.com/blog/?p=1658</a></p>
0
2016-07-05T19:02:23Z
[ "python", "http" ]
Simple Python server program to receive an image via http POST from Postman?
38,210,578
<p>Does anybody know of an example Python script to receive an image sent via http POST from Postman? I'd like to write a simple Python server script that could receive an image sent like this:</p> <p><a href="http://i.stack.imgur.com/9q7sz.png" rel="nofollow"><img src="http://i.stack.imgur.com/9q7sz.png" alt="enter ...
0
2016-07-05T18:49:17Z
38,210,877
<p>This is a pretty straightforward task with Tornado. The example here should mostly work, though it may need a few modifications:</p> <p><a href="https://technobeans.wordpress.com/2012/09/17/tornado-file-uploads/" rel="nofollow">https://technobeans.wordpress.com/2012/09/17/tornado-file-uploads/</a></p>
0
2016-07-05T19:07:15Z
[ "python", "http" ]
how to automatically install dependent modules used in a python app
38,210,650
<p>I just started learning Python and a bit confused about how packages are distributed and installed. I am aware of helper scripts <code>easy_install</code> and <code>pip</code> which can be used to install the dependent modules,howerver I am not clear how to do with programatically,can someone help me on this?</p> <...
2
2016-07-05T18:54:03Z
38,213,899
<p>Easiest way to handle module installs within a program is with <code>pip</code>:</p> <pre><code>import pip pip.main(["install", "numpy"]) </code></pre> <p>For example will install <code>numpy</code> and its dependencies. You can also specify versions using <code>numpy=xxx</code>, or upgrade by passing <code>"-upgr...
1
2016-07-05T22:32:37Z
[ "python", "packages", "setuptools" ]
filter words that contain some letters in a specific order
38,210,672
<p>In Python, I would like to search through a dictionary such as the Scrabble official list and identify all the words with x number of characters in a particular order. For example, I have "mmt" and would like the output to generate a list of words such as what you see below. </p> <p>"mmt":</p> <ul> <li>A<strong>M<...
2
2016-07-05T18:55:30Z
38,210,926
<p>You can generate a dynamic regular expression pattern and filter your list based on that:</p> <pre><code>import re words = ["AMALGAMATED", "AMMONIATED", "CIRCUMAMBULATED", "COMMENTATED", "TAMTAM", "BLUB", "HOUSE", "SOMETHING"] filter = "mmt" regex = re.compile(".*".join(filter), re.IGNORECASE) filtered_...
1
2016-07-05T19:10:36Z
[ "python", "search", "character" ]
Python: Random without repetition, but in def
38,210,700
<p>I don't know how in def I can randomize sentences without repetition.</p> <pre><code>def yellowJeden(x,m): if m &lt;= 25: zd1 = "Juz na samym poczatku meczu "+ x.strip() + " dostal" zd2 = "Juz w " + str(m) + ". minucie meczu zawodnik druzyny "+ druzyna1 + " dostal zolta kartke. "+ x.strip() + " ...
-1
2016-07-05T18:57:02Z
38,210,811
<p>Are you looking for something like this?</p> <pre><code>&gt;&gt;&gt; import random &gt;&gt;&gt; def ShuffleSentences(): ... sentences = [ "First sentence", "Second sentence", "Third sentence", "last sentence"] ... random.shuffle(sentences) ... for s in sentences: ... print s ... &gt;&gt;&gt; Shu...
2
2016-07-05T19:03:25Z
[ "python", "function", "random" ]
Python: Random without repetition, but in def
38,210,700
<p>I don't know how in def I can randomize sentences without repetition.</p> <pre><code>def yellowJeden(x,m): if m &lt;= 25: zd1 = "Juz na samym poczatku meczu "+ x.strip() + " dostal" zd2 = "Juz w " + str(m) + ". minucie meczu zawodnik druzyny "+ druzyna1 + " dostal zolta kartke. "+ x.strip() + " ...
-1
2016-07-05T18:57:02Z
38,210,839
<p>Consider a collection of sentences (eg. a list). Use <a href="https://docs.python.org/2/library/random.html?highlight=random.shuffle#random.shuffle" rel="nofollow">random.shuffle</a> to shuffle the collection. That way you avoid duplicates.</p>
1
2016-07-05T19:05:21Z
[ "python", "function", "random" ]
Downloading ServiceNow data into a CSV file using Python 3.5.2
38,210,813
<p>Can someone please tell me how to use SOAP and WSDL functionality along with ServiceNow in order to download data into a CSV file. I'm using Anaconda version 3.5.2</p> <p>A sample script would be really helpful</p> <p>Downgrading is not an option for me.</p>
-1
2016-07-05T19:03:36Z
38,211,334
<p>I also had a requirement at my work to download and process a service-now report. You can do it either using <code>SOAP</code> , <code>REST</code> or <code>WSDL</code>. I am using <code>REST</code>. Not sure if that will help.</p> <p>You need to <code>postfix</code> download type after table name. For e.g. <code>CS...
2
2016-07-05T19:34:48Z
[ "python", "csv", "soap", "wsdl", "servicenow" ]
Django encoding problems with path name
38,210,824
<p>I'm doing a Django project which expects non-ascii characters, like àéã, etc. So far I have been able to navigate well this encoding hell, but I'm having problems with path names of uploaded files.</p> <p>I have a model that reads thus:</p> <pre><code>class Property (models.Model): #... city = models.Ch...
0
2016-07-05T19:04:15Z
38,228,020
<p>Use python_2_unicode_compatible decorator:</p> <pre><code>from django.utils.encoding import python_2_unicode_compatible, force_text @python_2_unicode_compatible class Property (models.Model): #... city = models.CharField(max_length = 100, choices = CITIES_LIST) pdf_file = models.FileField(upload_to = g...
0
2016-07-06T15:37:49Z
[ "python", "django", "encoding", "utf-8" ]
Iterate through Table of Contents in docx using python-docx
38,210,905
<p>I have a doc with a table of contents that was auto generated in the beginning of the doc and would like to parse through this table of contents. Is this possible using <strong>python-docx</strong>? If I try to iterate through <code>doc.paragraphs.text</code>, the text in that is in the table of contents does not sh...
0
2016-07-05T19:09:19Z
38,212,674
<p>I believe you'll find that the actual generated contents of the TOC is "wrapped" in a non-paragraph element. <code>python-docx</code> won't get you there directly as it only finds paragraphs that are direct children of the <code>w:document/w:body</code> element.</p> <p>To get at these you'll need to go down to the ...
1
2016-07-05T21:02:12Z
[ "python", "python-docx" ]
How to resample dataframe with a linear interpolation by hour
38,210,933
<p>So, this has been somewhat answered, except that it is a little more challenging with the hour mark and I have been running into a problem trying to return the datetime. So, basically I have a dataframe that looks like this:</p> <pre><code> elev Dewpoint Temp time ...
1
2016-07-05T19:11:10Z
38,215,551
<p>So, I solved this after some attempts. This isn't the most beautiful coding, but it does work to solve sampling issues regardless of the sampling times to make sampling reflect (to the best of the knowledge given) what your data should look like:</p> <pre><code>lfile00=path0+dewpointstring+filetype0 df00=xselect(lf...
0
2016-07-06T02:30:35Z
[ "python", "pandas", "indexing", "dataframe" ]
Merging data frames while excluding empty records
38,211,067
<p>I am merging the two <code>data frames</code> on the basis of matching <code>website</code>. But there are few records in both data frames which do not have a website. This results in wrong matching in my resultant data frame because it also matches the records in which both the website field is empty. How can I put...
2
2016-07-05T19:20:09Z
38,211,098
<p>You can filter before merging by <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>boolean indexing</code></a>:</p> <pre><code>df1 = df1[df1.website1 != ''] df2 = df2[df2.website2 != ''] </code></pre> <p>Sample:</p> <pre><code>df1 = pd.DataFrame({'website1':...
0
2016-07-05T19:22:07Z
[ "python", "string", "pandas", "dataframe", "condition" ]
How do I read the name of a text file as a String in Python?
38,211,072
<p>I have a text file named doc123.txt, I want to create files named sub_doc123.txt. The file doc_123.txt is an input for a function.</p> <p>Edit: Sorry if this is basic and I am unable to see the quick solution. Essentially:</p> <pre><code>def test(main_txt_file): print main_txt_file test(practice_split_3.txt) ...
-4
2016-07-05T19:20:35Z
38,211,115
<p>You dont need a function for this. Following code will do.</p> <pre><code>inp = raw_input("Enter name of doc") outName = 'sub_' + inp </code></pre>
0
2016-07-05T19:23:12Z
[ "python", "function", "text-files" ]
How do I read the name of a text file as a String in Python?
38,211,072
<p>I have a text file named doc123.txt, I want to create files named sub_doc123.txt. The file doc_123.txt is an input for a function.</p> <p>Edit: Sorry if this is basic and I am unable to see the quick solution. Essentially:</p> <pre><code>def test(main_txt_file): print main_txt_file test(practice_split_3.txt) ...
-4
2016-07-05T19:20:35Z
38,211,593
<p>You will need to use the <code>os</code> module as you are wanting to manipulate (read/write) files in the directory. It would be additionally beneficial that you save the file used to manipulate your text files in the same directory as the files you would like to manipulate. </p> <pre><code>import os for fileName ...
0
2016-07-05T19:51:06Z
[ "python", "function", "text-files" ]
pywintypes.com_error opening Excel with Python
38,211,088
<p>I have the following script which was immitated from here ( <a href="http://pythonexcels.com/python-excel-mini-cookbook/" rel="nofollow">http://pythonexcels.com/python-excel-mini-cookbook/</a> ):</p> <pre><code>import win32com.client as win32 excel = win32.gencache.EnsureDispatch('Excel.Application') wb = excel.Wor...
1
2016-07-05T19:21:30Z
38,282,679
<p>Try this:</p> <pre><code>import win32com.client as win32 import os excel = win32.gencache.EnsureDispatch('Excel.Application') path = os.getcwdu().replace('\'','\\') + '\\' wb = excel.Workbooks.Open(path+'words.xlsx') </code></pre> <p><strong>Excepted a <code>path</code> error, not <code>module</code> or <code>sys...
2
2016-07-09T14:09:21Z
[ "python", "excel" ]
pywintypes.com_error opening Excel with Python
38,211,088
<p>I have the following script which was immitated from here ( <a href="http://pythonexcels.com/python-excel-mini-cookbook/" rel="nofollow">http://pythonexcels.com/python-excel-mini-cookbook/</a> ):</p> <pre><code>import win32com.client as win32 excel = win32.gencache.EnsureDispatch('Excel.Application') wb = excel.Wor...
1
2016-07-05T19:21:30Z
38,282,722
<p>Have you tried openpyxl, it's very easy to use, reading and writing excel files is no trouble </p> <pre><code>from openpyxl import Workbook </code></pre> <p>And initialize as </p> <pre><code>wb = Workbook() ws = wb.active() </code></pre> <p>And you can start reading and writing right away </p>
0
2016-07-09T14:15:57Z
[ "python", "excel" ]
Need to convert entire column from string format to date format from a Dataframe
38,211,201
<p>I am trying to convert an entire column from a Dataframe from a string to date format. Does anyone have any recommendations on how to do this?</p> <p>I've successfully been able to change one element of this using strptime, but not sure the best way to apply this to the entire column:</p> <p>Sample of the raw Dat...
2
2016-07-05T19:28:12Z
38,211,243
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow"><code>to_datetime</code></a>:</p> <pre><code>df = pd.DataFrame({'b':['2016/06/28 02:13:51','2016/06/28 02:13:51','2016/06/28 02:13:51'], 'a':[4,5,6]}) print (df) a ...
0
2016-07-05T19:29:47Z
[ "python", "datetime", "pandas", "dataframe" ]
Is there a way to minimize the number of calls to __new__ in numerical python code?
38,211,214
<p>I'm working to speed up some numerical modeling code written in python. It relies on <code>numpy</code> arrays and on a matrix solving method from <code>scipy.linalg</code>. It's a finite differences PDE solver. After profiling and taking care of some slower bits, the largest chunk of time is being taken up by the <...
1
2016-07-05T19:28:43Z
38,233,571
<p>Profiler should tell you which object's <code>__new__</code> method is being called.</p> <p>One thing which stands out in your code is that there's quite a bit of copying behind the scenes in your <code>solve_banded</code> call. </p> <p>The answer is in the source of <code>solve_banded</code>: <a href="https://git...
0
2016-07-06T20:51:00Z
[ "python", "numpy", "scipy" ]
Showing all index values when using multiIndexing in Pandas
38,211,350
<p>I would like that when viewing my DataFrame I will see all values of the multiIndex, including when subsequent rows have the same index for one of the levels. Here is an example:</p> <pre><code>arrays = [['20', '50', '20', '20'],['N/A', 'N/A', '10', '30']] tuples = list(zip(*arrays)) index = pd.MultiIndex.from_tupl...
2
2016-07-05T19:35:48Z
38,211,405
<p>You need set <code>display.multi_sparse</code> to <code>False</code>:</p> <pre><code>#if need temporary use option with pd.option_context('display.multi_sparse', False): print (df) 0 Jim Betty 20 N/A 0.201643 50 N/A 0.201643 20 10 0.201643 20 30 0.201643 </code></p...
2
2016-07-05T19:39:06Z
[ "python", "python-3.x", "pandas", "multi-index" ]
Create 3D array from existing 2D array in Python
38,211,375
<p>I am trying to create an array that is with dimensions:</p> <pre><code>a(Days,Hours,Station) </code></pre> <p>I have hourly data for array 'a' for 2 stations over 61 days so currently I have this array with these dimensions:</p> <pre><code>a(1464,2) </code></pre> <p>Where the 1464 is the number of hourly data po...
1
2016-07-05T19:37:23Z
38,211,525
<p>You could try to make a 61x24x2 array. This should work:</p> <pre><code>b = [] for i in xrange(61): b.append(a[i*61:(i+1)*61]) </code></pre>
1
2016-07-05T19:46:35Z
[ "python", "arrays", "dimensions" ]
Create 3D array from existing 2D array in Python
38,211,375
<p>I am trying to create an array that is with dimensions:</p> <pre><code>a(Days,Hours,Station) </code></pre> <p>I have hourly data for array 'a' for 2 stations over 61 days so currently I have this array with these dimensions:</p> <pre><code>a(1464,2) </code></pre> <p>Where the 1464 is the number of hourly data po...
1
2016-07-05T19:37:23Z
38,211,728
<p>If you're first field is <em>hours * days</em>, a transformation would simply be: a(x, y) => a(x // 24, x % 24, y)</p> <p><code>x // 24</code> is floor division so <code>1500 // 24 = 62</code>, the days. You did not specify, but I assume the "Hours" field would be the remaining hours; so <code>x % 24</code> gets th...
0
2016-07-05T19:59:13Z
[ "python", "arrays", "dimensions" ]
Create 3D array from existing 2D array in Python
38,211,375
<p>I am trying to create an array that is with dimensions:</p> <pre><code>a(Days,Hours,Station) </code></pre> <p>I have hourly data for array 'a' for 2 stations over 61 days so currently I have this array with these dimensions:</p> <pre><code>a(1464,2) </code></pre> <p>Where the 1464 is the number of hourly data po...
1
2016-07-05T19:37:23Z
38,212,096
<p>This will split array <code>a</code> to chunks with maximum length <code>size</code>.</p> <pre><code>def chunks( a, size ): arr = iter( a ) for v in arr: tmp = [ v ] for i,v in zip( range( size - 1 ), arr ): tmp.append( v ) yield tmp splitted = list( chunks( a, 24 ) ) <...
1
2016-07-05T20:23:42Z
[ "python", "arrays", "dimensions" ]
Speed up pandas dataframe iteration
38,211,408
<p>I have a dataframe with date and values, </p> <pre><code> Date Price Jun 30 95.60 Jun 29 94.40 Jun 28 93.59 Jun 27 92.04 Jun 24 93.40 Jun 23 96.10 Jun 22 95.55 Jun 21 95.91 Jun 20 95.10 Jun 17 95.33 Jun 16 97.55 Jun 15 97.14 Jun 14 97.46 Jun 13 97.34 Jun 10 98.83 Jun...
4
2016-07-05T19:39:26Z
38,212,016
<p>Let's invite <code>Scipy</code> too!</p> <p><strong>The Idea :</strong> Compare the current element with the previous <code>4</code> values by calculating the minimum in that interval and comparing with the current one. If it matches, we have basically failed all the comparisons and thus choose <code>False</code>. ...
2
2016-07-05T20:18:48Z
[ "python", "numpy", "pandas" ]
Speed up pandas dataframe iteration
38,211,408
<p>I have a dataframe with date and values, </p> <pre><code> Date Price Jun 30 95.60 Jun 29 94.40 Jun 28 93.59 Jun 27 92.04 Jun 24 93.40 Jun 23 96.10 Jun 22 95.55 Jun 21 95.91 Jun 20 95.10 Jun 17 95.33 Jun 16 97.55 Jun 15 97.14 Jun 14 97.46 Jun 13 97.34 Jun 10 98.83 Jun...
4
2016-07-05T19:39:26Z
38,212,169
<p>You can actually <em>time it</em>. Here is my experiment. It shows that loop over an list is much faster than your method. The answer from @Divakar is actually very good.</p> <pre><code>import pandas as pd import timeit import numpy as np df = pd.DataFrame({'Date':['Jun 30', 'Jun 29', 'Jun 28', 'Jun 27', 'Jun 24',...
1
2016-07-05T20:28:30Z
[ "python", "numpy", "pandas" ]
How can I sum values from df1 that match another value from df2
38,211,454
<p>How can I sum values from df1 that belong to another value in df2?</p> <p>I have a really large df, but lets say I have a df like this:</p> <pre><code>df1: A B C 0 John Pen Apple 1 John Printer Pie 2 John Charger Burger 3 Erick Battery Pizza 4 Mandy Keyboard Bread 5 Man...
2
2016-07-05T19:42:06Z
38,211,630
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.merge.html" rel="nofollow"><code>merge</code></a>:</p> <pre><code>df = pd.merge(df1, df2, left_on='B', right_on='A', suffixes=('','1')) df = df.groupby('A', as_index=False)['B1'].sum() df = pd.merge(df3, df, on='A', how='left').rename...
2
2016-07-05T19:53:18Z
[ "python", "list", "pandas", "sum" ]
Using chunksize to select data but keeping the same order?
38,211,468
<p>Below is the program I use <code>chunksize</code> to select data from a database.</p> <pre><code># Give my large required list subset = pd.read_csv(required_list, index_col=[0], low_memory=False).index.unique() # give my large database, it would select data based on column name tp = pd.read_csv(Database,iterator=T...
1
2016-07-05T19:42:48Z
38,211,938
<p>you can do it this way:</p> <pre><code>df = pd.concat(tp, ignore_index=True)[subset] </code></pre> <p><code>pd.concat(tp, ignore_index=True)</code> returns a Data Frame, and <code>df[list_of_cools]</code> - returns a DataFrame with columns ordered as in the <code>list_of_cools</code> list </p>
1
2016-07-05T20:13:23Z
[ "python", "python-2.7", "pandas" ]
physically closing a file in python as if i pressed the x button on a txt file
38,211,521
<p>so I'm new to python and I figured out how to open a file using <code>os.startfile</code>, but I can't seem to find the function to close a file as if I physically pressed the x button on a txt file.</p> <p>anybody know what the function is for that?</p>
-3
2016-07-05T19:46:18Z
38,211,590
<p><a href="http://www.tutorialspoint.com/python/file_close.htm" rel="nofollow">http://www.tutorialspoint.com/python/file_close.htm</a></p> <pre><code>#!/usr/bin/python # Open a file fo = open("foo.txt", "wb") print "Name of the file: ", fo.name # Close opend file fo.close() </code></pre>
-3
2016-07-05T19:50:56Z
[ "python" ]
physically closing a file in python as if i pressed the x button on a txt file
38,211,521
<p>so I'm new to python and I figured out how to open a file using <code>os.startfile</code>, but I can't seem to find the function to close a file as if I physically pressed the x button on a txt file.</p> <p>anybody know what the function is for that?</p>
-3
2016-07-05T19:46:18Z
38,211,711
<p>You can't that way.</p> <p>As described in the python documentation : <a href="https://docs.python.org/2/library/os.html#os.startfile" rel="nofollow">https://docs.python.org/2/library/os.html#os.startfile</a></p> <blockquote> <p>startfile() returns as soon as the associated application is launched. There is no o...
0
2016-07-05T19:58:08Z
[ "python" ]
Parsing all XML files in directory and all subdirectories
38,211,588
<p>I am new to Python, yet I have some experience with Delphi. I am trying to make a script that would be able to search all xml files in directory (including all subdirectories in that directory), then parse those XML and save some data (numbers) from there to a simple txt file. After that I work through that txt fil...
1
2016-07-05T19:50:39Z
38,212,646
<p>The pattern you are looking for is like:</p> <pre><code>with open ('ICP_all.txt', 'w') as SeznamICP_all: for root, dirs, files in os.walk(directory): for file in files: if (file.endswith('.xml')): xmldoc = minidom.parse(os.path.join(root, file)) itemlist = ...
1
2016-07-05T21:00:23Z
[ "python", "xml", "python-3.x", "xml-parsing", "directory" ]
Parsing all XML files in directory and all subdirectories
38,211,588
<p>I am new to Python, yet I have some experience with Delphi. I am trying to make a script that would be able to search all xml files in directory (including all subdirectories in that directory), then parse those XML and save some data (numbers) from there to a simple txt file. After that I work through that txt fil...
1
2016-07-05T19:50:39Z
38,214,083
<p>Your issue as already explained in Rob's answer is because you are not joining the path so once you leave the cwd you are finding files outside of the directory but looking for them in the cwd.</p> <p>Since you are using oythin3 you have a couple of other options to find the files, if your python3 version is 3.5 ca...
0
2016-07-05T22:54:45Z
[ "python", "xml", "python-3.x", "xml-parsing", "directory" ]
Python issue with linecache reading a line from an external .txt file
38,211,610
<p>I'm hacking together my first Python project. I'm running the below Python code and having trouble with the linecache.getline. I want it to open the stoarage.txt file. Check if the number is 0. If it is, change it to 1 - play the music and turn on the LED. Then switch it to 2 it doesn't play the music again every ti...
0
2016-07-05T19:52:05Z
38,211,810
<p>Your mistake lies in assuming that <code>linecache.getline</code> will simply return an integer. If you run it in an interpreter, it will return the string <code>'0\n'</code>, which is a string.</p> <p>After you get the line, you're going to need to find some way to simply get the number you want (if they're only ...
0
2016-07-05T20:04:43Z
[ "python", "raspberry-pi" ]
How does Python determine which type to cast something to?
38,211,657
<p>Suppose I have the following:</p> <pre><code>x = "0" y = 0 if x == y: print "You're winner!" </code></pre> <p>Will Python convert <code>x</code> to an int, or <code>y</code> to a string? Is there any way to control this behavior?</p>
0
2016-07-05T19:54:36Z
38,211,696
<p>No conversion will happen. <code>x</code> and <code>y</code> are not equal since they are different types. If you want to control equality testing, you can implement the "magic" <code>__eq__</code> method on your object. There is no implicit conversion feature.</p>
1
2016-07-05T19:57:11Z
[ "python", "casting", "comparison" ]
How does Python determine which type to cast something to?
38,211,657
<p>Suppose I have the following:</p> <pre><code>x = "0" y = 0 if x == y: print "You're winner!" </code></pre> <p>Will Python convert <code>x</code> to an int, or <code>y</code> to a string? Is there any way to control this behavior?</p>
0
2016-07-05T19:54:36Z
38,211,700
<p>Python is a strongly typed language. Barring a few exceptions with <code>float</code> types and <code>int</code> types involving arithmetic, Python does not convert types. </p>
1
2016-07-05T19:57:31Z
[ "python", "casting", "comparison" ]
How does Python determine which type to cast something to?
38,211,657
<p>Suppose I have the following:</p> <pre><code>x = "0" y = 0 if x == y: print "You're winner!" </code></pre> <p>Will Python convert <code>x</code> to an int, or <code>y</code> to a string? Is there any way to control this behavior?</p>
0
2016-07-05T19:54:36Z
38,211,704
<p>It won't convert either; it will just decide that they're not equal.</p>
1
2016-07-05T19:57:42Z
[ "python", "casting", "comparison" ]