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
Python3 - Loop over rows, then some columns to print text
40,050,625
<p>I have a pandas dataframe that looks something like this:</p> <pre><code> 0 1 2 3 \ 0 UICEX_0001 path/to/bam_T.bam path/to/bam_N.bam chr1:10000 1 UICEX_0002 path/to/bam_T2.bam path/to/bam_N2.bam chr54:4958392 4 0 chr4:...
0
2016-10-14T19:24:38Z
40,093,468
<p>I've come up with the answer. There are a few problems here:</p> <ol> <li>I was using <code>iterrows()</code> incorrectly.</li> </ol> <p>The iterrows object actually holds the information from the rows, and then you can use the index to save values from that Series.</p> <pre><code>for index, row in x.iterrows():...
0
2016-10-17T18:43:05Z
[ "python", "pandas" ]
Cannot import urllib in Python
40,050,630
<p>I would like to import <code>urllib</code> to use the function '<code>request</code>'. However, I encountered an error when trying to download via Pycharm: </p> <blockquote> <p>"Could not find a version that satisfies the requirement urllib (from versions: ) No matching distribution found for urllib" </p> </block...
-2
2016-10-14T19:25:00Z
40,050,845
<p>A few things:</p> <ol> <li>As metioned in the comments, <code>urllib</code> is not installed through <code>pip</code>, it is part of the standard library, so you can just do <code>import urllib</code> without installation. </li> <li>Python 3.x has a <a href="https://docs.python.org/3/library/urllib.request.html" re...
1
2016-10-14T19:40:17Z
[ "python", "python-2.7" ]
More efficient way to loop through PySpark DataFrame and create new columns
40,050,680
<p>I am converting some code written with Pandas to PySpark. The code has a lot of <code>for</code> loops to create a variable number of columns depending on user-specified inputs.</p> <p>I'm using Spark 1.6.x, with the following sample code:</p> <pre><code>from pyspark.sql import SQLContext from pyspark.sql import f...
1
2016-10-14T19:28:36Z
40,051,839
<p>One withColumn will work on entire rdd. So generally its not a good practise to use the method for every column you want to add. There is a way where you work with columns and their data inside a map function. Since one map function is doing the job here, the code to add new column and its data will be done in paral...
-1
2016-10-14T20:55:25Z
[ "python", "apache-spark", "pyspark" ]
More efficient way to loop through PySpark DataFrame and create new columns
40,050,680
<p>I am converting some code written with Pandas to PySpark. The code has a lot of <code>for</code> loops to create a variable number of columns depending on user-specified inputs.</p> <p>I'm using Spark 1.6.x, with the following sample code:</p> <pre><code>from pyspark.sql import SQLContext from pyspark.sql import f...
1
2016-10-14T19:28:36Z
40,058,813
<p>There is a small overhead of repeatedly calling JVM method but otherwise for loop alone shouldn't be a problem. You can improve it slightly by using a single select:</p> <pre><code>df = spark.range(1, 11).toDF("val1") def make_col(i): return (F.pow(F.lit(i), 2) + F.col("val1")).alias("val_{0}".format(i)) spar...
1
2016-10-15T12:06:34Z
[ "python", "apache-spark", "pyspark" ]
Python Matrix Multiplication and Caching
40,050,761
<p>I am investigating caching behavior in different languages. I create two matrices in python using lists (yes, I know it's a linked list but bear with me here). I then multiply these matrices together in three ways:</p> <pre><code>def baseline_matrix_multiply(a, b, n): ''' baseline multiply ''' c = z...
0
2016-10-14T19:33:39Z
40,050,931
<p>Python tends to not cache the results of its functions. It requires explicit notice of when you want build a cache for a function. You can do this using the <code>lrc_cache</code> decorator.</p> <p>The following is code I threw together the other day and I've just added some readability. If there's something wrong,...
0
2016-10-14T19:46:43Z
[ "python", "caching", "matrix" ]
Python Matrix Multiplication and Caching
40,050,761
<p>I am investigating caching behavior in different languages. I create two matrices in python using lists (yes, I know it's a linked list but bear with me here). I then multiply these matrices together in three ways:</p> <pre><code>def baseline_matrix_multiply(a, b, n): ''' baseline multiply ''' c = z...
0
2016-10-14T19:33:39Z
40,051,019
<p>The latter version (block multiplication) is only faster by 30% because you save 30% of index accessing by using a local variable in the inner loop!</p> <p>(and FYI this is not C++: <code>list</code> type is like C++ <code>vector</code> otherwise people would waste their time trying to access elements by index. So ...
1
2016-10-14T19:53:47Z
[ "python", "caching", "matrix" ]
Parse file upon initialization and make accessible to all classes
40,050,777
<p>Essentially, when the pyramid app starts, I need to parse a file and make the data from that file available to the whole app. On top of that, I need to monitor the file for changes, it's essentially a config file. I was considering just making a singleton and initializing it when the app starts up when Configurator ...
0
2016-10-14T19:34:59Z
40,069,623
<p>As noted in many places, <a href="http://stackoverflow.com/questions/137975/what-is-so-bad-about-singletons">Singleton is considered a code smell</a> and as such, should be avoided. IMHO, a <code>Singleton</code> <em>can</em> be used if there's a reasonable trade-off. For example, if using a <code>Singleton</code> b...
1
2016-10-16T11:14:49Z
[ "python", "python-2.7", "oop", "pyramid" ]
root.query_pointer()._data causes high CPU usage
40,050,780
<p>I'm a total noob in Python, programming and Linux. I wrote a simple python script to track usage time of various apps. I've noticed that after some time python is going nuts utilizing 100% of the CPU. Turns out it's the code obtaining mouse position is causing issues.</p> <p>I've tried running this code in an empty...
2
2016-10-14T19:35:09Z
40,051,138
<p>To keep the CPU usual steady I put <code>display.Display().screen()</code> before the loop so that it didn't have to do so much work all the time. The screen shouldn't change so nor should that value so it made sense to set it up before.</p> <pre><code>import time from Xlib import display disp = display.Display().s...
1
2016-10-14T20:01:55Z
[ "python", "linux" ]
Loop driver.get URL (webdriver python)
40,050,837
<p>How can i loop a URL infinitely in Python Selenium WebDriver? I have tried time.sleep driver.refresh() but it is not very efficient. </p> <pre><code> from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC ...
0
2016-10-14T19:39:31Z
40,053,848
<pre><code>from selenium import webdriver driver = webdriver.Chrome() driver.maximize_window() print "To quit the program, please kill the program or close browser" while True: driver.get("http://www.bbc.com/") </code></pre> <p>This will help to solve your problem</p>
1
2016-10-15T00:43:48Z
[ "python", "selenium", "selenium-webdriver", "webdriver" ]
Code is not working on an mac OSX with python 2.7.12
40,050,841
<p>I want to use this code for my data distribution, but I can't save the file or when I run this in python directly I got this error:</p> <blockquote> <p>Unsupported characters in input</p> </blockquote> <p>I think this code is generated on a windows environment and this is not working for macOSX. I installed all ...
0
2016-10-14T19:39:46Z
40,050,883
<p>Your python interpreter is finding an invalid chapter because the encoding on the file is wrong. You need to change the encoding of the file to utf-8 you can do this by adding this line:</p> <pre><code> # -*- coding: utf8 -*- </code></pre> <p>To the header of the file that you are working on</p> <p>You also ne...
0
2016-10-14T19:43:20Z
[ "python", "osx", "python-2.7", "unsupportedoperation" ]
Merge Sort count comparisons
40,050,849
<p>The questions are: 1) Is that correct code to count comparisons? 2) How can I return counter with sorted list like ([1,2,3,4], number_of_comparisons) Code:</p> <pre><code>counter = 0 def merge_sort(lst): """Sorts the input list using the merge sort algorithm. &gt;&gt;&gt; lst = [4, 5, 1, 6, 3] &gt;&gt;&gt; merge_s...
0
2016-10-14T19:40:48Z
40,051,235
<p>The answer is yes, this code may count the number of comparisons, but you have to clearly understand what do you want to count</p> <p>Here are some modifications, you may remove them if you don't need them</p> <pre><code>counter = 0 def merge_sort(lst): global counter if len(lst) &lt;= 1: counte...
0
2016-10-14T20:08:38Z
[ "python" ]
Merge Sort count comparisons
40,050,849
<p>The questions are: 1) Is that correct code to count comparisons? 2) How can I return counter with sorted list like ([1,2,3,4], number_of_comparisons) Code:</p> <pre><code>counter = 0 def merge_sort(lst): """Sorts the input list using the merge sort algorithm. &gt;&gt;&gt; lst = [4, 5, 1, 6, 3] &gt;&gt;&gt; merge_s...
0
2016-10-14T19:40:48Z
40,057,517
<p>I've found a solution in that way:</p> <pre><code>def merge_sort(input_array): counter = 0 if len(input_array) &lt;= 1: return input_array, counter left_part = merge_sort(input_array[:len(input_array) // 2]) right_part = merge_sort(input_array[len(left_part[0]):]) counter += left_part[1] + right_part[1] lef...
0
2016-10-15T09:49:06Z
[ "python" ]
Determining a sparse matrix quotient
40,050,947
<p>I am looking to divide two sparce matricies in python 2.7, essentially <code>k = numerator / denominator</code>, with the result as a sparse matrix of type <code>sp.csr_matrix</code>. I am using <code>scipy as sp</code> and <code>numpy as np</code>. </p> <p>To do this, I am following linear format of taking the dot...
0
2016-10-14T19:47:56Z
40,051,408
<p>Borrowing from the 2013 answer:</p> <pre><code>In [409]: a=np.random.rand(3,3) In [410]: A=sparse.csr_matrix(a) In [411]: np.linalg.inv(a) Out[411]: array([[ 26.11275413, -4.17749006, -9.82626551], [-37.22611759, 9.38404027, 13.80073216], [ 7.59314843, -2.04314605, -1.58410661]]) </code></pre...
2
2016-10-14T20:21:21Z
[ "python", "performance", "numpy", "scipy" ]
TCP client cannot connect to TCP server
40,050,999
<p>I have configured a Raspberry Pi to be client, and my personal computer to be TCP server, and trying to connect to server via an ethernet cable. On my personal computer I use Comm Operator and select port "1234". Raspberry Pi (TCP client) has following setup:</p> <pre><code>auto eth0 iface eth0 inet static addres...
1
2016-10-14T19:52:00Z
40,052,279
<p>You probably have a firewall running on your computer. Disable it or open up the desired port.</p>
1
2016-10-14T21:29:02Z
[ "python", "linux", "sockets", "tcp", "raspberry-pi" ]
Python popen wait command not behaving as expected
40,051,037
<p>I've a powershell script which calls an API and returns 0 or 99 based on if the POST request went through. My powershell code:</p> <pre><code>try { Invoke-RestMethod -uri $url -Method Post -Body $body -ContentType 'application/json' -ErrorAction Stop return 0 } catch { return 99 } </code></pre> <p>Thi...
0
2016-10-14T19:54:41Z
40,051,311
<p>req.wait() will return the exit code of the program you ran. In this case, power shell returns a good exit code of 0. It seems to just print out "99", which is what you are seeing in the output.</p> <p>You may want to use: </p> <pre><code>out = subprocess.check_output(...) print out </code></pre>
1
2016-10-14T20:13:53Z
[ "python", "powershell", "popen" ]
Python popen wait command not behaving as expected
40,051,037
<p>I've a powershell script which calls an API and returns 0 or 99 based on if the POST request went through. My powershell code:</p> <pre><code>try { Invoke-RestMethod -uri $url -Method Post -Body $body -ContentType 'application/json' -ErrorAction Stop return 0 } catch { return 99 } </code></pre> <p>Thi...
0
2016-10-14T19:54:41Z
40,051,422
<p>The 99 is output created by PowerShell because you used <code>return</code> instead of <code>exit</code>. Because of that the script prints 99 and exits with an exit code of 0 (which is what <code>req.wait()</code> receives). Also, your PowerShell commandline isn't built in a way to actually return a proper exit cod...
2
2016-10-14T20:22:36Z
[ "python", "powershell", "popen" ]
How do you store two different inputs from the same variable?
40,051,073
<p>Had to delete most (of shown script). The code was a major part of my coursework, thus i'd rather others wouldn't see it and try to copy the majority of my code. I can leave the relevant part to the question though.</p> <pre><code>while n == 1: w = input("Input the product code: ") </code></pre> <p>As I said c...
2
2016-10-14T19:57:29Z
40,051,111
<pre><code>inputs = [] for i in range(expected_number_of_inputs): inputs.append(input('Product Code: ')) for i in inputs: print(i) </code></pre>
1
2016-10-14T20:00:01Z
[ "python" ]
How do you store two different inputs from the same variable?
40,051,073
<p>Had to delete most (of shown script). The code was a major part of my coursework, thus i'd rather others wouldn't see it and try to copy the majority of my code. I can leave the relevant part to the question though.</p> <pre><code>while n == 1: w = input("Input the product code: ") </code></pre> <p>As I said c...
2
2016-10-14T19:57:29Z
40,051,147
<p>You can do this in two separate ways but the way you are trying to do it will not work. You cannot have a variable that is not a list hold two values.</p> <p>Solution 1: use two variables</p> <pre><code>w1 = input("value1") w2 = input("value2") print(w1) print(w2) </code></pre> <p>Solution 2: use a list</p> <pre...
0
2016-10-14T20:02:34Z
[ "python" ]
How do you store two different inputs from the same variable?
40,051,073
<p>Had to delete most (of shown script). The code was a major part of my coursework, thus i'd rather others wouldn't see it and try to copy the majority of my code. I can leave the relevant part to the question though.</p> <pre><code>while n == 1: w = input("Input the product code: ") </code></pre> <p>As I said c...
2
2016-10-14T19:57:29Z
40,051,232
<p>Use a container type instead of a single variable. In this case, <code>list()</code> would seem appropriate:</p> <pre><code>inputs = [] # use a list to add each input value to while n == 1: inputs.append(input("Input the product code: ")) # each time the user inputs a string, added it to the inputs list for i i...
0
2016-10-14T20:08:27Z
[ "python" ]
Copy keys and list contents from JSON in python
40,051,155
<p>I am trying to skim through a dictionary that contains asymmetrical data and make a list of unique headings. Aside from the normal key:value items, the data within the dictionary also includes other dictionaries, lists, lists of dictionaries, NoneTypes, and so on at various levels throughout. I would like to be ab...
1
2016-10-14T20:03:06Z
40,052,070
<p>You can try something like:</p> <pre><code> def skim(obj, connector=':', level=0, builded_str= ''): if isinstance(obj, dict): for k, v in obj.items(): if isinstance(v, dict) and v: yield from skim(v, connector, level + 1, builded_str + k + connector) elif isinstan...
0
2016-10-14T21:12:22Z
[ "python", "json", "types", "nested", "iterable" ]
Webpy: Variables not showing properly in html
40,051,163
<p>I'm getting an error while using webpy, my string is "No client", but when opening html in browser i get only 'No', the white space and rest of string is lost! What I'm doing wrong?</p> <p>This is what is in the .html part:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel...
-2
2016-10-14T20:03:30Z
40,055,255
<p>I think you just need to put quotes around the values. Your example should become:</p> <pre><code>&lt;input type="text" placeholder="$:nome2" value="$:nome2" name="nome3" id="nome3" readonly&gt; </code></pre>
0
2016-10-15T05:18:45Z
[ "python", "html", "web.py" ]
MiniBatchKMeans OverflowError: cannot convert float infinity to integer?
40,051,170
<p>I am trying to find the right number of clusters, <code>k</code>, according to silhouette scores using <code>sklearn.cluster.MiniBatchKMeans</code>.</p> <pre><code>from sklearn.cluster import MiniBatchKMeans from sklearn.feature_extraction.text import HashingVectorizer docs = ['hello monkey goodbye thank you', 'go...
0
2016-10-14T20:04:02Z
40,053,639
<p>Let's analyze your code:</p> <ul> <li><code>for k in range(5)</code> returns the following sequence: <ul> <li><code>0, 1, 2, 3, 4</code></li> </ul></li> <li><code>model = MiniBatchKMeans(n_clusters = k)</code> inits model with <code>n_clusters=k</code></li> <li>Let's look at the first iteration: <ul> <li><code>n_...
1
2016-10-15T00:06:48Z
[ "python", "types", "scikit-learn", "infinity" ]
Having trouble with Python functions in my Guess The Number Game P
40,051,178
<p>I'm having troubles getting a proper readout, guessed keeps coming up as undefined but I have definitely defined it there.</p> <p>Sorry about the terrible code, I'm really really new to this.</p> <p>If there are any problems past my probably really easy to see simple mistake, please inform me about that too!</p> ...
-2
2016-10-14T20:04:31Z
40,051,476
<p>I think I know why you have a problem: you probably <em>renamed</em> your <code>guess</code> method by <code>guessing</code> but <em>not in the <code>main</code> function</em>.</p> <p>But since PyScripter (or your editor) has previously run with the previous name, it has a copy of the old method in memory, hence th...
0
2016-10-14T20:27:26Z
[ "python", "function" ]
Having trouble with Python functions in my Guess The Number Game P
40,051,178
<p>I'm having troubles getting a proper readout, guessed keeps coming up as undefined but I have definitely defined it there.</p> <p>Sorry about the terrible code, I'm really really new to this.</p> <p>If there are any problems past my probably really easy to see simple mistake, please inform me about that too!</p> ...
-2
2016-10-14T20:04:31Z
40,051,534
<p>Like others pointed out, calling out the wrong function was the main one, still, there are other errors present. I'm using Python 3.5 so I had to edit it a bit. It's not perfect but it runs, just so you can learn from it.</p> <pre><code>import random def main(): print ("Hello what is your name?") name = ...
0
2016-10-14T20:31:30Z
[ "python", "function" ]
Move python folder on linux
40,051,205
<p>I have compiled python sources with the <code>--prefix</code> option. After running <code>make install</code> the binaries are copied to a folder of my account's home directory.</p> <p>I needed to rename this folder but when I use pip after the renaming it says that it can't find the python interpreter. It shows an...
2
2016-10-14T20:06:32Z
40,051,396
<p>Pip is a python script. Open it and see : </p> <p>it begins with <code>#!/usr/bin/python</code></p> <p>You can either create a symbolic link in the old path to point to the new one, or replace the shebang with the new path. You can also keep your distrib interpreter safe by leaving it be and set the compiled one i...
4
2016-10-14T20:20:25Z
[ "python", "linux", "python-3.5" ]
Scraping cached pages
40,051,215
<p>I'm using <code>scrapy</code> in order to fetch some web content, in this fashion:</p> <pre><code>class PitchforkTracks(scrapy.Spider): name = "pitchfork_tracks" allowed_domains = ["pitchfork.com"] start_urls = [ "http://pitchfork.com/reviews/best/tracks/?page=1", ...
0
2016-10-14T20:07:25Z
40,055,545
<p>you can use following Google URL for scraping cache page</p> <p><a href="http://webcache.googleusercontent.com/search?q=cache:http://pitchfork.com/reviews/best/tracks/?page=1" rel="nofollow">http://webcache.googleusercontent.com/search?q=cache:http://pitchfork.com/reviews/best/tracks/?page=1</a></p>
1
2016-10-15T05:58:09Z
[ "python", "scrapy", "browser-cache" ]
Access foreign key image in template
40,051,274
<p>I have the following models:</p> <pre><code>class Car(models.Model): # some fields class CarPhotos(models.Model): image = models.ImageField(upload_to='somewhere') car = models.ForeignKey(Car) </code></pre> <p>in views.py:</p> <pre><code>def car_list(request): cars = Car.objects.all() return r...
-1
2016-10-14T20:10:57Z
40,051,736
<p>To display all of them, you need to do something like:</p> <pre><code>{% for car in cars %} {% for photo in car.carphotos_set.all %} &lt;img src="{{ photo.image.url }}"&gt; {% endfor %} {% endfor %} </code></pre> <p>So loop through the cars, then nest-loop through the images per car.</p>
0
2016-10-14T20:46:20Z
[ "python", "django" ]
tensorflow generate "fake" random variables for the model
40,051,288
<pre><code>tf.set_random_seed(1) R = tf.Variable(tf.random_normal((2,2)), name="random_weights") with tf.Session() as sess: tf.set_random_seed(1) sess.run(tf.initialize_all_variables()) print(sess.run(R)) </code></pre> <p>for this piece of code, everytime I run it, it generates different variables, is that an...
0
2016-10-14T20:12:05Z
40,052,111
<p>Fix operation-level seed as <code>tf.Variable(tf.random_normal((2,2), seed=1)</code></p>
0
2016-10-14T21:15:58Z
[ "python", "tensorflow" ]
Defining the order of the arguments with argparse - Python
40,051,289
<p>I have the following command line tool:</p> <pre><code>import argparse parser = argparse.ArgumentParser(description = "A cool application.") parser.add_argument('positional') parser.add_argument('--optional1') parser.add_argument('--optional2') args = parser.parse_args() print args.positionals </code></pre> <p>T...
1
2016-10-14T20:12:10Z
40,051,582
<p>You would either have to provide your own help formatter, or specify an explicit usage string:</p> <pre><code>parser = argparse.ArgumentParser( description="A cool application.", usage="args.py [-h] positional [--optional1 OPTIONAL1] [--optional2 OPTIONAL2]") </code></pre> <p>The order in the help message,...
1
2016-10-14T20:35:04Z
[ "python", "command-line", "command", "argparse", "args" ]
Defining the order of the arguments with argparse - Python
40,051,289
<p>I have the following command line tool:</p> <pre><code>import argparse parser = argparse.ArgumentParser(description = "A cool application.") parser.add_argument('positional') parser.add_argument('--optional1') parser.add_argument('--optional2') args = parser.parse_args() print args.positionals </code></pre> <p>T...
1
2016-10-14T20:12:10Z
40,051,600
<p>With respect to each other the order of <code>positionals</code> is fixed - that's why they are called that. But <code>optionals</code> (the flagged arguments) can occur in any order, and usually can be interspersed with the postionals (there are some practical constrains when allowing variable length <code>nargs</...
0
2016-10-14T20:36:17Z
[ "python", "command-line", "command", "argparse", "args" ]
Dictionary key and value flipping themselves unexpectedly
40,051,320
<p>I am running python 3.5, and I've defined a function that creates XML SubElements and adds them under another element. The attributes are in a dictionary, but for some reason the dictionary keys and values will sometimes flip when I execute the script.</p> <p>Here is a snippet of kind of what I have (the code is br...
0
2016-10-14T20:15:02Z
40,051,357
<pre><code>attributes = [{'xmlns:g', 'http://base.google.com/ns/1.0'}] </code></pre> <p>This is a list containing a set, not a dictionary. Neither sets nor dictionaries are ordered.</p>
3
2016-10-14T20:18:03Z
[ "python", "xml" ]
Creating a pandas dataframe by adding columns
40,051,344
<p>Is there a way to create a dataframe by adding individual columns? </p> <p>Following is my code snippet:</p> <pre><code>df=pandas.DataFrame() for key in matrix: for beta in matrix[key]: df[key] = matrix[key][beta] print(df) </code></pre> <p>As you can see that I start by creating an empty dataframe an...
1
2016-10-14T20:16:53Z
40,051,559
<p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html" rel="nofollow"><code>DataFrame</code></a> constructor:</p> <pre><code>d = {'ABC10059536': {'577908224': '0.5902'}, 'ABC10799208': {'577908224': '0.369'}, 'ABC12564102': {'577908224': '0.163'}, 'ABC1744180...
1
2016-10-14T20:33:18Z
[ "python", "pandas", "dataframe" ]
Filter down dataframe
40,051,401
<p>I want to filter down a dataframe. Trying to use the standard boolean (multiple) expressions but it doesn't work. My code is:</p> <pre><code>import pandas as pd import numpy as np # Setting a dataframe dates = pd.date_range('1/1/2000', periods=10) df1 = pd.DataFrame(np.random.randn(10, 4), index=dates, columns=['...
0
2016-10-14T20:20:52Z
40,051,806
<p>No need for the anonymous lambda function. Simply filter with a boolean statement. Also, notice the use of the bitwise operator, <code>&amp;</code>, not boolean operator, <code>and</code>. Below are equivalent variants to filtering:</p> <pre><code>df1 = df1.query('(A &gt; -0.5) &amp; (A &lt; 0) &amp; (B &gt;= 0) &a...
2
2016-10-14T20:52:33Z
[ "python", "dataframe" ]
Calculate values without looping
40,051,479
<p>I am attempting to do a monte carlo-esque projection using pandas on some stock prices. I used numpy to create some random correlated values for percentage price change, however I am struggling on how to use those values to create a 'running tally' of the actual asset price. So I have a DataFrame that looks like t...
1
2016-10-14T20:27:34Z
40,052,698
<p>Is that what you want?</p> <pre><code>In [131]: new = df.add_suffix('_px') + 1 In [132]: new Out[132]: abc_px xyz_px def_px 0 1.093889 1.113750 1.082923 1 0.869707 0.851258 0.938110 2 1.062175 0.994537 1.022963 3 0.970959 0.984082 1.006735 4 0.951050 0.989055 0.965579 5 1.082868 1.08057...
1
2016-10-14T22:09:41Z
[ "python", "pandas" ]
python "'y' object has no attribute 'x'" when calling a grandparent method x
40,051,487
<p>Im attempting to call the grandparent method getColor() from the Class below.</p> <p>This is the grandparent class in its own file:</p> <pre><code>class IsVisible(object): def __init__(self): pass white = (255,255,255) black = (0,0,0) red = (255,0,0) blue = (0,0,255) green = (0,255,...
1
2016-10-14T20:27:48Z
40,051,578
<p>If it's just indentation (and nothing else is jumping out at me) &mdash;</p> <pre><code>class IsVisible(object): def __init__(self): pass white = (255,255,255) black = (0,0,0) red = (255,0,0) blue = (0,0,255) green = (0,255,0) def getColor(self): # &lt;--- indent this ...
1
2016-10-14T20:34:41Z
[ "python", "class", "inheritance", "pygame" ]
How to handle generator code inside a decorator?
40,051,499
<p>I'm attempting to write a login_required decorator for authenticating requests to a protected view in Django using a WSGI middleware.</p> <p>Here's my code:</p> <pre><code>def login_required(f, request_class=HTTPRequest): def _wrapper(*args, **kwargs): if not isinstance(args[0], request_class): ...
0
2016-10-14T20:29:09Z
40,054,455
<p>You can reference to the login_required decorator logic in <code>django/contrib/auth/decoractors.py</code></p> <p>It make use of <code>redirect_to_login</code> function to redirect to login page when login check is failed.</p> <pre><code>from django.contrib.auth.views import redirect_to_login return redirect_to_lo...
0
2016-10-15T02:55:38Z
[ "python", "django", "wsgi", "python-decorators" ]
Does a python-esque placeholder exist in the Javascript language?
40,051,523
<p>I am experienced in Python, but relatively new to the Javascript language. I know in Python, if I want to substitute a variable into a string (for instance) I could do it this way: </p> <p><code>s = "%s:%s" % (mins, secs)</code></p> <p>However, I can't find an equivalent way to substitute values in Javascript. Doe...
0
2016-10-14T20:30:47Z
40,051,544
<p>Not available in ES5, but it is available in ES6:</p> <p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals" rel="nofollow">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals</a></p> <p>Keep in mind this might not work right in the browser ...
2
2016-10-14T20:32:11Z
[ "javascript", "python" ]
New to programming, same result different program
40,051,524
<p>I'm taking my first course in programming, the course is meant for physics applications and the like. We have an exam coming up, my professor published a practice exam with the following question.</p> <blockquote> <p>The Maxwell distribution in speed v for an ideal gas consisting of particles of mass m at Kelvin ...
1
2016-10-14T20:30:57Z
40,051,863
<p>Things to be careful about when dealing with numbers is implicit type conversion from floats to ints. One instance I could figure in your code is that you use (3/2) which evaluates to 1, while the other code uses 1.5 directly. </p>
0
2016-10-14T20:57:33Z
[ "python", "algorithm" ]
How to run ShellCommandActivity on my own EC2 instance?
40,051,550
<p>I am trying to run a simple command to test a ShellCommandActivity with Data Pipeline from AWS.</p> <pre><code>&gt;&gt;&gt; /usr/bin/python /home/ubuntu/script.py </code></pre> <p>That script should create a file on a S3, I know I could create a S3 file using the same Data Pipeline, but I want to test how to execu...
0
2016-10-14T20:32:40Z
40,113,898
<p>One workaround is directly execute script.py like </p> <p>"command": "script.py"</p> <p>Be sure your script.py with header </p> <pre><code>#!/usr/bin/env python </code></pre>
0
2016-10-18T16:51:45Z
[ "python", "amazon-ec2", "amazon-data-pipeline" ]
iterating through passages for string extrction
40,051,565
<p>I came across this problem from a forum where these things are needed to be done: You will be given a sequence of passages, and must filter out any passage whose text (sequence of whitespace-delimited words) is wholly contained as a sub-passage of one or more of the other passages.</p> <p>When comparing for contain...
0
2016-10-14T20:33:40Z
40,053,840
<p>I literally coded this for you, hopefully it's easy to understand (I made it less optimal as such). Let me know if you need to speed it up or if you have any questions!</p> <p>BTW, this is python 3, just remove the brackets from the <code>print</code> statements and it will copy and paste and run for python 2.</p> ...
0
2016-10-15T00:42:33Z
[ "python", "string" ]
Pandas: Merge two dataframe columns
40,051,567
<p>Consider two dataframes:</p> <pre><code>df_a = pd.DataFrame([ ['a', 1], ['b', 2], ['c', NaN], ], columns=['name', 'value']) df_b = pd.DataFrame([ ['a', 1], ['b', NaN], ['c', 3], ['d', 4] ], columns=['name', 'value']) </code></pre> <p>So looking like<...
2
2016-10-14T20:33:54Z
40,051,595
<p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.combine_first.html" rel="nofollow"><code>combine_first</code></a>:</p> <pre><code>print (df_b.combine_first(df_a)) name value 0 a 1.0 1 b 2.0 2 c 3.0 3 d 4.0 </code></pre> <p>Or <a href="h...
3
2016-10-14T20:36:06Z
[ "python", "pandas", "dataframe", "merge" ]
OpenCV 3.1.0 with Python 3.5
40,051,573
<p>After following several different tutorials, guides and steps recommended in other SO answers I didn't manage to install OpenCV for use with Python 3.5 in my Ubuntu 16.04 system.</p> <p>As long as OpenCV 3.1.0 officially supports Python 3.x, how do I install it appropriately?</p>
1
2016-10-14T20:34:23Z
40,052,358
<p>I managed installing Python 3.5 and OpenCV library appropriately in my system after gathering steps and troubleshooting solutions over different tutorials and guides.</p> <p><em>The installation is performed under a virtualenv, so there is no need to clean up previous install attempts footprints from your system.</...
1
2016-10-14T21:35:25Z
[ "python", "linux", "opencv", "python-3.5", "opencv3.1" ]
Serial Numbers from a Storage Controller over SSH
40,051,576
<p><strong>Background</strong> <br> I'm working on a bash script to pull serial numbers and part numbers from all the devices in a server rack, my goal is to be able to run a single script (inventory.sh) and walk away while it generates text files containing the information I need. I'm using bash for maximum compatibil...
0
2016-10-14T20:34:32Z
40,055,963
<p>Have a look at SNMP. There is a reasonable chance that you can use SNMP tools to remotely extract the information you need. The manufacturer should be able to provide you with the MIBs.</p>
0
2016-10-15T06:50:47Z
[ "python", "linux", "bash", "perl", "ssh" ]
Working with increased precision of irrational numbers in python
40,051,584
<p>I am attempting to do a <a href="https://en.wikipedia.org/wiki/Continued_fraction" rel="nofollow">continued fraction derivation</a> of irrational numbers, e.g. sqrt(13), with Python. I have obtained a pretty good solution which is accurate for the first 10 or so iterations:</p> <ol> <li>Set the original number as c...
0
2016-10-14T20:35:11Z
40,051,796
<p>I don't know of any such placeholders in Python. </p> <p>However, you may consider using <a href="https://docs.python.org/2/library/decimal.html" rel="nofollow"><code>decimal.Decimal</code></a> which will increase the precision of your math operations but will never guarantee <em>infinite repetitions of the cycle</...
2
2016-10-14T20:51:35Z
[ "python", "precision" ]
Working with increased precision of irrational numbers in python
40,051,584
<p>I am attempting to do a <a href="https://en.wikipedia.org/wiki/Continued_fraction" rel="nofollow">continued fraction derivation</a> of irrational numbers, e.g. sqrt(13), with Python. I have obtained a pretty good solution which is accurate for the first 10 or so iterations:</p> <ol> <li>Set the original number as c...
0
2016-10-14T20:35:11Z
40,052,085
<p>You might cast an eye over <a href="https://rosettacode.org/wiki/Continued_fraction#Python" rel="nofollow">https://rosettacode.org/wiki/Continued_fraction#Python</a>. It uses the Fractions and Itertools modules.</p>
1
2016-10-14T21:13:55Z
[ "python", "precision" ]
Working with increased precision of irrational numbers in python
40,051,584
<p>I am attempting to do a <a href="https://en.wikipedia.org/wiki/Continued_fraction" rel="nofollow">continued fraction derivation</a> of irrational numbers, e.g. sqrt(13), with Python. I have obtained a pretty good solution which is accurate for the first 10 or so iterations:</p> <ol> <li>Set the original number as c...
0
2016-10-14T20:35:11Z
40,052,286
<p>Apparently Marius Becceanu has released <a href="https://web.archive.org/web/20151221205104/http://web.math.princeton.edu/mathlab/jr02fall/Periodicity/mariusjp.pdf" rel="nofollow">an algorithm for the specific continued fraction of sqrt(n)</a>, which is iterative and really nice. This algorithm does not require use ...
1
2016-10-14T21:29:36Z
[ "python", "precision" ]
packaging django application and deploying it locally
40,051,602
<p>I've never worked with Django before so forgive me if a question sounds stupid. </p> <p>I need to develop a web application, but I do not want to deploy it on a server. I need to package it, so that others would "install" it on their machine and run it. Why I want to do it this way? There are many reasons, which I ...
1
2016-10-14T20:36:19Z
40,051,673
<p>This is possible. However, the client machine would need to be equipped with the correct technologies for this to work. </p> <p>When you launch a web app on a server (live), the server is required to have certain settings and installs. For example, a Django web app: the server must have a version of Django installe...
0
2016-10-14T20:41:36Z
[ "python", "django" ]
packaging django application and deploying it locally
40,051,602
<p>I've never worked with Django before so forgive me if a question sounds stupid. </p> <p>I need to develop a web application, but I do not want to deploy it on a server. I need to package it, so that others would "install" it on their machine and run it. Why I want to do it this way? There are many reasons, which I ...
1
2016-10-14T20:36:19Z
40,051,692
<p>You need to either use a python to executable program, with Django already in it. The website files you can place into the dist folder or whatever folder has the executable in it. Then you can compress it and share it with others (who have the same OS as you).</p> <p>For an example:</p> <p>You have this script in ...
1
2016-10-14T20:42:47Z
[ "python", "django" ]
Creating a Knight Rider style streaming LED with a row of images in Python
40,051,731
<p>I'm learning python with the raspberry pi and a pi-face expansion board. Using Tkinter I've created a Gui with buttons to operate the pi-face LED's. In one part of the code I open a new window which shows a button and a row of images of a LED in the 'off' state. I'm trying to add some code to make the row of LED i...
0
2016-10-14T20:45:45Z
40,052,320
<p>You don't need threads for such a simple task. It's very easy to set up a persistent repeating task in tkinter, if the task doesn't take more than a couple hundred milliseconds (if it takes much longer, your UI will start to lag).</p> <p>The basic pattern is to write a function that does some work, and then have th...
1
2016-10-14T21:32:12Z
[ "python", "user-interface", "tkinter", "raspberry-pi", "led" ]
Creating a Knight Rider style streaming LED with a row of images in Python
40,051,731
<p>I'm learning python with the raspberry pi and a pi-face expansion board. Using Tkinter I've created a Gui with buttons to operate the pi-face LED's. In one part of the code I open a new window which shows a button and a row of images of a LED in the 'off' state. I'm trying to add some code to make the row of LED i...
0
2016-10-14T20:45:45Z
40,053,753
<p>Might not be exactly what you are looking for, but you can get some inspiration to set up this "cylon" algorithm on the terminal first. LEDs don't have intermediate color values, but I guess the remnant perception of light should do the trick. </p> <pre><code>import sys,time shift = lambda l, n=1: l[n:]+l[:n] c = u...
0
2016-10-15T00:26:13Z
[ "python", "user-interface", "tkinter", "raspberry-pi", "led" ]
An equivalent to python gdb.execute('...') in lldb
40,051,748
<p>If I have a structure like this (in C)</p> <pre><code>typedef struct { int x; int[2] y; } A; </code></pre> <p>And an instance of it, say <code>a</code> with <code>a.x=1</code> and <code>a.y={2,3}</code>.</p> <p>To access <code>a.y[1]</code> from python scripting, do I actually have to do this very voluble...
0
2016-10-14T20:47:19Z
40,052,835
<p>I'm not entirely sure what you want to do here. I'll answer a couple of potential questions, and you can tell me if one of them was right...</p> <p>If you're trying to find a nicer way to reach into known nested structures, this might be more convenient:</p> <pre><code>var = lldb.frame.FindVariable("a").GetValueF...
0
2016-10-14T22:25:20Z
[ "python", "lldb" ]
How to sort a list based on another list with integers Python
40,051,845
<p>So, I'm generally new at programming, and I was just wondering if it was possible to sort a list based not on the positions of another list, but the actual integers itself?</p> <pre><code>#Here is my list to be sorted sent = ['Ho','Hi','Hi','Ho','Hi','Ho','!','Hi'] #The positions I will sort by pos = [1, 2, 2, 1, ...
0
2016-10-14T20:55:50Z
40,052,216
<p>You can try something like that:</p> <pre><code>sent = ['Hi', 'Ho', '!'] pos = [1, 2, 2, 1, 1, 1, 3] recreate = [sent[i - 1] for i in pos] print(recreate) # ['Hi', 'Ho', 'Ho', 'Hi', 'Hi', 'Hi', '!'] </code></pre> <p>However it requires you to describe the table with 'signs' (<code>sent = ['Hi', 'Ho', '!']</code> h...
0
2016-10-14T21:24:04Z
[ "python" ]
How to sort a list based on another list with integers Python
40,051,845
<p>So, I'm generally new at programming, and I was just wondering if it was possible to sort a list based not on the positions of another list, but the actual integers itself?</p> <pre><code>#Here is my list to be sorted sent = ['Ho','Hi','Hi','Ho','Hi','Ho','!','Hi'] #The positions I will sort by pos = [1, 2, 2, 1, ...
0
2016-10-14T20:55:50Z
40,052,336
<p>I will make a few assumptions for my proposed solution.</p> <ul> <li><code>pos</code> has 7 elements but <code>sortlst</code> has 8. I assume this is a typo.</li> <li>You associate each <em>unique</em> element of <code>sent</code> with an integer based on its sorted value. Note, though, that you sort '!' as <em>aft...
0
2016-10-14T21:33:42Z
[ "python" ]
How to load angular2 files to Django template?
40,051,865
<p>I have app structure like this: </p> <pre><code>├── project | |── templates │ │ └── index.html │ ├── __init__.py │ ├── models.py │ ├── urls.py │ ├── serializers.py │ ├── views.py ├── static | ├── app | │ ├── app.co...
0
2016-10-14T20:57:38Z
40,053,141
<p>You have nested single quotes and your file name is <code>main.js</code> not <code>main</code>, you need also to remove the first <code>/</code>. Let me know if the following line of code solves your issue:</p> <pre><code>System.import("{% static 'app/main.js' %}") </code></pre>
1
2016-10-14T22:59:13Z
[ "python", "django", "angular2", "frontend" ]
Text classification in Python based on large dict of string:string
40,051,876
<p>I have a dataset that would be equivalent to a dict of 5 millions key-values, both strings.<br> Each key is unique but there are only a couple hundreds of different values. </p> <p>Keys are not natural words but technical references. The values are "families", grouping similar technical references. Similar is mean...
0
2016-10-14T20:58:30Z
40,061,332
<p>Make a training dataset, and train a classifier. Most classifiers work on the values of a set of features that you define yourself. (The kind of features depends on the classifier; in some cases they are numeric quantities, in other cases true/false, in others they can take several discrete values.) You provide the ...
1
2016-10-15T16:11:23Z
[ "python", "algorithm", "machine-learning" ]
Equivalent function of MatLab's "dateshift(...)" in Python?
40,051,890
<p>MatLab can take a date and move it to the end of the month, quarter, etc. using the <code>dateshift(...)</code> <a href="https://www.mathworks.com/help/matlab/ref/dateshift.html" rel="nofollow">function</a>.</p> <p>Is there an equivalent function in Python?</p>
0
2016-10-14T20:59:25Z
40,052,068
<p>I'm not sure if it counts as the same, but the <a href="https://docs.python.org/3/library/datetime.html" rel="nofollow"><code>datetime</code></a> module can make times available as a <a href="https://docs.python.org/3/library/datetime.html#datetime.date.timetuple" rel="nofollow"><code>timetuple</code></a>, with sepa...
0
2016-10-14T21:12:12Z
[ "python", "matlab", "date" ]
Equivalent function of MatLab's "dateshift(...)" in Python?
40,051,890
<p>MatLab can take a date and move it to the end of the month, quarter, etc. using the <code>dateshift(...)</code> <a href="https://www.mathworks.com/help/matlab/ref/dateshift.html" rel="nofollow">function</a>.</p> <p>Is there an equivalent function in Python?</p>
0
2016-10-14T20:59:25Z
40,052,069
<p>I think <code>calendar.monthrange</code> should do it for you, e.g.:</p> <pre><code>&gt;&gt;&gt; import datetime, calendar &gt;&gt;&gt; year = int(input("Enter year: ")) Enter year: 2012 &gt;&gt;&gt; month = int(input("Enter month: ")) Enter month: 3 &gt;&gt;&gt; endOfMonthDate = datetime.date(year, month, calendar...
0
2016-10-14T21:12:20Z
[ "python", "matlab", "date" ]
Converting File Data to Lists
40,051,902
<p>I have a file on sample employee data. The first line is the name, the second line is the salary, the third line is life insurance election (Y/N), the fourth line is health insurance election (PPOI, PPOF, None), and it repeats. A snippet of the file is below:</p> <pre><code>Joffrey Baratheon 190922 Y PPOI Gregor ...
0
2016-10-14T21:00:18Z
40,052,144
<p>Count the total lines, divide by four get number of people to add to the lists. </p> <pre><code>i = 0 while i &lt; num_of_people: for a in range(0, num_of_people+1): namelist.append(i) i += 1 salarylist.append(i) i +=1 ... </code></pre> <p>Be careful splitting the data l...
1
2016-10-14T21:18:23Z
[ "python", "list", "python-3.x" ]
Converting File Data to Lists
40,051,902
<p>I have a file on sample employee data. The first line is the name, the second line is the salary, the third line is life insurance election (Y/N), the fourth line is health insurance election (PPOI, PPOF, None), and it repeats. A snippet of the file is below:</p> <pre><code>Joffrey Baratheon 190922 Y PPOI Gregor ...
0
2016-10-14T21:00:18Z
40,052,173
<p>You could use 4 list comprehensions like so:</p> <pre><code>with open("file.txt",'r') as f: lines = f.readlines() name_list = [lines[i].rstrip() for i in range(0,len(lines),4)] salary_list = [lines[i].rstrip() for i in range(1,len(lines),4)] life_ins_list = [lines[i].rstrip() for i in range(2,len(lines),4)] he...
2
2016-10-14T21:20:18Z
[ "python", "list", "python-3.x" ]
Converting File Data to Lists
40,051,902
<p>I have a file on sample employee data. The first line is the name, the second line is the salary, the third line is life insurance election (Y/N), the fourth line is health insurance election (PPOI, PPOF, None), and it repeats. A snippet of the file is below:</p> <pre><code>Joffrey Baratheon 190922 Y PPOI Gregor ...
0
2016-10-14T21:00:18Z
40,052,292
<p>You can use <code>islice</code> from the <code>itertools</code> library. It will allow you to iterate over batches of 4 lines at a time.</p> <pre><code>from itertools import islice EmpData = [] headers = ['name', 'salary', 'life insurance', 'health insurance'] record = {} counter = 1 with open('data.txt', 'r') as i...
1
2016-10-14T21:30:00Z
[ "python", "list", "python-3.x" ]
a mistake I keep having with for loops and return statements
40,051,914
<p>I have been noticing a problem I am having whenever I try to make a function that takes changes a string or a list then returns it. </p> <p>I will give you an example of this happening with a code I just wrote:</p> <pre><code>def remove_exclamation(string): string.split(' ') for i in string: i.split() for ...
3
2016-10-14T21:01:06Z
40,052,060
<p>You write your code and formulate your question as if it was possible to modify strings in Python. <strong>It is not possible.</strong></p> <p>Strings are immutable. All functions which operate on strings return new strings. They do not modify existing strings.</p> <p>This returns a list of strings, but you are no...
4
2016-10-14T21:11:21Z
[ "python", "python-3.x", "for-loop", "return", "return-value" ]
a mistake I keep having with for loops and return statements
40,051,914
<p>I have been noticing a problem I am having whenever I try to make a function that takes changes a string or a list then returns it. </p> <p>I will give you an example of this happening with a code I just wrote:</p> <pre><code>def remove_exclamation(string): string.split(' ') for i in string: i.split() for ...
3
2016-10-14T21:01:06Z
40,052,155
<p>Without clearly knowing the intentions of your function and what you are attempting to do. I have an alternative to the answer that zvone gave.</p> <p>This option is to remove any characters that you have not defined in an allowed characters list:</p> <pre><code>characters = "0123456789abcdefghijklmnopqrstuvwxyzAB...
1
2016-10-14T21:18:54Z
[ "python", "python-3.x", "for-loop", "return", "return-value" ]
a mistake I keep having with for loops and return statements
40,051,914
<p>I have been noticing a problem I am having whenever I try to make a function that takes changes a string or a list then returns it. </p> <p>I will give you an example of this happening with a code I just wrote:</p> <pre><code>def remove_exclamation(string): string.split(' ') for i in string: i.split() for ...
3
2016-10-14T21:01:06Z
40,052,175
<p>Strings are immutable in Python. And you cannot change them. You can however, re-assign there values.</p> <p>That is where your problem lies. You never reassign the value of your strings, when you call <code>.split()</code> on them. </p> <p>But there are also others errors in your program such as:</p> <ul> <li>Yo...
0
2016-10-14T21:20:35Z
[ "python", "python-3.x", "for-loop", "return", "return-value" ]
a mistake I keep having with for loops and return statements
40,051,914
<p>I have been noticing a problem I am having whenever I try to make a function that takes changes a string or a list then returns it. </p> <p>I will give you an example of this happening with a code I just wrote:</p> <pre><code>def remove_exclamation(string): string.split(' ') for i in string: i.split() for ...
3
2016-10-14T21:01:06Z
40,052,375
<pre><code>def remove_exclamation(string): #you think you are splitting string into tokens #but you are not assigning the split anywhere... string.split(' ') #and here you are cycling through individual _chars_ in string which was not affected by the split above ;-) for i in string: #and n...
0
2016-10-14T21:37:22Z
[ "python", "python-3.x", "for-loop", "return", "return-value" ]
Pandas - identifying dataframe values that start with value in a list
40,051,958
<p>Say I have the following dataframe:</p> <pre><code>&gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; d=pd.DataFrame() &gt;&gt;&gt; d['A']=['12345','12354','76','4'] &gt;&gt;&gt; d['B']=['4442','2345','33','5'] &gt;&gt;&gt; d['C']=['5553','4343','33','5'] &gt;&gt;&gt; d A B C 0 12345 4442 5553 1 12354...
0
2016-10-14T21:04:07Z
40,052,050
<p>You can construct a regex pattern and test each column in turn using <code>apply</code> with a lambda calling <code>str.contains</code>:</p> <pre><code>In [9]: vals=['123','76'] v = ['^' + x for x in vals] d.apply(lambda x: x.str.contains('|'.join(v))) Out[9]: A B C 0 True False False 1 True...
1
2016-10-14T21:10:40Z
[ "python", "pandas" ]
Pandas - identifying dataframe values that start with value in a list
40,051,958
<p>Say I have the following dataframe:</p> <pre><code>&gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; d=pd.DataFrame() &gt;&gt;&gt; d['A']=['12345','12354','76','4'] &gt;&gt;&gt; d['B']=['4442','2345','33','5'] &gt;&gt;&gt; d['C']=['5553','4343','33','5'] &gt;&gt;&gt; d A B C 0 12345 4442 5553 1 12354...
0
2016-10-14T21:04:07Z
40,052,082
<p>You could do this:</p> <pre><code>d.applymap(lambda x: any([x.startswith(v) for v in vals])) </code></pre>
2
2016-10-14T21:13:46Z
[ "python", "pandas" ]
Pandas - identifying dataframe values that start with value in a list
40,051,958
<p>Say I have the following dataframe:</p> <pre><code>&gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; d=pd.DataFrame() &gt;&gt;&gt; d['A']=['12345','12354','76','4'] &gt;&gt;&gt; d['B']=['4442','2345','33','5'] &gt;&gt;&gt; d['C']=['5553','4343','33','5'] &gt;&gt;&gt; d A B C 0 12345 4442 5553 1 12354...
0
2016-10-14T21:04:07Z
40,052,102
<p>Alternative solution, which doesn't use <code>.apply()</code>:</p> <pre><code>In [66]: search_re = '^(?:{})'.format('|'.join(vals)) In [67]: search_re Out[67]: '^(?:123|76)' In [69]: df.astype(str).stack().str.match(search_re).unstack() Out[69]: A B C 0 True False False 1 True False False...
1
2016-10-14T21:15:05Z
[ "python", "pandas" ]
Pandas - identifying dataframe values that start with value in a list
40,051,958
<p>Say I have the following dataframe:</p> <pre><code>&gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; d=pd.DataFrame() &gt;&gt;&gt; d['A']=['12345','12354','76','4'] &gt;&gt;&gt; d['B']=['4442','2345','33','5'] &gt;&gt;&gt; d['C']=['5553','4343','33','5'] &gt;&gt;&gt; d A B C 0 12345 4442 5553 1 12354...
0
2016-10-14T21:04:07Z
40,052,271
<p>A bit complicated, but it seems the fastest solution. </p> <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.startswith.html" rel="nofollow"><code>str.startswith</code></a> which works only with Series, so use <code>list</code> comprehension and <a href="http://pandas.p...
0
2016-10-14T21:28:21Z
[ "python", "pandas" ]
Regex python findall issue
40,052,066
<p>From the test string:</p> <pre><code> test=text-AB123-12a test=text-AB123a </code></pre> <p>I have to extract only <code>'AB123-12'</code> and <code>'AB123'</code>, but:</p> <pre><code> re.findall("[A-Z]{0,9}\d{0,5}(?:-\d{0,2}a)?", test) </code></pre> <p>returns:</p> <pre><code>['', '', '', '', '', '', '', 'AB...
0
2016-10-14T21:11:53Z
40,052,150
<p>RegEx tester: <a href="http://www.regexpal.com/" rel="nofollow">http://www.regexpal.com/</a> says that your pattern string <code>[A-Z]{0,9}\d{0,5}(?:-\d{0,2}a)?</code> can match 0 characters, and therefore matches infinitely. </p> <p>Check your expression one more time. Python gives you undefined result.</p>
0
2016-10-14T21:18:47Z
[ "python", "regex" ]
Regex python findall issue
40,052,066
<p>From the test string:</p> <pre><code> test=text-AB123-12a test=text-AB123a </code></pre> <p>I have to extract only <code>'AB123-12'</code> and <code>'AB123'</code>, but:</p> <pre><code> re.findall("[A-Z]{0,9}\d{0,5}(?:-\d{0,2}a)?", test) </code></pre> <p>returns:</p> <pre><code>['', '', '', '', '', '', '', 'AB...
0
2016-10-14T21:11:53Z
40,052,151
<p>Since all parts of your pattern are optional (your ranges specify <em>zero</em> to N occurences and you are qualifying the group with <code>?</code>), each position in the string counts as a match and most of those are empty matches.</p> <p>How to prevent this from happening depends on the exact format of what you ...
0
2016-10-14T21:18:47Z
[ "python", "regex" ]
Regex python findall issue
40,052,066
<p>From the test string:</p> <pre><code> test=text-AB123-12a test=text-AB123a </code></pre> <p>I have to extract only <code>'AB123-12'</code> and <code>'AB123'</code>, but:</p> <pre><code> re.findall("[A-Z]{0,9}\d{0,5}(?:-\d{0,2}a)?", test) </code></pre> <p>returns:</p> <pre><code>['', '', '', '', '', '', '', 'AB...
0
2016-10-14T21:11:53Z
40,052,185
<p>The quantifier <code>{0,n}</code> will match anywhere from 0 to n occurrences of the preceding pattern. Since the two patterns you match allow 0 occurrences, and the third is optional (<code>?</code>) it will match 0-length strings, i.e. every character in your string.</p> <p>Editing to find a <em>minimum</em> of o...
3
2016-10-14T21:21:10Z
[ "python", "regex" ]
Regex python findall issue
40,052,066
<p>From the test string:</p> <pre><code> test=text-AB123-12a test=text-AB123a </code></pre> <p>I have to extract only <code>'AB123-12'</code> and <code>'AB123'</code>, but:</p> <pre><code> re.findall("[A-Z]{0,9}\d{0,5}(?:-\d{0,2}a)?", test) </code></pre> <p>returns:</p> <pre><code>['', '', '', '', '', '', '', 'AB...
0
2016-10-14T21:11:53Z
40,052,188
<p>Your pattern is set to match zero length characters with the lower limits of your <em>character set</em> quantifier set to 0. Simply setting to 1 will produce the results you want: </p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; test = ''' test=text-AB123-12a ... test=text-AB123a''' &gt;&gt;&gt; re.findall("...
1
2016-10-14T21:21:26Z
[ "python", "regex" ]
Regex python findall issue
40,052,066
<p>From the test string:</p> <pre><code> test=text-AB123-12a test=text-AB123a </code></pre> <p>I have to extract only <code>'AB123-12'</code> and <code>'AB123'</code>, but:</p> <pre><code> re.findall("[A-Z]{0,9}\d{0,5}(?:-\d{0,2}a)?", test) </code></pre> <p>returns:</p> <pre><code>['', '', '', '', '', '', '', 'AB...
0
2016-10-14T21:11:53Z
40,052,222
<p>Since letters or digits are optional at the beginning, you must ensure that there's at least one letter or one digit, otherwise your pattern will match the empty string at each position in the string. You can do it starting your pattern with a lookahead. Example:</p> <pre><code>re.findall(r'(?=[A-Z0-9])[A-Z]{0,9}\d...
0
2016-10-14T21:24:29Z
[ "python", "regex" ]
How to remove HTML tags in BeautifulSoup when I have contents
40,052,116
<p>The html for what I'm attempting to grab:</p> <p><code>&lt;div id="unitType"&gt; &lt;h2&gt;BB100 &lt;br&gt;v1.4.3&lt;/h2&gt; &lt;/div&gt;</code></p> <p>I have the contents of an <code>h2</code> tag below:</p> <pre><code>initialPage = beautifulSoup(urllib.urlopen(url).read(), 'html.parser') deviceInfo = init...
0
2016-10-14T21:16:21Z
40,052,289
<p>You can check if the element is a <code>&lt;br&gt;</code> tag with <code>if i.name == 'br'</code>, and then just change the list to have the contents instead.</p> <pre><code>for i in deviceInfo: if i.name == 'br': i = i.contents </code></pre> <p>If you need to iterate over it many times, modify the lis...
0
2016-10-14T21:29:46Z
[ "python", "python-2.7", "beautifulsoup" ]
How to remove HTML tags in BeautifulSoup when I have contents
40,052,116
<p>The html for what I'm attempting to grab:</p> <p><code>&lt;div id="unitType"&gt; &lt;h2&gt;BB100 &lt;br&gt;v1.4.3&lt;/h2&gt; &lt;/div&gt;</code></p> <p>I have the contents of an <code>h2</code> tag below:</p> <pre><code>initialPage = beautifulSoup(urllib.urlopen(url).read(), 'html.parser') deviceInfo = init...
0
2016-10-14T21:16:21Z
40,052,841
<p>Just use find and <em>extract</em> the <em>br</em> tag:</p> <pre><code>In [15]: from bs4 import BeautifulSoup ...: ...: h = """&lt;div id='unitType'&gt;&lt;h2&gt;BB10&lt;br&gt;v1.4.3&lt;/h2&gt;&lt;/d ...: iv&gt;""" ...: ...: soup = BeautifulSoup(h, "html.parser") ...: ...: h2 = soup.f...
2
2016-10-14T22:25:49Z
[ "python", "python-2.7", "beautifulsoup" ]
New York Times API and NYT python library
40,052,157
<p>I am trying to retrieve the parameter <code>web_url</code> on Python via the <code>newyorktimes</code> library. However, the query result on python is way smaller than the result from the NYT API. </p> <p>This is my code:</p> <pre><code>from nytimesarticle import articleAPI api = articleAPI("*Your Key*") articles...
0
2016-10-14T21:18:58Z
40,052,297
<p>You are missing pagination, try this:</p> <pre><code>articles = api.search( q = 'terrorist attack', page=1) </code></pre> <p>now you can keep incrementing <code>page</code> and get more articles. Its politely called RTFM <a href="https://pypi.python.org/pypi/nytimesarticle/0.1.0" rel="nofollow">nytimesarticle</a>....
0
2016-10-14T21:30:26Z
[ "python" ]
Check if variable is a standard type function in Python
40,052,224
<p>I'm looking for a way to catch all the std type functions in Python (int, str, xrange, etc).</p> <p>Basically anything which has a repr that looks like <code>&lt;type X&gt;</code> instead of <code>&lt;class X&gt;</code>. Here's a full list of all std types in Python 2: <a href="https://docs.python.org/2/library/std...
0
2016-10-14T21:24:36Z
40,052,731
<p>What you suggested seems good to me.</p> <pre><code>builtin = dir(__builtins__) def is_builtin(tested_object): return tested_object.__class__.__name__ in builtin </code></pre> <p>Bear in mind, however, that built-in types can be overshadowed.</p> <p>Update after comment from Rob:</p> <pre><code>def is_builti...
0
2016-10-14T22:13:53Z
[ "python" ]
Python matching lines of a file with a list of strings
40,052,241
<p>High-level requirement is that I need an equivalent of "grep -f match_str_file search_file".</p> <p>I have a list of strings which I need to find in a given text file. The string may occur anywhere in any line of file.</p> <p>What would be an efficient way to achieve this?</p> <pre><code>matchstr = ['string1', '...
-2
2016-10-14T21:25:43Z
40,052,308
<p>Try this:</p> <pre><code>matchstr = ['string1', 'string2', 'string3', ... 'string1000'] matches = [] def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 while 1: lines = file.readlines(file_len("fjiop.txt")) if not lines: break f...
0
2016-10-14T21:31:04Z
[ "python", "python-3.x", "string-matching" ]
How to import data from a file and append it to a Python list?
40,052,249
<p>This is what I've tried.</p> <pre><code>foo = {} foo['bar'] = [{'a': '1', 'b': '2'}, {'c':'3', 'd':'4'} ] import othervalues </code></pre> <p>This is the content of othervalues.py</p> <pre><code>foo['bar'].append({'e': '5', 'f': '6'}) </code></pre> <p>However when I try to run this, it fails saying that foo isn'...
-1
2016-10-14T21:26:23Z
40,052,341
<p>In othervalues you could have:</p> <pre><code>def fooadd(foo): foo['bar'].append({'e': '5', 'f': '6'}) </code></pre> <p>And then, in your normal code:</p> <pre><code>import othervalues othervalues.fooadd(foo) </code></pre>
0
2016-10-14T21:34:16Z
[ "python", "list", "import" ]
Is it possible to do lemmatization independently in spacy?
40,052,283
<p>I'm using spacy to preprocess the data for sentiment analysis.</p> <p>What I want to do is:</p> <p>1) Lemmatization<br> 2) POS tagging on lemmatized words</p> <p>But since spacy does all the process at once when the parser is called it's doing all the calculations twice. Is there an option to disable non-required...
1
2016-10-14T21:29:19Z
40,052,477
<p>Have a look at the Language.<strong>call</strong> method to see how the various processes are being applied in sequence. There aren't many -- it's basically:</p> <pre><code>doc = nlp.tokenizer(text) nlp.tagger(doc) nlp.parser(doc) nlp.entity(doc) </code></pre> <p>If you need a different sequence, you should just w...
2
2016-10-14T21:46:53Z
[ "python", "machine-learning", "nlp", "spacy" ]
Pandas Series any() vs all()
40,052,285
<pre><code>&gt;&gt;&gt; s = pd.Series([float('nan')]) &gt;&gt;&gt; s.any() False &gt;&gt;&gt; s.all() True </code></pre> <p>Isn't that weird? Documentation on <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.any.html" rel="nofollow">any</a> (Return whether any element is True over requested...
1
2016-10-14T21:29:27Z
40,052,398
<p>It seems to be an issue with how <code>pandas</code> normally ignores <code>NaN</code> unless told not to:</p> <pre><code>&gt;&gt;&gt; pd.Series([float('nan')]).any() False &gt;&gt;&gt; pd.Series([float('nan')]).all() True &gt;&gt;&gt; pd.Series([float('nan')]).any(skipna=False) True &gt;&gt;&gt; </code></pre> <p...
2
2016-10-14T21:39:56Z
[ "python", "pandas", "series" ]
Loop for pandas columns
40,052,290
<p>I want to apply kruskal test for several columns. I do as bellow</p> <pre><code>import pandas as pd import scipy df = pd.DataFrame({'a':range(9), 'b':[1,2,3,1,2,3,1,2,3], 'group':['a', 'b', 'c']*3}) </code></pre> <p>and then the Loop</p> <pre><code>groups = {} res = [] for grp in df['group'].unique(): for co...
0
2016-10-14T21:29:54Z
40,053,205
<p>Your for loops are upside down: the one-column algorithm is your loop invariant with regards to the column you chose. So the column for loop must be the outer loop. In plain English "for each column apply the kruskal algorithm which consists of this group.unique for loop:</p> <pre><code>groups = {} res = [] for col...
1
2016-10-14T23:05:41Z
[ "python", "loops", "pandas" ]
Loop for pandas columns
40,052,290
<p>I want to apply kruskal test for several columns. I do as bellow</p> <pre><code>import pandas as pd import scipy df = pd.DataFrame({'a':range(9), 'b':[1,2,3,1,2,3,1,2,3], 'group':['a', 'b', 'c']*3}) </code></pre> <p>and then the Loop</p> <pre><code>groups = {} res = [] for grp in df['group'].unique(): for co...
0
2016-10-14T21:29:54Z
40,053,288
<p>before i made like this</p> <pre><code>groups = {} res = [] for column in df[[0, 1]]: for grp in df['group'].unique(): groups[grp] = df[column][df['group']==grp].values args = groups.values() g = scipy.stats.kruskal(*args) res.append(g) print (res) </code></pre> <p>and i get </p> <pre><code>[Krusk...
0
2016-10-14T23:16:40Z
[ "python", "loops", "pandas" ]
Computing 3↑↑↑3 (In Python)
40,052,328
<p>I'm giving a presentation on <a href="https://en.wikipedia.org/wiki/Graham%27s_number" rel="nofollow">Graham's Number</a> and I wanted to compute the first few ↑s (i.e. 3↑3, 3↑↑3, and 3↑↑↑3) to give them an idea of how huge it gets in such a short time. I wrote some naive/direct code in python, based o...
3
2016-10-14T21:33:12Z
40,052,448
<p>From <a href="https://en.wikipedia.org/wiki/Knuth%27s_up-arrow_notation" rel="nofollow">Wikipedia</a>:<a href="https://i.stack.imgur.com/U0xV7.png" rel="nofollow"><img src="https://i.stack.imgur.com/U0xV7.png" alt="enter image description here"></a></p> <p>Suppose you want to store this number (call it <code>N</cod...
4
2016-10-14T21:44:01Z
[ "python", "memory", "bigdata" ]
Computing 3↑↑↑3 (In Python)
40,052,328
<p>I'm giving a presentation on <a href="https://en.wikipedia.org/wiki/Graham%27s_number" rel="nofollow">Graham's Number</a> and I wanted to compute the first few ↑s (i.e. 3↑3, 3↑↑3, and 3↑↑↑3) to give them an idea of how huge it gets in such a short time. I wrote some naive/direct code in python, based o...
3
2016-10-14T21:33:12Z
40,066,202
<p>Expanding on my comment, I just want to flesh out a bit just <em>how</em> hopeless it is to grasp numbers of this size.</p> <p>I assume you already know that</p> <pre><code>3 ↑↑↑ 3 = 3 ↑↑ (3 ↑↑↑ 2) = 3 ↑↑ (3 ↑↑ 3) = 3 ↑↑ (3 ↑ 3 ↑ 3) = 3 ↑↑ (3 ↑ 27) = 3 ↑↑ 7625597484987 </c...
2
2016-10-16T02:24:40Z
[ "python", "memory", "bigdata" ]
HackerRank Python - some test cases get "Terminated due to timeout", how can i optimize the code?
40,052,339
<p>Currently, on HackerRank, I am trying to solve the <a href="https://www.hackerrank.com/challenges/circular-array-rotation?h_r=next-challenge&amp;h_v=zen" rel="nofollow">Circular Array Rotation</a> problem. Most of the test cases work, but some are "Terminated due to timeout".</p> <p>How can I change my code to opti...
-1
2016-10-14T21:34:04Z
40,052,478
<p>There's no need to transform the list at all. Just subtract <code>k</code> from the index you're passed whenever you do a lookup (perhaps with a modulus if <code>k</code> could be larger than <code>n</code>). This is <code>O(1)</code> per lookup, or <code>O(q)</code> overall.</p> <p>Even if you wanted to transform ...
1
2016-10-14T21:46:54Z
[ "python", "python-3.x" ]
Iterate QPushButton
40,052,348
<p>I am using PyQt4. I have a QPushButton and now I want to Iterate it. On button click, it should load data from csv file into QTableWidget. But I want only one case to display at a time. </p> <p>For example csv has 1000 rows excluding headers. Now it should assign header to table widget from header. and display only...
2
2016-10-14T21:34:29Z
40,071,781
<p>The main problem was, when ever the button was clicked, the iterator is getting set to 0 or 1 what ever it was assigned. So, assign the variable outside of the class and call it into the class to maintain the loop structure.</p> <pre><code>class staticVariable: static_count_clicked = 1 class Mainwindow(QtGui.Q...
0
2016-10-16T15:07:03Z
[ "python", "pyqt", "pyqt4", "qpushbutton", "import-csv" ]
PyCharm is not doing code inspection on non-project files
40,052,432
<p>I'm working on a Python project in PyCharm and I wanted to edit a python script outside the project. PyCharm doesn't inspect the code and doesn't give any PEP8 violations. Hoped that there would be a setting for that but couldn't find anything so far.</p> <p>Does anyone know how to enable code inspection on non-pr...
0
2016-10-14T21:42:23Z
40,062,538
<p>I am able to reproduce the problem (with 5.0.5 Pro Linux version).</p> <p>The inspection is actually active and the PEP8 checks are all enabled, I even got a <code>blank line at end of file</code> flag raised, but not an <code>unresolved reference</code> one:</p> <p><a href="https://i.stack.imgur.com/Zo05U.png" re...
0
2016-10-15T18:11:32Z
[ "python", "pycharm", "inspection" ]
Writing a while loop for error function erf(x)?
40,052,433
<p>I understand there is a <a href="https://docs.python.org/3/library/math.html#math.erf" rel="nofollow">erf</a> (<a href="https://en.wikipedia.org/wiki/Error_function" rel="nofollow">Wikipedia</a>) function in python. But in this assignment we are specifically asked to write the error function as if it was not already...
0
2016-10-14T21:42:25Z
40,052,946
<p>First of all - SO is not the place when people code for you, here people help you to solve particular problem not the whole task </p> <p>Any way: It's not too hard to implement wikipedia algorithm: </p> <pre><code>import math def erf(x): n = 1 res = 0 res1 = (2 / math.sqrt(math.pi)) * x diff = 1 ...
0
2016-10-14T22:37:29Z
[ "python", "while-loop" ]
Cannot import Decimal module
40,052,442
<p>I am trying to do some simple decimal math to practice with the Tkinter GUI, but for some reason I cannot import Decimal:</p> <pre><code>&gt;&gt;&gt; from decimal import Decimal Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/Library/Frameworks/Python.framework/Versions...
-1
2016-10-14T21:43:18Z
40,052,821
<p>You called a file <code>math.py</code>, meaning it overrides the built-in <code>math</code> module and breaks everything that uses that module. Pick a different name, and the problem will go away.</p>
3
2016-10-14T22:23:19Z
[ "python", "python-2.7", "import", "decimal" ]
Get Python 3 from bash file using similar syntax for Python 3
40,052,616
<p>I am writing an install script and is trying to get a variable linking to Python 3 instead of Python 2. In bash you can do:</p> <pre><code>:~$ export PYTHON="${PYTHON:-python}" :~$ echo $PYTHON /usr/bin/python2 </code></pre> <p>How would you call similar syntax for Python 3 instead? I have tried</p> <pre><code>:~...
0
2016-10-14T22:01:32Z
40,052,704
<p>Your original, Python 2 code doesn't do what you think it's doing:</p> <pre><code>:~$ export PYTHON="${PYTHON:-python}" :~$ echo $PYTHON /usr/bin/python2 </code></pre> <p>This is because <code>${foo:-bar}</code> expands the variable named <code>foo</code>, or -- if that variable is either unset or set to an empty ...
2
2016-10-14T22:11:10Z
[ "python", "bash", "python-3.x" ]
Is there a way to find the source of an error in Python with no file name?
40,052,641
<p>I've been getting several mystery errors after my program completes and exits successfully. There were 3, but I fixed the "Nonetype" error by making a second import of an Agilent library local instead of global, I assume it was freeing the same object twice. But I still get these two:</p> <pre><code>Exception ctype...
1
2016-10-14T22:03:36Z
40,052,798
<p>You can start your script with a <a href="https://wiki.python.org/moin/PythonDebuggingTools" rel="nofollow">python debugger</a> or use a tool like GDB or strace to run your python program.</p> <p>The python debuggers may fail to dig into imported compiled libraries, but with the other two you can get a stack trace ...
2
2016-10-14T22:20:11Z
[ "python", "selenium", "visa" ]
Python Flask: RQ Worker raising KeyError because of environment variable
40,052,740
<p>I'm trying to setup a redis queue and a worker to process the queue with my flask app. I'm implementing this to handle a task that sends emails. I'm a little confused because it appears that the stack trace is saying that my 'APP_SETTINGS' environment variable is not set when it is in fact set.</p> <p>Prior to star...
-1
2016-10-14T22:14:40Z
40,052,947
<p>Thanks to the prompting of @danidee, I discovered that the environment variables need to be defined in each terminal. Hence, APP_SETTINGS was defined for the actual app, but not for the worker.</p> <p>The solution was to set APP_SETTINGS in the worker terminal. </p>
0
2016-10-14T22:37:30Z
[ "python", "python-2.7", "flask", "python-rq" ]
Django 1.9 get kwargs in class based view
40,052,924
<p>I was wondering if there is a way to get the kwargs directly in a class based view. I know this can be done in functions inside the class, but I'm having problems when I try this:</p> <p><strong>views.py</strong></p> <pre><code>class EmployeesUpdateStudies(UpdateView): form_class = form_ES model = Employee...
-1
2016-10-14T22:35:54Z
40,052,975
<p>You can't use <code>kwargs</code> in <code>success_url</code>, because when Django loads the class when the server starts, it doesn't have access to the request. Override the <code>get_success_url</code> method instead. </p> <pre><code>def get_success_url(self) return reverse('employee-details', kwargs={'pk':...
1
2016-10-14T22:40:13Z
[ "python", "django", "django-views", "django-urls" ]
Django 1.9 get kwargs in class based view
40,052,924
<p>I was wondering if there is a way to get the kwargs directly in a class based view. I know this can be done in functions inside the class, but I'm having problems when I try this:</p> <p><strong>views.py</strong></p> <pre><code>class EmployeesUpdateStudies(UpdateView): form_class = form_ES model = Employee...
-1
2016-10-14T22:35:54Z
40,053,017
<p>Alasdair's answer solves your problem. You can however define a <code>get_absolute_url</code> method for your <code>EmployeePersonal</code> model which will act as the <code>success_url</code> for your view: </p> <blockquote> <p>You don’t even need to provide a <code>success_url</code> for <code>CreateView</co...
2
2016-10-14T22:45:09Z
[ "python", "django", "django-views", "django-urls" ]
How to make a nested for loop using a generator in python?
40,052,968
<p>I'm trying to convert this nested for loop:</p> <pre><code> for k,v in all_R.iteritems(): for pairs in v: print pairs[1] </code></pre> <p>to a one liner, something like this:</p> <pre><code>print ([pairs[1] for pairs in v for k,v in all_R.iteritems()]) </code></pre> <p>But I'm ...
0
2016-10-14T22:39:18Z
40,053,020
<p>List comprehensions are written in the same order as for loops, so you are actually looking for (Note the order is reversed) <code>print ([pairs[1] for k,v in all_R.iteritems() for pairs in v ])</code></p> <p>If you are looking to use generators as your title suggests, you can use parenthesis instead of brackets <c...
2
2016-10-14T22:45:19Z
[ "python", "syntax", "nested", "generator", "bioinformatics" ]
How to execute a multi-threaded `merge()` with dask? How to use multiples cores via qsub?
40,052,981
<p>I've just begun using dask, and I'm still fundamentally confused how to do simple pandas tasks with multiple threads, or using a cluster. </p> <p>Let's take <code>pandas.merge()</code> with <code>dask</code> dataframes. </p> <pre><code>import dask.dataframe as dd df1 = dd.read_csv("file1.csv") df2 = dd.read_csv("...
3
2016-10-14T22:40:57Z
40,054,183
<h3>Single machine scheduling</h3> <p>Dask.dataframe will use the threaded scheduler by default with as many threads as you have logical cores in your machine. </p> <p>As pointed out in the comments, you can control the number of threads or the Pool implementation with keyword arguments to the <code>.compute()</code...
2
2016-10-15T01:55:35Z
[ "python", "multithreading", "pandas", "cluster-computing", "dask" ]
Append new items in database only
40,053,010
<p>I have a table called <code>classes</code> Which has fields:</p> <p><code>course name</code><br> <code>times_mentioned</code></p> <p>So what I'm trying to do is. Set <code>course_name</code> and <code>times_Mentioned</code> to null at first. But when a user for instance in my website chooses a class, I just want ...
1
2016-10-14T22:44:11Z
40,053,441
<p>1- change type of <code>times_mentioned</code> to <code>integer</code></p> <p>2- use <code>count</code> func to check if instance exist if so increase counter else create a new one</p> <pre><code>def AddCourseName(coursename): if db.session.query(popular_courses.id).filter(popular_courses.nam‌​e==coursenam...
0
2016-10-14T23:37:07Z
[ "python", "database", "syntax", "sqlalchemy" ]
python: how can I pass a variable to a function with only the string name
40,053,099
<blockquote> <p>I'm interacting with a relatively complex program and putting a GUI on it to issue commands. I made up a simple example which I think demonstrates the problem. I know what parameters need to be passed to issue a command but I will only be able to get them as strings.</p> </blockquote> <p>There are hu...
0
2016-10-14T22:53:48Z
40,053,183
<p>If my comment to your question is what you are after then perhaps using a dictionary as key-word arguments would work for you.</p> <pre><code>&gt;&gt;&gt; def issueTheCommand(mode, seconds): ... print mode, seconds ... &gt;&gt;&gt; issueTheCommand(**{"mode": "16bits", "seconds": "8bits"}) 16bits 8bits </code></...
0
2016-10-14T23:02:58Z
[ "python", "string", "variables", "parameters" ]
python: how can I pass a variable to a function with only the string name
40,053,099
<blockquote> <p>I'm interacting with a relatively complex program and putting a GUI on it to issue commands. I made up a simple example which I think demonstrates the problem. I know what parameters need to be passed to issue a command but I will only be able to get them as strings.</p> </blockquote> <p>There are hu...
0
2016-10-14T22:53:48Z
40,054,794
<p>Arguments specified as keywords can be picked up as a dict. Conversely, keyword arguments can be provided as a dict. Look:</p> <pre><code>&gt;&gt;&gt; def a(**b): # Pick up keyword args in a dict named b. ... print(b) ... &gt;&gt;&gt; a(x=1, y=2) {'y': 2, 'x': 1} &gt;&gt;&gt; c = {'y': 2, 'x': 1} &gt;&gt;&gt...
0
2016-10-15T04:00:12Z
[ "python", "string", "variables", "parameters" ]