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
python: i have an error while trying this on my mac using IDLE on mac or terminal
40,062,854
<p>i want to see some info and get info about my os with python as in my tutorial but actually can't run this code:</p> <pre><code>import os F = os.popen('dir') </code></pre> <p>and this :</p> <pre><code>F.readline() ' Volume in drive C has no label.\n' F = os.popen('dir') # Read by sized blocks F.rea...
0
2016-10-15T18:43:52Z
40,062,950
<p><code>open</code> and <code>os.popen</code> <em>are entirely different</em><sup>*</sup>. </p> <p>The first one just opens a file (by default <em>for reading</em>), but the second one runs a command in your shell and gives you the ability to communicate with it (e.g. get the output). </p> <p>So, given that <code>op...
0
2016-10-15T18:52:18Z
[ "python", "osx" ]
python: i have an error while trying this on my mac using IDLE on mac or terminal
40,062,854
<p>i want to see some info and get info about my os with python as in my tutorial but actually can't run this code:</p> <pre><code>import os F = os.popen('dir') </code></pre> <p>and this :</p> <pre><code>F.readline() ' Volume in drive C has no label.\n' F = os.popen('dir') # Read by sized blocks F.rea...
0
2016-10-15T18:43:52Z
40,063,025
<p><code>os.popen</code> executes a program and returns a file-like object to read the program output. So, <code>os.popen('dir')</code> runs the <code>dir</code> command (which lists information about your hard drive) and gives you the result. <code>open</code> opens a file on your hard drive for reading.</p> <p>Your ...
0
2016-10-15T18:59:15Z
[ "python", "osx" ]
How to make a dynamic grid in Python
40,062,870
<p>I am building an X's and O's (tic tac toe) application where the user can decide whether the grid is between 5X5 and 10X10, how do I write the code so that the grid is dynamic? </p> <p>At the moment this is all I have to make a grid of one size:</p> <pre><code> grid = [[0,0,0,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,0,0]...
0
2016-10-15T18:45:08Z
40,063,123
<p>Code:</p> <pre><code>#defining size x = y = 5 #create empty list to hold rows grid = [] #for each row defined by Y, this loop will append a list containing X occurrences of "0" for row in range(y): grid.append(list("0"*x)) print grid </code></pre> <p>Output:</p> <pre><code>[['0', '0', '0', '0', '0'], ['0', '...
1
2016-10-15T19:07:50Z
[ "python", "grid" ]
How to make that multiply all numbers in list (Permutation) with smaller code?
40,062,948
<p>My problem is:</p> <pre><code> perm_list = list(range(a,b,-1)) if len(perm_list) == 1: print(perm_list[0]) elif len(perm_list) == 2: print(perm_list[0]* perm_list[1]) elif len(perm_list) == 3: </code></pre> <p>I cant find a way to make that smaller if i can do it would be awesome.<br> ...
0
2016-10-15T18:52:06Z
40,062,991
<p>Just use the <code>itertools</code> library</p> <pre><code>from itertools import permutations lst = list(range(3)) result = list(permutations(lst, 2)) print(result) =&gt; [(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)] print(list(permutations(lst, 3))) =&gt; [(0, 1, 2), (0, 2, 1), (1, 0, 2), (1, 2, 0), (2, 0, 1),...
0
2016-10-15T18:56:03Z
[ "python", "python-3.x", "permutation" ]
Problems with querying multiindex table in HDF when using data_columns
40,062,965
<p>I try to query a multi-index table in a pandas HDF store, but it fails when using a query over the index and data_columns at the same time. This only occurs when <code>data_columns=True</code>. Any idea if this is expected, or how to avoid if I don't want to explicitly specify the data_columns?</p> <p>See the follo...
2
2016-10-15T18:53:58Z
40,069,108
<p>It's an interesting question, indeed!</p> <p>I can't explain the following difference (why do we have index columns indexed when using <code>data_columns=None</code> (default due to the <code>docstring</code> of the <code>HDFStore.append</code> method) and we don't have them indexed when using <code>data_columns=Tr...
2
2016-10-16T10:08:57Z
[ "python", "pandas", "dataframe", "pytables", "hdf" ]
Fill a multidimensional array efficiently that have many if else statements
40,063,034
<p>I want to fill an 4dim numpy array in a specific and efficient way. Because I don't know better I startet to write the code with if else statements, but that doesn't look nice, is probably slow and I also can not be really sure if I thought about every combination. Here is the code which I stopped writing down:</p> ...
4
2016-10-15T18:59:57Z
40,063,118
<p>I don't really know what you mean by saying that those variables are the same, but if indeed they are, than all you have to do is just use <code>set()</code>.</p> <pre><code>from functools import reduce from operator import mul sercnew2 = numpy.zeros((gn, gn, gn, gn)) for x1 in range(gn): for x2 in range(x1, gn...
3
2016-10-15T19:06:56Z
[ "python", "arrays", "numpy" ]
Fill a multidimensional array efficiently that have many if else statements
40,063,034
<p>I want to fill an 4dim numpy array in a specific and efficient way. Because I don't know better I startet to write the code with if else statements, but that doesn't look nice, is probably slow and I also can not be really sure if I thought about every combination. Here is the code which I stopped writing down:</p> ...
4
2016-10-15T18:59:57Z
40,063,184
<p>You can do it in a single for loop too. Building on Divakar's Trick for a list of indexes, the first thing we need to do is figure out how to extract only the unique indices of a given element in the 4d array <code>sercnew2</code>.</p> <p>One of the fastest ways to do this (Refer: <a href="https://www.peterbe.com/p...
2
2016-10-15T19:14:25Z
[ "python", "arrays", "numpy" ]
Fill a multidimensional array efficiently that have many if else statements
40,063,034
<p>I want to fill an 4dim numpy array in a specific and efficient way. Because I don't know better I startet to write the code with if else statements, but that doesn't look nice, is probably slow and I also can not be really sure if I thought about every combination. Here is the code which I stopped writing down:</p> ...
4
2016-10-15T18:59:57Z
40,063,414
<p>Really hoping that I have got it! Here's a vectorized approach -</p> <pre><code>from itertools import product n_dims = 4 # Number of dims # Create 2D array of all possible combinations of X's as rows idx = np.sort(np.array(list(product(np.arange(gn), repeat=n_dims))),axis=1) # Get all X's indexed values from ewp...
3
2016-10-15T19:37:55Z
[ "python", "arrays", "numpy" ]
Casting an array of C structs to a numpy array
40,063,080
<p>A function I'm calling from a shared library returns a structure called info similar to this:</p> <pre><code>typedef struct cmplx { double real; double imag; } cmplx; typedef struct info{ char *name; int arr_len; double *real_data cmplx *cmplx_data; } info; </code></pre> <p>One of the fields of the st...
0
2016-10-15T19:04:15Z
40,063,208
<p>Define your field as double and make a complex view with numpy:</p> <pre><code>class info(Structure): _fields_ = [("name", c_char_p), ("arr_len", c_int), ("real_data", POINTER(c_double)), ("cmplx_data", POINTER(c_double))] c_func.restype = info ret_val = c_func()...
0
2016-10-15T19:15:43Z
[ "python", "arrays", "python-3.x", "numpy", "ctypes" ]
Selenium unable to start Firefox
40,063,088
<p>I'm trying to make a simple scraping program but I am not able to get Selenium working with Firefox. I installed <a href="https://developer.mozilla.org/en-US/docs/Mozilla/QA/Marionette/WebDriver" rel="nofollow">Marionette</a> but that didn't solve anything. When I type this:</p> <pre><code>from selenium import webd...
0
2016-10-15T19:04:51Z
40,063,192
<p>Try using the complete path to firefox executable. Maybe it's not listed in you variable environment path..</p> <pre><code>from selenium import webdriver driver = webdriver.Firefox("/path/to/firefox") </code></pre> <p>This should tell your script where to find the firefox executable.</p> <p><strong>Edit:</strong>...
0
2016-10-15T19:14:53Z
[ "python", "selenium", "firefox", "pycharm" ]
Selenium unable to start Firefox
40,063,088
<p>I'm trying to make a simple scraping program but I am not able to get Selenium working with Firefox. I installed <a href="https://developer.mozilla.org/en-US/docs/Mozilla/QA/Marionette/WebDriver" rel="nofollow">Marionette</a> but that didn't solve anything. When I type this:</p> <pre><code>from selenium import webd...
0
2016-10-15T19:04:51Z
40,065,022
<p>Try:</p> <pre><code>driver = webdriver.Firefox(executable_path="path to your driver") </code></pre> <p>eg: <code>driver = webdriver.Firefox(executable_path="C:\Python27\wires.exe")</code></p>
0
2016-10-15T22:46:38Z
[ "python", "selenium", "firefox", "pycharm" ]
Python tkinter moving object in def that as been created in another def
40,063,124
<p>I am creating flappy bird style game. And my problem is that i cant move tubes that has been created on another def. My code is</p> <pre><code>from tkinter import * from random import randint window = Tk() c = Canvas(window, width=800, height=800, bg='steelblue') tube11 = randint(600, 650) tube12 = randint(400, 700...
0
2016-10-15T19:07:55Z
40,063,393
<p>Try creating a class</p> <pre><code>from tkinter import * from random import randint window = Tk() c = Canvas(window, width=800, height=800, bg='steelblue') tube11 = randint(600, 650) tube12 = randint(400, 700) class Tubes: def __init__(self): self.createtubes() def createtubes(self): self.t...
1
2016-10-15T19:36:01Z
[ "python", "python-3.x", "tkinter" ]
Python tkinter moving object in def that as been created in another def
40,063,124
<p>I am creating flappy bird style game. And my problem is that i cant move tubes that has been created on another def. My code is</p> <pre><code>from tkinter import * from random import randint window = Tk() c = Canvas(window, width=800, height=800, bg='steelblue') tube11 = randint(600, 650) tube12 = randint(400, 700...
0
2016-10-15T19:07:55Z
40,064,624
<p>You can also use tags option on your rectangles.</p> <pre><code>tube1 = c.create_rectangle(800, 800, tube11, tube12, fill='green', tags='tube') tube2 = c.create_rectangle(800, 0, tube11, 200, fill='green', tags='tube') </code></pre> <p>And in your function only one move :</p> <pre><code>c.move('tube', -3.5, 0) </...
1
2016-10-15T21:57:28Z
[ "python", "python-3.x", "tkinter" ]
multiple conditions to a if loop python
40,063,156
<p>Hello I'm having some problems with some code I am writing for a school and its not working. It wont run through the whole loop but all the code looks right to me. Does anyone have any ideas?</p> <pre><code> User_Input = input ( "Please enter a message that is no longer than 7 characters." ) User_Input_Length...
-2
2016-10-15T19:10:58Z
40,063,238
<p>You're not testing what you think you are. Your expressions look like:</p> <pre><code>{ User_Input_Length &gt;= 7 and User_Input_Length == 1 } </code></pre> <p>In Python, <code>{}</code> encloses a <code>set</code> or <code>dict</code> (or comprehension of either). This is thus a set containing one <code>bool</cod...
3
2016-10-15T19:18:13Z
[ "python" ]
multiple conditions to a if loop python
40,063,156
<p>Hello I'm having some problems with some code I am writing for a school and its not working. It wont run through the whole loop but all the code looks right to me. Does anyone have any ideas?</p> <pre><code> User_Input = input ( "Please enter a message that is no longer than 7 characters." ) User_Input_Length...
-2
2016-10-15T19:10:58Z
40,063,244
<p>Those braces are for defining sets, and a non-empty set always evaluates to true, so your code will always evaluate the first if.</p> <p>Python doesn't requires parenthesis (or braces) around if statements.</p>
1
2016-10-15T19:19:02Z
[ "python" ]
multiple conditions to a if loop python
40,063,156
<p>Hello I'm having some problems with some code I am writing for a school and its not working. It wont run through the whole loop but all the code looks right to me. Does anyone have any ideas?</p> <pre><code> User_Input = input ( "Please enter a message that is no longer than 7 characters." ) User_Input_Length...
-2
2016-10-15T19:10:58Z
40,063,330
<p>you must use parentheses for the parameters of the <code>if</code> condition, and be careful about the placement of your code blocks: unlike C which uses <code>;</code> as a delimiter, python knows your block is over only because it jumps to the next line.</p> <pre><code>if(1 &lt; 2) and (2 &lt; 3): print("true...
0
2016-10-15T19:27:09Z
[ "python" ]
pdfkit - python : 'str' object has no attribute decode
40,063,205
<p>I am attempting to use pdfkit to convert string html to a pdf file. This is what I am doing</p> <pre><code> try: options = { 'page-size': 'A4', 'margin-top': '0.75in', 'margin-right': '0.75in', 'margin-bottom': '0.75in', 'margin-left': '0.75in', ...
0
2016-10-15T19:15:32Z
40,063,760
<p>Try replacing the config line with this - path to the binary is provided as a bytes object:</p> <pre><code>config = pdfkit.configuration(wkhtmltopdf=bytes("/usr/local/bin/wkhtmltopdf", 'utf8')) </code></pre> <p>Reference: <a href="https://github.com/JazzCore/python-pdfkit/issues/32" rel="nofollow">https://github.c...
1
2016-10-15T20:14:21Z
[ "python", "pdfkit" ]
Python dataframe sum rows
40,063,242
<p>If I have a dataframe with <code>n</code> rows, is there a way to set the ith row to be sum of <code>row[i]</code> and <code>row[i-1]</code> and do this so that the assignment to earlier rows is reflected in the latter rows? I would really like to avoid loops if possible.</p> <p>Example DF:</p> <pre><code> ...
4
2016-10-15T19:18:49Z
40,063,294
<p>based on your question, you are looking for a cumulative sum of each columns. you could use the <code>cumsum()</code> method</p> <pre><code>DF.cumsum() SPY AAPL GOOG 2011-01-10 0.4400 -0.8100 1.8000 2011-01-11 0.4400 -0.8100 1.8000 2011-01-12 -0.6700 -3.5800 0.9400 2011-01-13 -1.5800 -7.6000 ...
2
2016-10-15T19:23:47Z
[ "python", "pandas", "dataframe" ]
Python dataframe sum rows
40,063,242
<p>If I have a dataframe with <code>n</code> rows, is there a way to set the ith row to be sum of <code>row[i]</code> and <code>row[i-1]</code> and do this so that the assignment to earlier rows is reflected in the latter rows? I would really like to avoid loops if possible.</p> <p>Example DF:</p> <pre><code> ...
4
2016-10-15T19:18:49Z
40,063,308
<p>Use <code>DF.shift()</code></p> <pre><code>DF + DF.shift() </code></pre>
2
2016-10-15T19:25:09Z
[ "python", "pandas", "dataframe" ]
How can I ensure that a function takes a certain amount of time in Go?
40,063,269
<p>I am implementing EnScrypt for an SQRL client in Go. The function needs to run until it has used a minimum amount of CPU time. My Python code looks like this:</p> <pre><code>def enscrypt_time(salt, password, seconds, n=9, r=256): N = 1 &lt;&lt; n start = time.process_time() end = start + seconds dat...
5
2016-10-15T19:21:07Z
40,066,992
<p>You may use <a href="https://golang.org/pkg/runtime/#LockOSThread" rel="nofollow"><code>runtime.LockOSThread()</code></a> to wire the calling goroutine to its current OS thread. This will ensure that no other goroutines will be scheduled to this thread, so your goroutine will run and not get interrupted or put on ho...
3
2016-10-16T04:54:42Z
[ "python", "go", "time", "sqrl" ]
Python - How can i print a certain dictionary field from many dictionaries within a list?
40,063,316
<p>I am currently working on a Guess Who like game for school work and I cannot seem to get this to work. What I am trying to do is get the field "Name" printed from all the dictionaries below within a list.</p> <pre><code> Greg = {"Name":"Greg", "HairLength":"Short", "HairColour":"Brown", "FacialHair":"Yes", "Jewelle...
0
2016-10-15T19:26:07Z
40,063,352
<p>You can use a list comprehension to get a list of all the suspects' names</p> <pre><code>suspects_names = [suspect['Name'] for suspect in AISuspects] </code></pre> <p>Then you can use <code>print(' '.join(suspect_names))</code></p> <p>If you don't mind printing each name in a new line, just use a for loop:</p> <...
5
2016-10-15T19:30:20Z
[ "python", "list", "dictionary", "printing", "output" ]
Python - How can i print a certain dictionary field from many dictionaries within a list?
40,063,316
<p>I am currently working on a Guess Who like game for school work and I cannot seem to get this to work. What I am trying to do is get the field "Name" printed from all the dictionaries below within a list.</p> <pre><code> Greg = {"Name":"Greg", "HairLength":"Short", "HairColour":"Brown", "FacialHair":"Yes", "Jewelle...
0
2016-10-15T19:26:07Z
40,063,473
<pre><code>UserSuspects = [Greg['Name'], Chris['Name'],Jason['Name'], Clancy['Name'], Betty['Name'], Selena['Name'], Helen['Name'], Jacqueline['Name']] print UserSuspects </code></pre>
-1
2016-10-15T19:44:51Z
[ "python", "list", "dictionary", "printing", "output" ]
Python Plotting Data Using the Row referring to rows to columns from CSV file
40,063,339
<p>Below is the data from CSV file : Each Value Separated by "COMMA"</p> <pre><code>SName,Sub1,Sub2,Sub3, ... ,Sub10 0 A,40,50,33, ... ,78 1 B,55,55,33, ... ,66 2 C,99,100,34, ... ,44 </code></pre> <p>I want to Plot only the Row 0 - that is Student Name: A's subject marks from Sub1 till Sub 10 . The Graph shoul...
-2
2016-10-15T19:28:38Z
40,064,161
<p>Possibly the easiest way of many plots is to begin with one of the samples available at the <a href="http://matplotlib.org/gallery.html" rel="nofollow">matplotlib gallery</a>. In this case, I reminded myself about details using two of the samples since I don't use matplotlib often. This code represents part of a sol...
1
2016-10-15T21:01:00Z
[ "python", "python-2.7", "pandas", "numpy", "matplotlib" ]
Python - converting to list
40,063,378
<pre><code>import requests from bs4 import BeautifulSoup webpage = requests.get("http://www.nytimes.com/") soup = BeautifulSoup(requests.get("http://www.nytimes.com/").text, "html.parser") for story_heading in soup.find_all(class_="story-heading"): articles = story_heading.text.replace('\n', '').replace(' ', '') pr...
0
2016-10-15T19:34:13Z
40,063,409
<p>You are constantly overwriting <code>articles</code> with the next value in your list. What you want to do instead is make <code>articles</code> a list, and just <code>append</code> in each iteration: </p> <pre><code>import requests from bs4 import BeautifulSoup webpage = requests.get("http://www.nytimes.com/") s...
2
2016-10-15T19:37:18Z
[ "python", "string", "list", "split" ]
Python - Reversing data generated with particular loop order
40,063,401
<h1>Question: How could I peform the following task more efficiently?</h1> <p>My problem is as follows. I have a (large) 3D data set of points in real physical space (x,y,z). It has been generated by a nested for loop that looks like this:</p> <pre><code># Generate given dat with its ordering x_samples = 2 y_samples ...
0
2016-10-15T19:36:43Z
40,063,949
<p>You could reshape your array, swap the axes as necessary and reshape back again:</p> <pre><code># (No need to copy if you don't want to keep the given_dat ordering) data = np.copy(given_dat).reshape(( z_samples, y_samples, x_samples, 3)) # swap the "y" and "x" axes data = np.swapaxes(data, 1,2) # back to 2-D array ...
2
2016-10-15T20:35:38Z
[ "python", "numpy" ]
How to find and print out of a specific value from a list (at least i think thats what i want to do?)
40,063,567
<p>Here is my code: </p> <pre><code>n = 1 inputs = [] quantities = [] while n == 1: w = input('Enter the product code: ') inputs.append(w) with open('items.txt') as f: found = False for line in f: if w in line: price1 = line[21:25] desc1 = line[9...
0
2016-10-15T19:54:17Z
40,063,657
<p>You can use <a href="https://docs.python.org/2/library/functions.html#enumerate" rel="nofollow"><code>enumerate</code></a>. For example:</p> <pre><code>for index, i in enumerate(inputs): print(index, i) </code></pre> <p>That should print out </p> <pre><code>0, 74283187 1, 15372185 </code></pre> <p>Getting the ...
0
2016-10-15T20:02:52Z
[ "python" ]
How to find and print out of a specific value from a list (at least i think thats what i want to do?)
40,063,567
<p>Here is my code: </p> <pre><code>n = 1 inputs = [] quantities = [] while n == 1: w = input('Enter the product code: ') inputs.append(w) with open('items.txt') as f: found = False for line in f: if w in line: price1 = line[21:25] desc1 = line[9...
0
2016-10-15T19:54:17Z
40,063,658
<p>I would re-write the latter part of your code to iterate through the <em><a href="https://docs.python.org/2/library/functions.html#range" rel="nofollow">range</a></em> of values in <code>inputs</code>, rather than the values themselves. Then, you can call the index of the element you want to print from <code>quanti...
1
2016-10-15T20:03:19Z
[ "python" ]
How to find and print out of a specific value from a list (at least i think thats what i want to do?)
40,063,567
<p>Here is my code: </p> <pre><code>n = 1 inputs = [] quantities = [] while n == 1: w = input('Enter the product code: ') inputs.append(w) with open('items.txt') as f: found = False for line in f: if w in line: price1 = line[21:25] desc1 = line[9...
0
2016-10-15T19:54:17Z
40,063,703
<p>You're creating a new list for the quantities so at the end where you print out this list you can append it to print out only the product code of that item. Understand? I'll post the code in a little bit if I can.</p>
0
2016-10-15T20:08:28Z
[ "python" ]
Pandas flatten hierarchical index on non overlapping columns
40,063,580
<p>I have a dataframe, and I set the index to a column of the dataframe. This creates a hierarchical column index. I want to flatten the columns to a single level. Similar to this question - <a href="http://stackoverflow.com/questions/14507794/python-pandas-how-to-flatten-a-hierarchical-index-in-columns">Python Pandas ...
3
2016-10-15T19:55:17Z
40,063,647
<p>there will always be an index in your dataframes. if you don't set 'id' as index, it will be at the same level as other columns and pandas will populate an increasing integer for your index starting from 0.</p> <pre><code>df = pd.DataFrame([(101,3,'x'), (102,5,'y')], columns=['id', 'A', 'B']) In[52]: df Out[52]: ...
1
2016-10-15T20:01:27Z
[ "python", "pandas" ]
Pandas flatten hierarchical index on non overlapping columns
40,063,580
<p>I have a dataframe, and I set the index to a column of the dataframe. This creates a hierarchical column index. I want to flatten the columns to a single level. Similar to this question - <a href="http://stackoverflow.com/questions/14507794/python-pandas-how-to-flatten-a-hierarchical-index-in-columns">Python Pandas ...
3
2016-10-15T19:55:17Z
40,063,868
<p>Given:</p> <pre><code>&gt;&gt;&gt; df2=pd.DataFrame([(101,3,'x'), (102,5,'y')], columns=['id', 'A', 'B']) &gt;&gt;&gt; df2.set_index('id', inplace=True) &gt;&gt;&gt; df2 A B id 101 3 x 102 5 y </code></pre> <p>For printing purdy, you can produce a copy of the DataFrame with a reset the index and u...
1
2016-10-15T20:27:43Z
[ "python", "pandas" ]
Pandas flatten hierarchical index on non overlapping columns
40,063,580
<p>I have a dataframe, and I set the index to a column of the dataframe. This creates a hierarchical column index. I want to flatten the columns to a single level. Similar to this question - <a href="http://stackoverflow.com/questions/14507794/python-pandas-how-to-flatten-a-hierarchical-index-in-columns">Python Pandas ...
3
2016-10-15T19:55:17Z
40,065,612
<p>You are misinterpreting what you are seeing.</p> <pre><code> A B id 101 3 x 102 5 y </code></pre> <p>Is not showing you a hierarchical column index. <code>id</code> is the name of the row index. In order to show you the name of the index, pandas is putting that space there for you.</p> <p>The an...
2
2016-10-16T00:29:01Z
[ "python", "pandas" ]
Why won't this APScheduler code work?
40,063,734
<p>been looking for quite a while for an answer so I turned to here! It gives me the error, "Invalid Index" for the sched.start()!</p> <pre><code>import random import datetime from apscheduler.schedulers.blocking import BlockingScheduler import smtplib import email def randEmail(): #Gets randLine file_object...
0
2016-10-15T20:11:35Z
40,065,143
<p>You can add a job to a scheduler by decorating a function with the <code>scheduled_job</code> decorator:</p> <pre><code>from apscheduler.schedulers.blocking import BlockingScheduler sched = BlockingScheduler() # minute=30 not minutes=30 @sched.scheduled_job('cron', day_of_week='mon-fri', hour=18, minute=30) def r...
0
2016-10-15T23:07:11Z
[ "python", "apscheduler" ]
Can someone help me make the transition to a new window using Tkinter in Python?
40,063,782
<p>Im very new and am interested in working with windows and Tkinter. please be gentle.</p> <p>here is my code that is supposed to go to a new window then open an image in that new window. However, instead of putting the image in the new window it puts it in the first window.</p> <p>I think this has something to do w...
0
2016-10-15T20:16:35Z
40,064,148
<p>Try this code:</p> <pre><code>import tkinter as tk class MainWindow(tk.Frame): counter = 0 def __init__(self, *args, **kwargs): tk.Frame.__init__(self, *args, **kwargs) self.button = tk.Button(self, text="Create new window", command=self.create_window) ...
0
2016-10-15T20:59:47Z
[ "python", "windows", "tkinter" ]
Can someone help me make the transition to a new window using Tkinter in Python?
40,063,782
<p>Im very new and am interested in working with windows and Tkinter. please be gentle.</p> <p>here is my code that is supposed to go to a new window then open an image in that new window. However, instead of putting the image in the new window it puts it in the first window.</p> <p>I think this has something to do w...
0
2016-10-15T20:16:35Z
40,064,158
<p>To create another toplevel widget, use the <code>Toplevel</code> command. Don't try calling <code>Tk()</code> again.</p> <p>For instance the following produces two toplevel Tk windows on screen:</p> <pre><code>import tkinter as tk root = tk.Tk() dlg = tk.Toplevel(root) </code></pre> <p>One significant difference ...
1
2016-10-15T21:00:42Z
[ "python", "windows", "tkinter" ]
Explanation for re.split() error?
40,063,797
<p>I'm sure you see this a lot but just wanted to warn you that I'm still very new to coding in general and have a lot to learn. I've been attempting teaching myself by working on a personal project and youtube whenever I have the time. </p> <p>Long version: I always get an error when I use the split function, but I s...
0
2016-10-15T20:17:50Z
40,063,847
<p>What you have is not an error, it's a warning.</p> <p>For one, I think you should not use a raw string, you need <code>'\u00b0'</code>, the character. And <code>'c*'</code> will match 0 or more of <code>c</code>, so it matches the empty string. I believe this is what the warning is about. I suggest that you use</p>...
2
2016-10-15T20:24:47Z
[ "python", "split" ]
Explanation for re.split() error?
40,063,797
<p>I'm sure you see this a lot but just wanted to warn you that I'm still very new to coding in general and have a lot to learn. I've been attempting teaching myself by working on a personal project and youtube whenever I have the time. </p> <p>Long version: I always get an error when I use the split function, but I s...
0
2016-10-15T20:17:50Z
40,063,961
<p>Since you are using regular expressions, you could parse the entire string with a single regex, and take advantage of grouping:</p> <pre><code>import re def decimal_alt(x): REGEX = re.compile( u"([NS])\\s(\\d+)\u00B0(\\d+)\'(\\d+)\"") rm = REGEX.match(x) if rm is not None: sign = -1 if rm.group(1) == 'S'...
1
2016-10-15T20:36:42Z
[ "python", "split" ]
How call arguments stack works in Python?
40,063,929
<p>I am learning python and trying to get idea how stack works in python. I have some doubts. I know how stack work and i have read many articles and tutorials about it. I have read many threads on stackoverflow they are all good, still I have some doubts.</p> <p>As far I have read stack stores and return values of f...
-1
2016-10-15T20:33:17Z
40,064,190
<p>If you're interested how python works under the hood, there is a standard CPython library <a href="https://docs.python.org/2/library/dis.html" rel="nofollow">dis</a>. Here is the output for your test code:</p> <pre><code>&gt;&gt;&gt; import dis &gt;&gt;&gt; def test(): ... a = 9 ... b = 2 ... c = 13 ......
0
2016-10-15T21:04:21Z
[ "python", "stack", "callstack" ]
How call arguments stack works in Python?
40,063,929
<p>I am learning python and trying to get idea how stack works in python. I have some doubts. I know how stack work and i have read many articles and tutorials about it. I have read many threads on stackoverflow they are all good, still I have some doubts.</p> <p>As far I have read stack stores and return values of f...
-1
2016-10-15T20:33:17Z
40,064,483
<p>Although stacks work as a LIFO, you have to be careful about exactly which data structures are being stacked. For instance, many programming languages use a stack to store parameters and local variables when calling a function. But the thing that is being stacked is the entire call frame, not the individual variable...
0
2016-10-15T21:38:11Z
[ "python", "stack", "callstack" ]
Make python read 12 from file as 12 not 1 and 2
40,063,930
<p>Trying to make a program that provides the price to different numbers of stages. In "tripss.txt",third line is the number 12, python interprets it as 1 and 2 instead and gives the price for each rather than the number as a whole, any way to fix it to that it's read as 12?.</p> <pre><code>infile = open("tripss.txt",...
-2
2016-10-15T20:33:30Z
40,064,065
<p>In your code it seems that you want to consider customer_three as a list of strings. However in your code it is a string, not a list of strings, and so the for loop iterates on the characters of the string ("1" and "2").<br> So I suggest you to replace: </p> <pre><code>customer_three= infile.readline().strip("\n")...
0
2016-10-15T20:48:17Z
[ "python", "file", "for-loop", "numbers", "readlines" ]
Make python read 12 from file as 12 not 1 and 2
40,063,930
<p>Trying to make a program that provides the price to different numbers of stages. In "tripss.txt",third line is the number 12, python interprets it as 1 and 2 instead and gives the price for each rather than the number as a whole, any way to fix it to that it's read as 12?.</p> <pre><code>infile = open("tripss.txt",...
-2
2016-10-15T20:33:30Z
40,064,328
<p>You say <em>third line is the number 12</em> so after <code>customer_three= infile.readline().strip("\n")</code>, <code>customer_three</code> will be the string <code>"12"</code>. If you then start the for loop <code>for number in customer_three:</code>, <code>number</code> will be assigned each element of the strin...
0
2016-10-15T21:18:58Z
[ "python", "file", "for-loop", "numbers", "readlines" ]
Convert QueryDict into list of arguments
40,064,010
<p>I'm receiving via POST request the next payload through the view below:</p> <pre><code>class CustomView(APIView): """ POST data """ def post(self, request): extr= externalAPI() return Response(extr.addData(request.data)) </code></pre> <p>And in the <code>externalAPI</code> class I have the...
0
2016-10-15T20:42:53Z
40,064,117
<p>You can write a helper function that walks through the <em>QueryDict</em> object and converts valid <em>JSON</em> objects to Python objects, string objects that are digits to integers and returns the first item of lists from lists:</p> <pre><code>import json def restruct(d): for k in d: # convert value...
1
2016-10-15T20:54:22Z
[ "python", "json", "django", "dictionary" ]
Why is Python 3.5 crashing on a MySQL connection with correct credentials?
40,064,012
<p>I'm using Python 3.5.1, mysqlclient 1.3.9 (fork of MySQLdb that supports Python 3), and MariaDB 10.1 on Windows 10 (64-bit).</p> <p>When I run</p> <pre><code>import MySQLdb con = MySQLdb.connect(user=my_user, passwd=my_pass, db=my_db) </code></pre> <p>Python crashes.</p> <p>In pycharm, I am also presented with t...
0
2016-10-15T20:42:59Z
40,082,843
<p>I'm not familiar with <code>pycharm</code> but I think your problem is as @nemanjap suggests, with your <code>MySQLdb</code> installation. I just went through a similar nightmare (with Python 3.5), so I hope I can help. Here are my suggestions:</p> <ul> <li>If you haven't already, install <code>pip</code></li> <li>...
1
2016-10-17T09:30:23Z
[ "python", "mysql", "python-3.x", "mariadb" ]
XOR very big List with its rotation
40,064,067
<p>Efficient way to XOR on list such that,</p> <p>eg:</p> <pre><code>#here a,b,c,d are integers L = [a,b,c,d] N = [b,c,d,a] #right rotation of list L Newlist = enter code here[a^b, b^c, c ^d ,d^a] </code></pre> <p>as size of list is very large, is there any efficient way to solve.</p> <p>this is so far what i have...
0
2016-10-15T20:48:23Z
40,064,123
<p>You can try to check this:</p> <pre><code>from collections import deque L = [6, 7, 1, 3] L2 = deque(L) L2.rotate(-1) # rotate to left result = [i ^ j for i, j in zip(L, L2)] </code></pre> <p>This might be at least slightly faster.</p> <p>Other solution would be to check this possibility:</p> <pre><code>from ite...
3
2016-10-15T20:54:59Z
[ "python", "xor" ]
XOR very big List with its rotation
40,064,067
<p>Efficient way to XOR on list such that,</p> <p>eg:</p> <pre><code>#here a,b,c,d are integers L = [a,b,c,d] N = [b,c,d,a] #right rotation of list L Newlist = enter code here[a^b, b^c, c ^d ,d^a] </code></pre> <p>as size of list is very large, is there any efficient way to solve.</p> <p>this is so far what i have...
0
2016-10-15T20:48:23Z
40,064,299
<p>Here is another approach. The generator I've written could probably be improved, but it gives you the idea. This is space efficient, because you are not building a new list:</p> <pre><code>&gt;&gt;&gt; def rotation(lst,n): ... for i in range(len(lst)): ... yield lst[(i + n) % len(lst)] ... &gt;&gt;&gt; L = [...
0
2016-10-15T21:15:19Z
[ "python", "xor" ]
XOR very big List with its rotation
40,064,067
<p>Efficient way to XOR on list such that,</p> <p>eg:</p> <pre><code>#here a,b,c,d are integers L = [a,b,c,d] N = [b,c,d,a] #right rotation of list L Newlist = enter code here[a^b, b^c, c ^d ,d^a] </code></pre> <p>as size of list is very large, is there any efficient way to solve.</p> <p>this is so far what i have...
0
2016-10-15T20:48:23Z
40,064,389
<p>Here's another method!</p> <p>I define a function that, given an index, returns the number at that index and its next neighbor on the "right" as a pair <code>(a, b)</code>, and then XOR those. It is also safe to give it indices outside the range of the list. So:</p> <pre><code>def rotate_and_xor(l): def get_pa...
0
2016-10-15T21:26:34Z
[ "python", "xor" ]
Python: importing a sub-package module from both the sub-package and the main package
40,064,202
<p>Here we go with my first ever stackoverflow quesion. I did search for an answer, but couldn't find a clear one. Here's the situation. I've got a structure like this:</p> <pre><code>myapp package/ __init.py__ main.py mod1.py mod2.py </code></pre> <p>Now, in this scenario, fro...
2
2016-10-15T21:06:00Z
40,064,571
<p>The reason this is happening is because how python looks for modules and packages when you run a python script as the <code>__main__</code> script.</p> <p>When you run <code>python main.py</code>, python will add the parent directory of <code>main.py</code> to the pythonpath, meaning packages and modules within the...
1
2016-10-15T21:51:27Z
[ "python", "import" ]
Wait for threads to finish before running them again
40,064,337
<p>I am making a program that controls 2 motors through a raspberry Pi. I am running python code and I am wondering how to achieve the following :</p> <ul> <li>Run motor1</li> <li>Run motor2 simultaneously</li> <li>Wait for both motors to finish</li> <li>Run motor1</li> <li>Run motor2 simultaneously</li> <li><p>etc.</...
1
2016-10-15T21:19:51Z
40,064,713
<p>You can use <a href="https://docs.python.org/2/library/threading.html#threading.Semaphore" rel="nofollow"><code>Semaphore</code></a> actually:</p> <pre><code>from threading import Semaphore class Stepper(Thread): def __init__(self, stepper, semaphore): Thread.__init__(self) self.stepper = step...
1
2016-10-15T22:05:55Z
[ "python", "multithreading", "raspberry-pi", "python-multithreading" ]
Wait for threads to finish before running them again
40,064,337
<p>I am making a program that controls 2 motors through a raspberry Pi. I am running python code and I am wondering how to achieve the following :</p> <ul> <li>Run motor1</li> <li>Run motor2 simultaneously</li> <li>Wait for both motors to finish</li> <li>Run motor1</li> <li>Run motor2 simultaneously</li> <li><p>etc.</...
1
2016-10-15T21:19:51Z
40,064,754
<p>You can use the thread's <code>join</code> method like so:</p> <pre><code>thread_1.join() # Wait for thread_1 to finish thread_2.join() # Same for thread_2 </code></pre> <p>As per the documentation at <a href="https://docs.python.org/3/library/threading.html#threading.Thread.join" rel="nofollow">https://docs.pytho...
0
2016-10-15T22:10:04Z
[ "python", "multithreading", "raspberry-pi", "python-multithreading" ]
Multiplying spaces with length of input
40,064,369
<p>python newbie here. I'm trying to print a 5 line pyramid of text based off the user's input if the string is even. I'm having trouble making the pyramid centre without hardcoding the spaces in. In line 2 I'm getting "TypeError: unsupported operand type(s) for -: 'str' and 'int' If len is returning the length and int...
0
2016-10-15T21:23:29Z
40,064,386
<p><code>*</code> has higher precendence than <code>-</code>, so you must wrap them in parenthesis</p> <pre><code>space = ' ' * (len(userString) - 1) </code></pre>
0
2016-10-15T21:25:53Z
[ "python" ]
Most Pythonic way to find/check items in a list with O(1) complexity?
40,064,377
<p>The problem I'm facing is finding/checking items in a list with O(1) complexity. The following has a complexity of O(n):</p> <pre><code>'foo' in list_bar </code></pre> <p>This has a complexity of O(n) because you are using the <code>in</code> keyword on a <code>list</code>. (Refer to <a href="https://wiki.python.o...
3
2016-10-15T21:24:43Z
40,064,454
<p>In general, it's impossible to find elements in a <code>list</code> in constant time. You could hypothetically maintain both a <code>list</code> and a <code>set</code>, but updating operations will take linear time.</p> <p>You mention that your motivation is</p> <blockquote> <p>a list, and not a set, is largely ...
7
2016-10-15T21:33:53Z
[ "python", "algorithm", "performance", "python-3.x", "time-complexity" ]
urls.py entry for django v1.10 mysite.com:8000/index.html
40,064,411
<p>I'm having trouble getting the url entry in my app's urls.py file how I want it. When a person enters <code>mysite.com:8000/</code>, I want it to use the same view as <code>mysite.com:8000/index.html</code> I can use <code>url(r'^index.html$', views.index, name='index'),</code> and the view is properly displayed wh...
1
2016-10-15T21:28:34Z
40,064,484
<p>You can use the following regex pattern that matches 0 or 1 repetitions of <code>'index.html'</code> in the url i.e. either <code>^$</code> or <code>r'^index.html$'</code>:</p> <pre><code>&gt;&gt;&gt; re.match(r'^(?:index\.html)?$', 'index.html') &lt;_sre.SRE_Match object; span=(0, 10), match='index.html'&gt; &gt;&...
1
2016-10-15T21:38:13Z
[ "python", "html", "django" ]
Issues with shaping Tensorflow/TFLearn inputs/outputs for images
40,064,422
<p>To learn more about deep learning and computer vision, I'm working on a project to perform lane-detection on roads. I'm using TFLearn as a wrapper around Tensorflow.</p> <p><strong>Background</strong></p> <p>The training inputs are images of roads (each image represented as a 50x50 pixel 2D array, with each elemen...
4
2016-10-15T21:30:02Z
40,064,653
<p>Have a look at the imageflow wrapper for tensorflow, which converts a numpy array containing multiple images into a .tfrecords file, which is the suggested format for using tensorflow <a href="https://github.com/HamedMP/ImageFlow" rel="nofollow">https://github.com/HamedMP/ImageFlow</a>.</p> <p>You have to install i...
1
2016-10-15T21:59:45Z
[ "python", "machine-learning", "computer-vision", "neural-network", "tensorflow" ]
Share DB connection in a process pool
40,064,437
<p>I have a Python 3 program that updates a large list of rows based on their ids (in a table in a Postgres 9.5 database).</p> <p>I use multiprocessing to speed up the process. As Psycopg's connections can’t be shared across processes, I create a connection <strong>for each row</strong>, then close it.</p> <p>Overa...
1
2016-10-15T21:32:00Z
40,064,748
<p>You can use the <strong>initializer</strong> parameter of the Pool constructor. Setup the DB connection in the initializer function. Maybe pass the connection credentials as parameters.</p> <p>Have a look at the docs: <a href="https://docs.python.org/3/library/multiprocessing.html#module-multiprocessing.pool" rel="...
0
2016-10-15T22:09:40Z
[ "python", "postgresql", "multiprocessing", "psycopg2" ]
Python: Unable to remove spaces from list
40,064,559
<p>I am trying to remove white spaces from a list of strings in Python. I have tried almost every other method, but still I am not able to remove the spaces. Here is the list:</p> <pre><code>names=[': A slund\n', ': N Brenner and B Jessop and M Jones and G Macleod\n', ': C Boone\n', ': PB Evans\n', ': F Neil utitle: u...
0
2016-10-15T21:48:39Z
40,064,591
<p>With list comprehension.</p> <pre><code>names_without_space = [name.replace(' ', '') for name in names] print(names_without_space[:3]) # [':Aslund\n', ':NBrennerandBJessopandMJonesandGMacleod\n', ':CBoone\n'] </code></pre>
1
2016-10-15T21:53:41Z
[ "python", "list", "spaces" ]
Python search text file and count occurrences of a specified string
40,064,565
<p>I am attempting to use python to search a text file and count the number of times a user defined word appears. But when I run my code below instead of getting a sum of the number of times that unique word appears in the file, I am getting a count for the number lines within that file contain that word. </p> <p>Exam...
0
2016-10-15T21:50:21Z
40,064,630
<p>One way to do this would be to loop over the words after you split the line and increment <code>count</code> for each matching word:</p> <pre><code>user_search_value = raw_input("Enter the value or string to search for: ") count = 0 with open(file.txt, 'r') as f: for line in f.readlines(): words =...
0
2016-10-15T21:58:13Z
[ "python", "python-2.7", "string-matching" ]
Python search text file and count occurrences of a specified string
40,064,565
<p>I am attempting to use python to search a text file and count the number of times a user defined word appears. But when I run my code below instead of getting a sum of the number of times that unique word appears in the file, I am getting a count for the number lines within that file contain that word. </p> <p>Exam...
0
2016-10-15T21:50:21Z
40,075,922
<p>As I mentioned in the comment above, after playing with this for a (long) while I figured it out. My code is below.</p> <pre><code>#read file f = open(filename, "r") lines = f.readlines() f.close() #looking for patterns for line in lines: line = line.strip().lower().split() for words in line: if wo...
0
2016-10-16T21:59:25Z
[ "python", "python-2.7", "string-matching" ]
Image display error after changing dtype of image matrix
40,064,587
<p>I'm using opencv + python to process fundus(retinal images). There is a problem that im facing while converting a float64 image to uint8 image.</p> <p><strong>Following is the python code:</strong></p> <pre><code>import cv2 import matplotlib.pyplot as plt import numpy as np from tkFileDialog import askopenfilename...
1
2016-10-15T21:52:55Z
40,064,690
<p>Usually when Images are represented with np float64 arrays, RGB values are in range 0 to 1. So when converting to uint8 there is a possible precision loss when converting from float64 to uint8.</p> <p>I would directly create Dd as a:</p> <pre><code>Dd = np.zeros((height, width), dtype=np.uint8) </code></pre> <p>T...
1
2016-10-15T22:03:57Z
[ "python", "opencv", "numpy" ]
Image display error after changing dtype of image matrix
40,064,587
<p>I'm using opencv + python to process fundus(retinal images). There is a problem that im facing while converting a float64 image to uint8 image.</p> <p><strong>Following is the python code:</strong></p> <pre><code>import cv2 import matplotlib.pyplot as plt import numpy as np from tkFileDialog import askopenfilename...
1
2016-10-15T21:52:55Z
40,082,027
<p>Look I executed your code and there are the <a href="http://postimg.org/gallery/1qi7dozn0" rel="nofollow">results</a></p> <p>They seem pretty normal to me... this is the exact <a href="https://pastebin.com/6jwgKi9r" rel="nofollow">code</a> I used</p> <p>Ar is different from the others because when you <code>imShow...
1
2016-10-17T08:48:48Z
[ "python", "opencv", "numpy" ]
Google search scrapper , Python
40,064,588
<p>I am new to Python and trying to make a Google search scrapper for the purpose of getting stock prices , but I run my code below I dont get any results instead I am getting the page HTML formatting.</p> <pre><code>import urllib.request from bs4 import BeautifulSoup import requests url = 'https://www.google.com/we...
1
2016-10-15T21:53:08Z
40,064,707
<p>Check out <code>Beautiful Soup's</code> <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#find-all" rel="nofollow">documentation</a> on how to select elements of the HTML document you just parsed you could try something like:</p> <p><code>soup.findAll("span", ['_Rnb', 'fmob_pr, 'fac-l'])</code></p> <...
0
2016-10-15T22:05:18Z
[ "python", "parsing", "beautifulsoup", "urllib" ]
Google search scrapper , Python
40,064,588
<p>I am new to Python and trying to make a Google search scrapper for the purpose of getting stock prices , but I run my code below I dont get any results instead I am getting the page HTML formatting.</p> <pre><code>import urllib.request from bs4 import BeautifulSoup import requests url = 'https://www.google.com/we...
1
2016-10-15T21:53:08Z
40,064,906
<p>Like @Jeff mentioned, this kind of tasks are easier to handle by APIs rather than scrapping web pages.</p> <p>Here is a solution using Yahoo Finance API</p> <pre><code>import urllib2 response = urllib2.urlopen('http://finance.yahoo.com/d/quotes.csv?s=UWTI&amp;f=sa') print response.read() </code></pre> <p>Output:<...
-1
2016-10-15T22:30:30Z
[ "python", "parsing", "beautifulsoup", "urllib" ]
Google search scrapper , Python
40,064,588
<p>I am new to Python and trying to make a Google search scrapper for the purpose of getting stock prices , but I run my code below I dont get any results instead I am getting the page HTML formatting.</p> <pre><code>import urllib.request from bs4 import BeautifulSoup import requests url = 'https://www.google.com/we...
1
2016-10-15T21:53:08Z
40,065,315
<p>It is in the source when you right-click and choose view-source in your browser. You just need to change the <em>url</em> slightly and pass a <em>user-agent</em> to match what you see there using requests:</p> <pre><code>In [2]: from bs4 import BeautifulSoup ...: import requests ...: ...: url = 'https://w...
2
2016-10-15T23:36:40Z
[ "python", "parsing", "beautifulsoup", "urllib" ]
Counting sub-element in string?
40,064,589
<p>Say I have a <code>string = "Nobody will give me pancakes anymore"</code></p> <p>I want to count each word in the string. So I do <code>string.split()</code> to get a list in order to get <code>['Nobody', 'will', 'give', 'me', 'pancakes', 'anymore']</code>.</p> <p>But when I want to know the length of <code>'Nobod...
0
2016-10-15T21:53:09Z
40,064,601
<p>You took the first letter of <code>string[0]</code>, ignoring the result of the <code>string.split()</code> call.</p> <p>Store the split result; that's a list with individual words:</p> <pre><code>words = string.split() first_worth_length = len(words[0]) </code></pre> <p>Demo:</p> <pre><code>&gt;&gt;&gt; string ...
4
2016-10-15T21:54:51Z
[ "python", "list", "string-length" ]
Counting sub-element in string?
40,064,589
<p>Say I have a <code>string = "Nobody will give me pancakes anymore"</code></p> <p>I want to count each word in the string. So I do <code>string.split()</code> to get a list in order to get <code>['Nobody', 'will', 'give', 'me', 'pancakes', 'anymore']</code>.</p> <p>But when I want to know the length of <code>'Nobod...
0
2016-10-15T21:53:09Z
40,064,640
<p>Yup, <code>string[0]</code> is just <code>'N'</code></p> <p>Regarding your statement...</p> <blockquote> <p>I want to count each word in the string</p> </blockquote> <pre><code>&gt;&gt;&gt; s = "Nobody will give me pancakes anymore" &gt;&gt;&gt; lens = map(lambda x: len(x), s.split()) &gt;&gt;&gt; print lens [6...
1
2016-10-15T21:58:40Z
[ "python", "list", "string-length" ]
Counting sub-element in string?
40,064,589
<p>Say I have a <code>string = "Nobody will give me pancakes anymore"</code></p> <p>I want to count each word in the string. So I do <code>string.split()</code> to get a list in order to get <code>['Nobody', 'will', 'give', 'me', 'pancakes', 'anymore']</code>.</p> <p>But when I want to know the length of <code>'Nobod...
0
2016-10-15T21:53:09Z
40,064,994
<pre><code>words = s.split() d = {word : len(word) for word in words} or words = s.split() d = {} for word in words: if word not in d: d[word]=0 d[word]+=len(word) In [15]: d Out[15]: {'me': 2, 'anymore': 7, 'give': 4, 'pancakes': 8, 'Nobody': 6, 'will': 4} In [16]: d['Nobody'] Out[16]: 6 </c...
0
2016-10-15T22:41:42Z
[ "python", "list", "string-length" ]
python program to find prime number n by seeing if they can divide evenly into prime numbers less that the squareroot of n
40,064,657
<p>How do I make this return the right results for primes less than 10 ?</p> <pre><code>from math import * def isPrime(n): i = [c for c in range(int(sqrt(n)),0,-1) if c % 2 != 0 and c &gt; 1 ] for x in i: if n % x == 0: return print('%s is not prime' % (n)) return print('%s is prime number' %(n)) def...
-3
2016-10-15T22:00:08Z
40,064,716
<pre><code>i = [c for c in range(int(sqrt(n)),0,-1) if c % 2 != 0] </code></pre> <p>This code is skipping all even divisors. This is correct for <em>most</em> divisors, but it incorrectly skips 2, so it will misclassify even numbers!</p> <p>You need to make an exception for 2, either in the filter or by adding a spec...
0
2016-10-15T22:06:16Z
[ "python" ]
python program to find prime number n by seeing if they can divide evenly into prime numbers less that the squareroot of n
40,064,657
<p>How do I make this return the right results for primes less than 10 ?</p> <pre><code>from math import * def isPrime(n): i = [c for c in range(int(sqrt(n)),0,-1) if c % 2 != 0 and c &gt; 1 ] for x in i: if n % x == 0: return print('%s is not prime' % (n)) return print('%s is prime number' %(n)) def...
-3
2016-10-15T22:00:08Z
40,064,791
<p>Your error is that you exit the <code>for</code> loop in the first iteration <em>always</em>. You should only exit when you find it has a divisor, but otherwise you should keep looping. When you exit the loop without finding a divisor then is the time to return that fact.</p> <p>So change:</p> <pre><code>for x in ...
0
2016-10-15T22:13:34Z
[ "python" ]
python program to find prime number n by seeing if they can divide evenly into prime numbers less that the squareroot of n
40,064,657
<p>How do I make this return the right results for primes less than 10 ?</p> <pre><code>from math import * def isPrime(n): i = [c for c in range(int(sqrt(n)),0,-1) if c % 2 != 0 and c &gt; 1 ] for x in i: if n % x == 0: return print('%s is not prime' % (n)) return print('%s is prime number' %(n)) def...
-3
2016-10-15T22:00:08Z
40,064,984
<p>As suggested by @Duskwolf, the line where you check for primes is wrong. A replacement function could simply be </p> <pre><code>import numpy as np def isPrime(n): len = int(sqrt(n)) divisors = np.zeros(len, dtype=np.bool) for i in range(1,len): if(n%(i+1)==0): divisors[i]=True p...
0
2016-10-15T22:40:37Z
[ "python" ]
IndexError: list index of range. Python 3
40,064,660
<p>I was just trying to create a Matrix filled with zeros, like the function of numpy.</p> <p>But it continues to give me that error. Here's the code:</p> <pre><code>def zeros(a,b): for i in range(a): for j in range(b): R[i][j]=0 return R </code></pre> <p>I tried with a=3 and b=2, s...
-2
2016-10-15T22:00:29Z
40,064,741
<p>You could do that:</p> <pre><code>&gt;&gt;&gt; def zeros(a,b): ... return [[0 for _ in range(a)] for _ in range(b)] ... &gt;&gt;&gt; zeros(3,2) [[0, 0, 0], [0, 0, 0]] </code></pre> <p>Or something more close to your code:</p> <pre><code>def zeros(a,b): R = [] l = [0]*a for _ in range(b): R...
0
2016-10-15T22:09:12Z
[ "python", "python-3.x" ]
Python abundant, deficient, or perfect number
40,064,750
<pre><code>def classify(numb): i=1 j=1 sum=0 for i in range(numb): for j in range(numb): if (i*j==numb): sum=sum+i sum=sum+j if sum&gt;numb: print("The value",numb,"is an abundant number.") elif sum&lt;numb: ...
3
2016-10-15T22:09:45Z
40,064,812
<p>I would highly recommend u to create a one function which creates the proper divisor of given N, and after that, the job would be easy.</p> <pre><code>def get_divs(n): return [i for i in range(1, n) if n % i == 0] def classify(num): divs_sum = sum(get_divs(num)) if divs_sum &gt; num: print('{}...
2
2016-10-15T22:17:30Z
[ "python", "for-loop", "indentation", "break" ]
Python abundant, deficient, or perfect number
40,064,750
<pre><code>def classify(numb): i=1 j=1 sum=0 for i in range(numb): for j in range(numb): if (i*j==numb): sum=sum+i sum=sum+j if sum&gt;numb: print("The value",numb,"is an abundant number.") elif sum&lt;numb: ...
3
2016-10-15T22:09:45Z
40,065,111
<p>Somewhere you are misinterpreting something. As is you are printing what kind the number is, as many times as the value of the number. I might be missing something but anyway. </p> <p>The sum of proper divisors can be found naively through using modulo </p> <pre><code>def classify1(num): div_sum = sum(x for x ...
0
2016-10-15T23:01:29Z
[ "python", "for-loop", "indentation", "break" ]
Get list of variables from Jinja2 template (parent and child)
40,064,867
<p>I'm trying to get a list of variables from a Jinja2 template.</p> <p>test1.j2:</p> <pre><code>some-non-relevant-content {{var1}} {% include 'test2.j2' %} </code></pre> <p>test2.j2:</p> <pre><code>another-text {{var2}} </code></pre> <p>I can get variables from test1 easily:</p> <pre><code>env = Environment(load...
0
2016-10-15T22:25:43Z
40,069,288
<p>Found a way to code that without a big pain. meta.find_referenced_templates helps to load all child templates when applied recursively. When done, it's trivial to get variables from all templates in a single list.</p>
0
2016-10-16T10:31:39Z
[ "python", "python-3.x", "jinja2" ]
Splitting strings unhashable type
40,064,881
<p>I have never split strings in Python before so I am not too sure what is going wrong here. </p> <pre><code>import pyowm owm = pyowm.OWM('####################') location = owm.weather_at_place('Leicester, uk') weather = location.get_weather() weather.get_temperature('celsius') temperature = weather.get_temperature...
1
2016-10-15T22:27:55Z
40,064,912
<p><code>get_temperature</code> returns a dictionary, which you're then trying to index with a <code>slice</code> object, which is not hashable. e.g.</p> <pre><code>&gt;&gt;&gt; hash(slice(5, 10)) Traceback (most recent call last): ...
2
2016-10-15T22:31:56Z
[ "python", "python-3.x" ]
python different print output for <class 'str'> and <class 'str'>
40,064,939
<p>This is probably a basic question for most, yet it's not making sense to me.</p> <p>When I try to print a str in the interpreter i'm getting different results back even though when I <code>type</code> them they are the same.</p> <p>Here's the whole thing -></p> <pre><code>&gt;&gt;&gt; print(abs.__doc__) abs(numbe...
-1
2016-10-15T22:34:52Z
40,064,953
<p>You're confusing a string, with an expression, <code>'abs.__doc__'</code> (string) is different from <code>abs.__doc__</code> (expression), you can evaluate the string as an expression with the <code>exec</code> function (Which you most probably shouldn't do unless you know what you're doing)</p>
0
2016-10-15T22:36:34Z
[ "python" ]
Working with strings in Python: Formatting the information in a very specific way
40,064,997
<p>OBS: I am working on Python 3.5.2 and I use the standard Shell and IDLE</p> <p>Hi everyone, I think one of the most difficult tasks I have when programming with python is dealing with strings. Is there someone who can help?</p> <p>One of the problems I face frequently is transforming the string so I can use it pro...
1
2016-10-15T22:41:56Z
40,065,033
<p>Maybe something like this will work:</p> <pre><code>commands = my_input.split('!!!') my_commands = [c.split(' ', 2) for c in commands] </code></pre> <p>The second argument of the <code>split</code> methods tells it how many times you want it to split the string.</p>
3
2016-10-15T22:48:26Z
[ "python", "string", "python-3.x" ]
Regex taking too long in python
40,065,108
<p>I have used regex101 to test my regex and it works fine.What i am trying to is to detect these patterns</p> <ol> <li>section 1.2 random 2</li> <li>1.2 random 2</li> <li>1.2. random 2</li> <li>random 2</li> <li>random 2.</li> </ol> <p>But its just random it shouldn't match if the string is like that</p> <ol> <li>r...
2
2016-10-15T23:00:58Z
40,065,276
<p>After some simplification, this regular expression meets the requirements stated above and reproduced in the test cases below.</p> <pre><code>import re regex = r'(?:section)*\s*(?:[0-9.])*\s*random\s+(?!random)(?:[0-9.])*' strings = [ "random random random random random", "section 1.2 random 2", "1.2 ran...
1
2016-10-15T23:29:08Z
[ "python", "regex" ]
check user security for modifying objects
40,065,155
<p>I am thinking about security implementation for my python web app. For example I have user and profiles. Each user can edit his profile by sending POST at /profile/user_id</p> <p>On every request i can get session user_id and compare it with profile.user_id if they not same - raise SecurityException().</p> <p>But ...
0
2016-10-15T23:09:11Z
40,069,274
<blockquote> <p>/profile/4?key=secret</p> </blockquote> <p>Practical issues:</p> <ul> <li>it's generally a bad idea to put a secret in a URL. URLs leak easily through logs, history, referrers etc. Also it breaks navigation. It's better to put the secret in a cookie or POST data.</li> <li>you would typically include...
2
2016-10-16T10:29:43Z
[ "python", "security", "web-applications" ]
Enumeration Program
40,065,285
<p>I'm in the process of creating a program that takes an IP address, performs an nmap scan, and takes the output and puts it in a text file. The scan works fine, but I can't seem to figure out why it's not writing anything to the text file.</p> <p>Here is what I have so far</p> <pre><code>if __name__ == "__main__": ...
0
2016-10-15T23:30:38Z
40,065,306
<p>You're using print statements in your show_scan() function. Instead try passing the file reference to show_scan() and replacing the print() calls with f.write() calls. This would save to file everything you're currently printing to the terminal.</p> <p>Alternatively you could just change your code so that the show_...
0
2016-10-15T23:34:38Z
[ "python", "text-files", "nmap" ]
UnsupportedOperationException: Cannot evalute expression: .. when adding new column withColumn() and udf()
40,065,302
<p>So what I am trying to do is simply to convert fields: <code>year, month, day, hour, minute</code> (which are of type integer as seen below) into a string type.</p> <p>So I have a dataframe df_src of type :</p> <pre><code>&lt;class 'pyspark.sql.dataframe.DataFrame'&gt; </code></pre> <p>and here is its schema: </p...
0
2016-10-15T23:34:10Z
40,077,911
<p>allright..I think I understand the problem...The cause is because my dataFrame just had a lot of data loaded in memory causing <code>show()</code> action to fail.</p> <p>The way I realize it is that what is causing the exception : </p> <pre><code>Py4JJavaError: An error occurred while calling o2108.showString. : j...
0
2016-10-17T03:06:10Z
[ "python", "apache-spark", "pyspark" ]
Creating an array of tensors in tensorflow?
40,065,313
<p>Suppose I have two tensor variables each of size 2x4:</p> <pre><code>v1 = tf.logical_and(a1, b1) v2 = tf.logical_and(a2, b2) </code></pre> <p>Instead, I want to store these in an array called <code>v</code> which is of size 2x2x4. How do I do this in Tensorflow? The idea would be something like this:</p> <pre><co...
0
2016-10-15T23:36:22Z
40,065,373
<p>tf.pack() is probably what you are looking for.</p>
1
2016-10-15T23:45:09Z
[ "python", "arrays", "numpy", "tensorflow" ]
How to include git dependencies in setup.py for pip installation
40,065,321
<p>I need to include Python packages available via public Github repositories along with my Python (2.7) package. My package should be installable via <code>pip</code> using <code>setup.py</code>.</p> <p>So far, this could be done using <code>dependency_links</code> in the <code>setup.py</code> file:</p> <pre class="...
2
2016-10-15T23:36:58Z
40,065,404
<p>I always create a <code>requirements.txt</code> which contains all of my dependencies which can then be installed using <code>pip install -r requirements.txt</code>. A usual <code>requirements.txt</code> looks like this (this is just an example):</p> <pre><code>pytz==2016.4 six==1.10.0 SQLAlchemy==1.0.13 watchdog==...
0
2016-10-15T23:50:14Z
[ "python", "git", "pip", "setup.py" ]
PiCameraValueError: Incorrect buffer length for resolution 1920x1080
40,065,328
<p>This is my code to detect circle/balls. I want to detect soccer ball from Pi camera. (soccer ball could be in any color.) I am having trouble with some PiCameraValueError. What is wrong with this code. I am using Raspberry Pi 2, Python2, and OpenCV.</p> <pre><code>from picamera.array import PiRGBArray from picamera...
1
2016-10-15T23:38:13Z
40,066,149
<p>As explained <a href="https://github.com/waveform80/picamera" rel="nofollow">here</a>,</p> <blockquote> <p>the <code>PiCameraValueError</code> is a secondary exception raised in response to the KeyboardInterrupt exception. This is quite normal and not a bug (it's more a consequence of how generic the output m...
0
2016-10-16T02:15:47Z
[ "python", "opencv", "raspberry-pi", "detection", "raspbian" ]
Python using custom color in plot
40,065,378
<p>I'm having a problem that (I think) should have a fairly simple solution. I'm still a relative novice in Python, so apologies if I'm doing something obviously wrong. I'm just trying to create a simple plot with multiple lines, where each line is colored by its own specific, user-defined color. When I run the followi...
2
2016-10-15T23:45:44Z
40,065,407
<p>In the <code>plot</code> command, you could enter Hex colours. A much more simple way to beautify your plot would be to simply use matplotlib styles. For instance, before any plot function, just write <code>plt.style.use('ggplot')</code></p>
0
2016-10-15T23:51:16Z
[ "python", "numpy", "matplotlib", "colors" ]
Python using custom color in plot
40,065,378
<p>I'm having a problem that (I think) should have a fairly simple solution. I'm still a relative novice in Python, so apologies if I'm doing something obviously wrong. I'm just trying to create a simple plot with multiple lines, where each line is colored by its own specific, user-defined color. When I run the followi...
2
2016-10-15T23:45:44Z
40,072,897
<p>The statement <br>ax.plot(x, mpt1, color='dbz53', label='53 dBz') <br>is wrong with quoted dbz53. Where python treated it as a string of unknown rgb value. <br>You can simply put color='#DD3044', and it will work. <br>Or you can try <br>color=dbz53.get_hex() <br>without quote if you want to use the colour module yo...
0
2016-10-16T16:57:19Z
[ "python", "numpy", "matplotlib", "colors" ]
Finding and replacing a value in a Python dictionary
40,065,381
<p>I'm a complete newbie to stackoverflow, so please excuse me if I end up posting this in the wrong place (or any other newbie-related mitakes! Thanks!).</p> <p>My question pertains to Python 3.x, where I am trying to basically access a value in a very small dictionary (3 keys, 1 value each). I have searched high and...
-3
2016-10-15T23:46:06Z
40,065,439
<p>You first must find the key that has the value <code>"Rose"</code>:</p> <pre><code>for color, flower in a1.items(): if flower == "Rose": a1[color] = "Tulip" </code></pre>
0
2016-10-15T23:57:29Z
[ "python", "dictionary", "replace", "find" ]
Tensorflow: Converting a tenor [B, T, S] to list of B tensors shaped [T, S]
40,065,396
<p>Tensorflow: Converting a tenor [B, T, S] to list of B tensors shaped [T, S]. Where B, T, S are whole positive numbers ...</p> <p>How can I convert this? I can't do eval because no session is running at the time I want to do this.</p>
0
2016-10-15T23:49:10Z
40,065,428
<p>It sounds like you want tf.unpack()</p>
0
2016-10-15T23:55:58Z
[ "python", "tensorflow", "deep-learning", "lstm" ]
Google Maps API Python/R
40,065,448
<p>I am trying to use the google maps API for <a href="https://developers.google.com/maps/documentation/javascript/places#place_search_requests" rel="nofollow">nearby</a> search and ideally I'd use a <a href="https://developers.google.com/maps/documentation/javascript/reference#LatLngBounds" rel="nofollow">latlngBounds...
0
2016-10-15T23:58:48Z
40,075,423
<p>As you've alluded to, the Javascript API allows you to use a LatLngBounds object, however, the <a href="https://developers.google.com/places/web-service/search" rel="nofollow">web services API</a> does not.</p> <p>A couple of options I can suggest</p> <ol> <li><p>Write some Javascript and parse it yourself in R us...
0
2016-10-16T21:00:55Z
[ "python", "google-maps" ]
Numpy repeat for 2d array
40,065,479
<p>Given two arrays, say </p> <pre><code>arr = array([10, 24, 24, 24, 1, 21, 1, 21, 0, 0], dtype=int32) rep = array([3, 2, 2, 0, 0, 0, 0, 0, 0, 0], dtype=int32) </code></pre> <p>np.repeat(arr, rep) returns </p> <pre><code>array([10, 10, 10, 24, 24, 24, 24], dtype=int32) </code></pre> <p>Is there any way to repl...
5
2016-10-16T00:01:25Z
40,065,645
<p>So you have a different repeat array for each row? But the total number of repeats per row is the same?</p> <p>Just do the <code>repeat</code> on the flattened arrays, and reshape back to the correct number of rows.</p> <pre><code>In [529]: np.repeat(arr,rep.flat) Out[529]: array([10, 10, 10, 24, 24, 24, 24, 10, ...
3
2016-10-16T00:34:37Z
[ "python", "arrays", "numpy", "vectorization" ]
Numpy repeat for 2d array
40,065,479
<p>Given two arrays, say </p> <pre><code>arr = array([10, 24, 24, 24, 1, 21, 1, 21, 0, 0], dtype=int32) rep = array([3, 2, 2, 0, 0, 0, 0, 0, 0, 0], dtype=int32) </code></pre> <p>np.repeat(arr, rep) returns </p> <pre><code>array([10, 10, 10, 24, 24, 24, 24], dtype=int32) </code></pre> <p>Is there any way to repl...
5
2016-10-16T00:01:25Z
40,066,467
<p>Another solution similar to @hpaulj's solution:</p> <pre><code>def repeat2dvect(arr, rep): lens = rep.sum(axis=-1) maxlen = lens.max() ret_val = np.zeros((arr.shape[0], maxlen)) mask = (lens[:,None]&gt;np.arange(maxlen)) ret_val[mask] = np.repeat(arr.ravel(), rep.ravel()) return ret_val </co...
1
2016-10-16T03:17:33Z
[ "python", "arrays", "numpy", "vectorization" ]
Python - Removing 1 char from a series of nested lists
40,065,495
<p>I've solved the problem with the code below, but I'm trying to understand a better way to strip out the zeros at the end of the each string of numbers because they throw off the calculation. The solution I have seems heavy handed, is there a more elegant way to solve this without a for loop removing the 0s?</p> <h1...
-1
2016-10-16T00:07:00Z
40,065,517
<p>As far getting the job done I think looks okay. Why not just do:</p> <pre><code>If r[-1] == 0: Del r[-1] </code></pre>
-1
2016-10-16T00:12:08Z
[ "python", "list" ]
Python - Removing 1 char from a series of nested lists
40,065,495
<p>I've solved the problem with the code below, but I'm trying to understand a better way to strip out the zeros at the end of the each string of numbers because they throw off the calculation. The solution I have seems heavy handed, is there a more elegant way to solve this without a for loop removing the 0s?</p> <h1...
-1
2016-10-16T00:07:00Z
40,065,520
<p>You can do it all in one go using slicing and list comprehension:</p> <pre><code>lin = [map(int,i.split())[:-1] for i in inp[1:]] </code></pre>
0
2016-10-16T00:12:54Z
[ "python", "list" ]
Python - Removing 1 char from a series of nested lists
40,065,495
<p>I've solved the problem with the code below, but I'm trying to understand a better way to strip out the zeros at the end of the each string of numbers because they throw off the calculation. The solution I have seems heavy handed, is there a more elegant way to solve this without a for loop removing the 0s?</p> <h1...
-1
2016-10-16T00:07:00Z
40,065,529
<p>Cant you just do:</p> <pre><code>lin=[] for line in sys.stdin: lin.append([float(e) for e in line.split()[:-1]]) </code></pre> <p>So that becomes a single line:</p> <pre><code>lin=[[float(e) for e in line.split()[:-1]] for line in sys.stdin] </code></pre> <p>Then your averages become:</p> <pre><code>avgs=[s...
-1
2016-10-16T00:14:10Z
[ "python", "list" ]
Connecting to a SQL db using python
40,065,615
<p>I currently have a python script that can connect to a mySQL db and execute queries. I wish to modify it so that I can connect to a different SQL db to run a separate query. I am having trouble doing this, running osx 10.11. This is my first question and I'm a newbie programmer so please take it easy on me...</p>...
0
2016-10-16T00:29:33Z
40,069,734
<p>You can use a Python library called SQLAlchemy. It abstracts away the "low-level" operations you would do with a database (e.g. specifying queries manually).</p> <p>A tutorial for using SQLAlchemy can be found <a href="http://www.rmunn.com/sqlalchemy-tutorial/tutorial.html" rel="nofollow">here</a>.</p>
0
2016-10-16T11:29:51Z
[ "python", "mysql", "sql", "database" ]
Connecting to a SQL db using python
40,065,615
<p>I currently have a python script that can connect to a mySQL db and execute queries. I wish to modify it so that I can connect to a different SQL db to run a separate query. I am having trouble doing this, running osx 10.11. This is my first question and I'm a newbie programmer so please take it easy on me...</p>...
0
2016-10-16T00:29:33Z
40,114,063
<p>I was able to get connected using SQL Alchemy--thank you. If anyone else tries, I think you'll need a ODBC driver per this page: </p> <p><a href="http://docs.sqlalchemy.org/en/latest/dialects/mssql.html" rel="nofollow">http://docs.sqlalchemy.org/en/latest/dialects/mssql.html</a></p> <p>Alternatively, pymssql is a...
0
2016-10-18T17:00:25Z
[ "python", "mysql", "sql", "database" ]
Python Pandas Concat "WHERE" a Condition is met
40,065,641
<p>How can I "concat" a specific column from many Python Pandas dataframes, WHERE another column in each of the many dataframes meets a certain condition (colloquially termed condition "X" here).</p> <p>In SQL this would be simple using JOIN clause with WHERE df2.Col2 = "X" and df3.Col2 = "X" and df4.col2 = "X"... etc...
2
2016-10-16T00:33:21Z
40,068,065
<p>consider the <code>list</code> <code>dfs</code> of <code>pd.DataFrame</code>s</p> <pre><code>import pandas as pd import numpy as np np.random.seed([3,1415]) dfs = [pd.DataFrame(np.random.rand(10, 2), columns=['Col1', 'Col2']) for _ in range(5)] </code></pre> <p>I'll use <code>pd.concat</code>...
2
2016-10-16T07:42:07Z
[ "python", "pandas", "join", "where", "concat" ]
TypeError: 'float' object is not subscriptable in 3d array
40,065,702
<p>guys I'm trying to write a function which get a 3-D array and check how many of its cells are empty. but i will got the following error</p> <pre><code>in checkpoint if m[i][j][0] == 0: TypeError: 'float' object is not subscriptable </code></pre> <p>my function is as following</p> <pre><code>def checkpoint(m, i, ...
0
2016-10-16T00:44:05Z
40,065,751
<p>That means m is not actually 3d array, the code is trying to do <code>[i]</code> or <code>[i][j]</code> or <code>[i][j][0]</code> on a <code>float</code>. </p> <p>"containers" are "scriptable" as described <a href="http://stackoverflow.com/questions/216972/in-python-what-does-it-mean-if-an-object-is-subscriptable-o...
0
2016-10-16T00:51:51Z
[ "python", "arrays", "python-3.x", "object", "typeerror" ]
Collecting Summary Statistics on Dataframe built by randomly sampling other dataframes
40,065,703
<p>My goal is to build a dataframe by randomly sampling from other dataframes, collecting summary statistics on the new dataframe, and then append those statistics to a list. Ideally, I can iterate through this process n number of times (e.g. bootstrap). </p> <pre><code>dfposlist = [OFdf, Firstdf, Seconddf, Thirddf, C...
1
2016-10-16T00:44:07Z
40,067,759
<p>Here (with random data):</p> <pre><code>import pandas as pd import numpy as np dfposlist = dict(zip(range(10), [pd.DataFrame(np.random.randn(10, 5), columns=list('abcde')) for i in range(10)])) for df in dfposlist.values(): df['f'] = ...
2
2016-10-16T07:00:57Z
[ "python", "loops", "pandas", "dictionary" ]
Python Import Dependency
40,065,715
<p>I know this question has been asked many times, but even after I tried many SO suggestions, I still cannot get it right. So, posting here for your help.</p> <p>I'm building a simple web server with Flask-Restful and Flask-SqlAlchemy. Basically, I think I'm getting an error because of a circular import. My <strong>W...
0
2016-10-16T00:45:58Z
40,065,739
<p>Change your import to look like this:</p> <pre><code>from app import models </code></pre> <p>And then use <code>models.WidgetModel</code> / <code>models.VisualizationModel</code> instead.</p> <p>The problem is that you're creating a circular import dependency where both files require the other file to already hav...
1
2016-10-16T00:50:07Z
[ "python", "flask-sqlalchemy", "flask-restful" ]
I'm trying to write a line of code at ask the user for two inputs but can't figure out how to complete this
40,065,720
<h1>Why does this line of code not split the two</h1> <pre><code>Lat1,long1 = input("Enter the Lat and Long of the source point separated by a comma eg 20,30").split() </code></pre>
0
2016-10-16T00:47:15Z
40,065,740
<p>By default using <code>split()</code> will only split on a space. You are asking the user to enter two entries separated by a <code>,</code>, so you will end up getting a</p> <pre><code>ValueError: not enough values to unpack (expected 2, got 1) </code></pre> <p>To resolve this, you need to split on the identifier...
2
2016-10-16T00:50:13Z
[ "python", "split" ]
How can i find the closest match
40,065,725
<p>I am matching values which is slightly different in that case how can i find the closest match</p> <p>In this example everything has very close relationship but how can my script find a match</p> <p>Eg script which i wrote</p> <pre><code>a = ["12,th 3rd street","6th avenue 3r cross","6th street pan,CA","345 hosto...
0
2016-10-16T00:47:43Z
40,065,823
<p>I hope you need some predefined words for matching <code>this or that</code>.</p> <pre><code>for eg., {cross:{cr,crs}, avenue:{av,avn}} </code></pre> <p>you can match the some continuous strings directly </p> <pre><code>for i in a: for j in b: if i in j or j in i: print (i,j) </code></pre>...
0
2016-10-16T01:07:55Z
[ "python", "algorithm", "data-structures", "string-matching" ]
Why does this code take so long to be executed? - Python
40,065,760
<p>I coded this on Python. It took way too long to finish if the input were just 40x40 (it's for image processing using <code>numpy</code>). Its behavious is the following: there's an array with objects in it (which have an 'image' attribute which is a numpy array) and then I check if that object is somewhere in anothe...
0
2016-10-16T00:53:10Z
40,065,951
<p>Instead of this:</p> <pre><code>if not np.array_equal(self.__sub_images[i][j].get_image(), to_compare_image.get_sub_images()[k][l].get_image()): same = False else: same = True #snip if not same: #snip </code></pre> <p>You can do this:</p> <pre><code>same=np.array_equal(self.__sub_images[i][j].get_...
-1
2016-10-16T01:34:35Z
[ "python", "performance", "loops" ]