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
sequence
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:4958392 1 NaN </code></pre> <p>I am trying to loop through each row and print text to output for another program. I need to print the first three columns (with some other text), then go through the rest of the columns and print something different depending on if they are NaN or not.</p> <p>This works mostly:</p> <p><strong>Current code</strong></p> <pre><code>def CreateIGVBatchScript(x): for row in x.iterrows(): print("\nnew") sample = x[0] bamt = x[1] bamn = x[2] print("\nload", bamt.to_string(index=False), "\nload", bamn.to_string(index=False)) for col in range(3, len(x.columns)): position = x[col] if position.isnull().values.any(): print("\n") else: position = position.to_string(index=False) print("\ngoto ", position, "\ncollapse\nsnapshot ", sample.to_string(index=False), "_", position,".png\n") CreateIGVBatchScript(data) </code></pre> <p>but the output looks like this:</p> <p><strong>Actual Output</strong></p> <pre><code>new load path/to/bam_T.bam path/to/bam_T2.bam load path/to/bam_N.bam path/to/bam_N2.bam goto chr1:10000 chr54:4958392 collapse snapshot UICEX_0001 **&lt;-- ISSUE: it's printing both rows at the same time** UICEX_0002 _ chr1:10000 chr54:4958392 .png new load path/to/bam_T.bam path/to/bam_T2.bam load path/to/bam_N.bam path/to/bam_N2.bam goto chr1:10000 chr54:4958392 collapse snapshot UICEX_0001 **&lt;-- ISSUE: it's printing both rows at the same time** UICEX_0002 _ chr1:10000 chr54:4958392 .png </code></pre> <p>The first part seems fine, but when I start to iterate over the columns, all rows are printed. I can't seem to figure out how to fix this. Here's what I want one of those parts to look like:</p> <p><strong>Partial Wanted Output</strong></p> <pre><code>goto chr1:10000 collapse snapshot UICEX_0001_chr1:10000.png goto chr54:4958392 collapse snapshot UICEX_0001_chr54:495832.png </code></pre> <p><strong>Extra information</strong> Incidentally, I'm actually trying to adapt this from an R script in order to better learn Python. Here's the R code, in case that helps:</p> <pre><code>CreateIGVBatchScript &lt;- function(x){ for(i in 1:nrow(x)){ cat("\nnew") sample = as.character(x[i, 1]) bamt = as.character(x[i, 2]) bamn = as.character(x[i, 3]) cat("\nload",bamt,"\nload",bamn) for(j in 4:ncol(x)){ if(x[i, j] == "" | is.na(x[i, j])){ cat("\n") } else{ cat("\ngoto ", as.character(x[i, j]),"\ncollapse\nsnapshot ", sample, "_", x[i,j],".png\n", sep = "") } } } cat("\nexit") } CreateIGVBatchScript(data) </code></pre>
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(): sample = row[0] </code></pre> <p>will save the value in that row in column 0.</p> <ol start="2"> <li>Iterate over the columns</li> </ol> <p>At this point, you can use a simple for loop, as I was doing to iterate over the columns.</p> <pre><code>for col in range(3, len(data.columns)): position = row[col] </code></pre> <p>lets you save a value from that column.</p> <p>The final Python code is:</p> <pre><code>def CreateIGVBatchScript(x): x=x.fillna(value=999) for index, row in x.iterrows(): print("\nnew", sep="") sample = row[0] bamt = row[1] bamn = row[2] print("\nload ", bamt, "\nload ", bamn, sep="") for col in range(3, len(data.columns)): position = row[col] if position == 999: print("\n") else: print("\ngoto ", position, "\ncollapse\nsnapshot ", sample, "_", position, ".png\n", sep="") CreateIGVBatchScript(data) </code></pre> <p>Answers were guided by the following posts:</p> <ul> <li><a href="http://stackoverflow.com/questions/28218698/how-to-iterate-over-columns-of-pandas-dataframe-to-run-regression">How to iterate over columns of pandas dataframe to run regression</a></li> <li><a href="http://stackoverflow.com/questions/16476924/how-to-iterate-over-rows-in-a-dataframe">How to iterate over rows in a DataFrame?</a></li> <li><a href="http://stackoverflow.com/questions/29700552/series-objects-are-mutable-and-cannot-be-hashed-error">“Series objects are mutable and cannot be hashed” error</a></li> <li><a href="http://stackoverflow.com/questions/255147/how-do-i-keep-python-print-from-adding-newlines-or-spaces">How do I keep Python print from adding newlines or spaces?</a></li> </ul>
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> </blockquote> <p>I tried <code>pip install urllib</code> but still had the same error. I am using Python 2.7.11. Really appreciate any help</p>
-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" rel="nofollow"><code>urllib.request</code></a> module, but Python 2.x does not, as far as I know.</li> <li><p>The functionality that you are looking for from <code>urllib.request</code> is most likely contained in <a href="https://docs.python.org/2/library/urllib2.html#module-urllib2" rel="nofollow"><code>urllib2</code></a> (which is also part of the standard library), but you might be even better off using <a href="http://docs.python-requests.org/en/master/" rel="nofollow"><code>requests</code></a>, which probably does need to be installed through <code>pip</code> in your case:</p> <pre><code>pip install requests </code></pre> <p>In fact, the <code>urllib2</code> documentation itself recommends that you use the <code>requests</code> library "for a higher-level HTTP client interface" - but I am not sure what you wish to do, so it is hard to say what would be best for your particular use case. </p></li> </ol>
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 functions as F import pandas as pd import numpy as np # create a Pandas DataFrame, then convert to Spark DataFrame test = sqlContext.createDataFrame(pd.DataFrame({'val1': np.arange(1,11)})) </code></pre> <p>Which leaves me with </p> <pre><code>+----+ |val1| +----+ | 1| | 2| | 3| | 4| | 5| | 6| | 7| | 8| | 9| | 10| +----+ </code></pre> <p>I loop a lot in the code, for example the below:</p> <pre><code>for i in np.arange(2,6).tolist(): test = test.withColumn('val_' + str(i), F.lit(i ** 2) + test.val1) </code></pre> <p>Which results in: </p> <pre><code>+----+-----+-----+-----+-----+ |val1|val_2|val_3|val_4|val_5| +----+-----+-----+-----+-----+ | 1| 5| 10| 17| 26| | 2| 6| 11| 18| 27| | 3| 7| 12| 19| 28| | 4| 8| 13| 20| 29| | 5| 9| 14| 21| 30| | 6| 10| 15| 22| 31| | 7| 11| 16| 23| 32| | 8| 12| 17| 24| 33| | 9| 13| 18| 25| 34| | 10| 14| 19| 26| 35| +----+-----+-----+-----+-----+ </code></pre> <p>**Question: ** How can I rewrite the above loop to be more efficient?</p> <p>I've noticed that my code runs slower as Spark spends a lot of time on each group of loops (even on small datasets like 2GB of text input).</p> <p>Thanks</p>
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 parallel. </p> <p>a. you can gather new values based on the calculations</p> <p>b. Add these new column values to main rdd as below</p> <pre><code>val newColumns: Seq[Any] = Seq(newcol1,newcol2) Row.fromSeq(row.toSeq.init ++ newColumns) </code></pre> <p>Here row, is the reference of row in map method</p> <p>c. Create new schema as below</p> <pre><code>val newColumnsStructType = StructType{Seq(new StructField("newcolName1",IntegerType),new StructField("newColName2", IntegerType)) </code></pre> <p>d. Add to the old schema</p> <pre><code>val newSchema = StructType(mainDataFrame.schema.init ++ newColumnsStructType) </code></pre> <p>e. Create new dataframe with new columns</p> <pre><code>val newDataFrame = sqlContext.createDataFrame(newRDD, newSchema) </code></pre>
-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 functions as F import pandas as pd import numpy as np # create a Pandas DataFrame, then convert to Spark DataFrame test = sqlContext.createDataFrame(pd.DataFrame({'val1': np.arange(1,11)})) </code></pre> <p>Which leaves me with </p> <pre><code>+----+ |val1| +----+ | 1| | 2| | 3| | 4| | 5| | 6| | 7| | 8| | 9| | 10| +----+ </code></pre> <p>I loop a lot in the code, for example the below:</p> <pre><code>for i in np.arange(2,6).tolist(): test = test.withColumn('val_' + str(i), F.lit(i ** 2) + test.val1) </code></pre> <p>Which results in: </p> <pre><code>+----+-----+-----+-----+-----+ |val1|val_2|val_3|val_4|val_5| +----+-----+-----+-----+-----+ | 1| 5| 10| 17| 26| | 2| 6| 11| 18| 27| | 3| 7| 12| 19| 28| | 4| 8| 13| 20| 29| | 5| 9| 14| 21| 30| | 6| 10| 15| 22| 31| | 7| 11| 16| 23| 32| | 8| 12| 17| 24| 33| | 9| 13| 18| 25| 34| | 10| 14| 19| 26| 35| +----+-----+-----+-----+-----+ </code></pre> <p>**Question: ** How can I rewrite the above loop to be more efficient?</p> <p>I've noticed that my code runs slower as Spark spends a lot of time on each group of loops (even on small datasets like 2GB of text input).</p> <p>Thanks</p>
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)) spark.range(1, 11).toDF("val1").select("*", *(make_col(i) for i in range(2, 6))) </code></pre> <p>I would also avoid using NumPy types. Initializing NumPy objects is typically more expensive compared to plain Python objects and Spark SQL doesn't support NumPy types so there some additional conversions required.</p>
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 = zero_matrix(n) for i in range(n): for j in range(n): for k in range(n): c[i][j] += a[i][k] * b[k][j] return c def baseline_matrix_multiply_flipjk(a, b, n): ''' same as baseline but switch j and k loops ''' c = zero_matrix(n) for i in range(n): for k in range(n): for j in range(n): c[i][j] += a[i][k] * b[k][j] return c def fast_matrix_multiply_blocking(a, b, n): ''' use blocking ''' c = zero_matrix(n) block = 25; en = int(block * n/block) for kk in range(0, en, block): for jj in range(0, en, block): for i in range(n): for j in range(jj, jj + block): sum = c[i][j] for k in range(kk, kk + block): sum += a[i][k] * b[k][j] c[i][j] = sum return c </code></pre> <p>My timings are as follows:</p> <pre><code>Baseline: 3.440004294627216 Flip j and k: 3.4685347505603144 100.83% of baseline Blocking: 2.729924394035205 79.36% of baseline </code></pre> <p>Some things to note:</p> <ol> <li><p>I am familiar with CPU caching behavior. To see my experiment in C see <a href="http://codereview.stackexchange.com/questions/143061/cache-conscious-simd-matrix-multiply-of-unsigned-integers">here</a> though I havent gotten any reviews for it.</p></li> <li><p>I've done this in Javascript and C# and the flip-j-k function provides significant performance gains using arrays (JS run on chrome browser)</p></li> <li><p>Python implementation is Python 3.5 by way of Anaconda</p></li> <li><p>Please dont tell me about numpy. My experiment is not about absolute performance but rather understanding caching behavior.</p></li> </ol> <p><strong>Question</strong>: Anyone know what is going on here? Why does flip-j-k not provide speedup? Is it because it's a linked list? But then why does blocking provide a non-marginal improvement in performance?</p>
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, comment and I'll sort it out:</p> <pre><code>from functools import lru_cache from random import randint as rand from time import clock as clk recur = 0 #@lru_cache(maxsize=4, typed=False) def Func(m, n): global recur recur += 1 if m == 0: return n + 1 elif n == 0: return Func(m - 1, 1) else: return Func(m - 1, Func(m, n - 1)) n = [] m = 0 ITER = 50 F1 = 3 F2 = 4 staTime = clk() for x in range (ITER): n.append(Func(F1, F2)) m += clk()-staTime print("Uncached calls of Func:: "+str(recur//ITER)) print("Average time per solving of Ackerman's function:: "+str(m/ITER)) print("End result:: "+str(n[0])) </code></pre> <p>BTW: "#" indicates a comment, in case you're unfamiliar with Python.</p> <p>So try running this and try AGAIN without the "#" on the line <code>#@lru_cache(maxsize=4, typed=False)</code> </p> <p>Additionally, maxsize is the maximum size of the cache (works best in powers of two according to the docs) and typed just makes the cache add a new cached condition whenever a different type of the same value is passed as an argument.</p> <p>Finally, the "Func" function is known as Ackermann's function. A stupidly deep amount of recursion goes on so be aware of stackoverflows (lol) if you should change the max recursion depth.</p>
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 = zero_matrix(n) for i in range(n): for j in range(n): for k in range(n): c[i][j] += a[i][k] * b[k][j] return c def baseline_matrix_multiply_flipjk(a, b, n): ''' same as baseline but switch j and k loops ''' c = zero_matrix(n) for i in range(n): for k in range(n): for j in range(n): c[i][j] += a[i][k] * b[k][j] return c def fast_matrix_multiply_blocking(a, b, n): ''' use blocking ''' c = zero_matrix(n) block = 25; en = int(block * n/block) for kk in range(0, en, block): for jj in range(0, en, block): for i in range(n): for j in range(jj, jj + block): sum = c[i][j] for k in range(kk, kk + block): sum += a[i][k] * b[k][j] c[i][j] = sum return c </code></pre> <p>My timings are as follows:</p> <pre><code>Baseline: 3.440004294627216 Flip j and k: 3.4685347505603144 100.83% of baseline Blocking: 2.729924394035205 79.36% of baseline </code></pre> <p>Some things to note:</p> <ol> <li><p>I am familiar with CPU caching behavior. To see my experiment in C see <a href="http://codereview.stackexchange.com/questions/143061/cache-conscious-simd-matrix-multiply-of-unsigned-integers">here</a> though I havent gotten any reviews for it.</p></li> <li><p>I've done this in Javascript and C# and the flip-j-k function provides significant performance gains using arrays (JS run on chrome browser)</p></li> <li><p>Python implementation is Python 3.5 by way of Anaconda</p></li> <li><p>Please dont tell me about numpy. My experiment is not about absolute performance but rather understanding caching behavior.</p></li> </ol> <p><strong>Question</strong>: Anyone know what is going on here? Why does flip-j-k not provide speedup? Is it because it's a linked list? But then why does blocking provide a non-marginal improvement in performance?</p>
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 this is the fastest standard random access container available in python)</p> <p>I just made some test program based on your code to prove my point and what I was suspecting (I had to complete your code, sorry for the big block but at least it is minimal complete &amp; verifiable for all).</p> <pre><code>def zero_matrix(sz): return [[0]*sz for i in range(sz)] def baseline_matrix_multiply(a, b, n): ''' baseline multiply ''' c = zero_matrix(n) for i in range(n): for j in range(n): for k in range(n): c[i][j] += a[i][k] * b[k][j] return c def baseline_matrix_multiply_flipjk(a, b, n): ''' same as baseline but switch j and k loops ''' c = zero_matrix(n) for i in range(n): for k in range(n): for j in range(n): c[i][j] += a[i][k] * b[k][j] return c def baseline_matrix_multiply_flipjk_faster(a, b, n): ''' same as baseline but switch j and k loops ''' c = zero_matrix(n) for i in range(n): ci = c[i] for k in range(n): bk = b[k] aik = a[i][k] for j in range(n): ci[j] += aik * bk[j] return c def fast_matrix_multiply_blocking(a, b, n): ''' use blocking ''' c = zero_matrix(n) block = 25; en = int(block * n/block) for kk in range(0, en, block): for jj in range(0, en, block): for i in range(n): for j in range(jj, jj + block): sum = c[i][j] for k in range(kk, kk + block): sum += a[i][k] * b[k][j] c[i][j] = sum return c def fast_matrix_multiply_blocking_faster(a, b, n): ''' use blocking ''' c = zero_matrix(n) block = 25; en = int(block * n/block) for kk in range(0, en, block): for jj in range(0, en, block): for i in range(n): ai = a[i] ci = c[i] for j in range(jj, jj + block): s = ci[j] for k in range(kk, kk + block): s += ai[k] * b[k][j] ci[j] = s return c def init_ab(sz): return [list(range(sz)) for i in range(sz)],[[3]*sz for i in range(sz)] sz=200 import time a,b = init_ab(sz) start_time=time.time() baseline_matrix_multiply(a,b,sz) print("baseline_matrix_multiply: "+str(time.time()-start_time)) a,b = init_ab(sz) start_time=time.time() baseline_matrix_multiply_flipjk(a,b,sz) print("baseline_matrix_multiply_flipjk: "+str(time.time()-start_time)) a,b = init_ab(sz) start_time=time.time() fast_matrix_multiply_blocking(a,b,sz) print("fast_matrix_multiply_blocking: "+str(time.time()-start_time)) a,b = init_ab(sz) start_time=time.time() baseline_matrix_multiply_flipjk_faster(a,b,sz) print("**baseline_matrix_multiply_flipjk_faster**: "+str(time.time()-start_time)) a,b = init_ab(sz) start_time=time.time() fast_matrix_multiply_blocking_faster(a,b,sz) print("**fast_matrix_multiply_blocking_faster**: "+str(time.time()-start_time)) </code></pre> <p>results on my PC (last results surrounded with stars are my versions):</p> <pre><code>baseline_matrix_multiply: 2.578160047531128 baseline_matrix_multiply_flipjk: 2.5315518379211426 fast_matrix_multiply_blocking: 1.9359750747680664 **baseline_matrix_multiply_flipjk_faster**: 1.4532990455627441 **fast_matrix_multiply_blocking_faster**: 1.7031919956207275 </code></pre> <p>As you can see, my version of your <code>baseline_matrix_multiply_flipjk</code> (the fourth one) is faster than even the block multiply, meaning that index checking &amp; accessing dwarves the cache effect that you can experience in compiled languages &amp; using direct pointers like C or C++.</p> <p>I just stored the values that were not changing in the inner loop (the one to optimize most) to avoid index access.</p> <p>Note that I tried to apply the same recipe to the block multiply and I gained some time compared to your version, but is still beaten by the flipjk_faster version because of the unability to avoid index access.</p> <p>Maybe compiling the code using Cython and drop the checks would get the result you want. But pre-computing indexes never hurts.</p>
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 is initialized. Is that the best way to do it, or are there any other approaches I should follow/consider?</p> <p>Sorry, new to pyramid and python, thank you!</p>
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> boosts the performance in a significant way. In your situation this just might be the case: If the config file is used in many places across you app, reading the file multiple times might impact your performance. However, if you choose to use a Singleton, keep in mind the dangers that come with it.</p> <p>To answer you question, I don't think it's possible to tell what's the <em>best</em> way for you to go, because that depends on your specific app. I can only suggest that you take into account the pros and cons of each option, and making your choice depending on your needs.</p>
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 python script:</p> <pre><code>import time from Xlib import display while True: d = display.Display().screen().root.query_pointer()._data print(d["root_x"], d["root_y"]) time.sleep(0.1) </code></pre> <p>It works but the CPU usage is increasing over time. With <code>time.sleep(1)</code> it takes some time but sooner or later it reaches crazy values.</p> <p>I'm on Ubuntu 16.04.1 LTS using Python 3.5 with python3-xlib 0.15</p>
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().screen() while True: d = disp.root.query_pointer()._data print(d["root_x"], d["root_y"]) time.sleep(0.1) </code></pre> <p>I've tested it and it stays at about 0.3% for me.</p> <p>Hope it this helps :)</p>
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 from selenium.common.exceptions import TimeoutException import os import time chromedriver = "chromedriver.exe" driver = webdriver.Chrome() driver.get("http://www.example.com/load") </code></pre>
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 necessary packages.</p> <pre><code>%matplotlib inline import warnings import numpy as np import pandas as pd import scipy.stats as st import statsmodels as sm import matplotlib import matplotlib.pyplot as plt matplotlib.rcParams['figure.figsize'] = (16.0, 12.0) matplotlib.style.use('ggplot') # Create models from data def best_fit_distribution(data, bins=200, ax=None): """Model data by finding best fit distribution to data""" # Get histogram of original data y, x = np.histogram(data, bins=bins, normed=True) x = (x + np.roll(x, -1))[:-1] / 2.0 # Distributions to check DISTRIBUTIONS = [ st.alpha,st.anglit,st.arcsine,st.beta,st.betaprime,st.bradford,st.burr,st.cauchy,st.chi,st.chi2,st.cosine, st.dgamma,st.dweibull,st.erlang,st.expon,st.exponnorm,st.exponweib,st.exponpow,st.f,st.fatiguelife,st.fisk, st.foldcauchy,st.foldnorm,st.frechet_r,st.frechet_l,st.genlogistic,st.genpareto,st.gennorm,st.genexpon, st.genextreme,st.gausshyper,st.gamma,st.gengamma,st.genhalflogistic,st.gilbrat,st.gompertz,st.gumbel_r, st.gumbel_l,st.halfcauchy,st.halflogistic,st.halfnorm,st.halfgennorm,st.hypsecant,st.invgamma,st.invgauss, st.invweibull,st.johnsonsb,st.johnsonsu,st.ksone,st.kstwobign,st.laplace,st.levy,st.levy_l,st.levy_stable, st.logistic,st.loggamma,st.loglaplace,st.lognorm,st.lomax,st.maxwell,st.mielke,st.nakagami,st.ncx2,st.ncf, st.nct,st.norm,st.pareto,st.pearson3,st.powerlaw,st.powerlognorm,st.powernorm,st.rdist,st.reciprocal, st.rayleigh,st.rice,st.recipinvgauss,st.semicircular,st.t,st.triang,st.truncexpon,st.truncnorm,st.tukeylambda, st.uniform,st.vonmises,st.vonmises_line,st.wald,st.weibull_min,st.weibull_max,st.wrapcauchy ] # Best holders best_distribution = st.norm best_params = (0.0, 1.0) best_sse = np.inf # Estimate distribution parameters from data for distribution in DISTRIBUTIONS: # Try to fit the distribution try: # Ignore warnings from data that can't be fit with warnings.catch_warnings(): warnings.filterwarnings('ignore') # fit dist to data params = distribution.fit(data) # Separate parts of parameters arg = params[:-2] loc = params[-2] scale = params[-1] # Calculate fitted PDF and error with fit in distribution pdf = distribution.pdf(x, loc=loc, scale=scale, *arg) sse = np.sum(np.power(y - pdf, 2.0)) # if axis pass in add to plot try: if ax: pd.Series(pdf, x).plot(ax=ax) end except Exception: pass # identify if this distribution is better if best_sse &gt; sse &gt; 0: best_distribution = distribution best_params = params best_sse = sse except Exception: pass return (best_distribution.name, best_params) def make_pdf(dist, params, size=10000): """Generate distributions's Propbability Distribution Function """ # Separate parts of parameters arg = params[:-2] loc = params[-2] scale = params[-1] # Get sane start and end points of distribution start = dist.ppf(0.01, *arg, loc=loc, scale=scale) if arg else dist.ppf(0.01, loc=loc, scale=scale) end = dist.ppf(0.99, *arg, loc=loc, scale=scale) if arg else dist.ppf(0.99, loc=loc, scale=scale) # Build PDF and turn into pandas Series x = np.linspace(start, end, size) y = dist.pdf(x, loc=loc, scale=scale, *arg) pdf = pd.Series(y, x) return pdf # Load data from statsmodels datasets data = pd.Series(sm.datasets.elnino.load_pandas().data.set_index('YEAR').values.ravel()) # Plot for comparison plt.figure(figsize=(12,8)) ax = data.plot(kind='hist', bins=50, normed=True, alpha=0.5, color=plt.rcParams['axes.color_cycle'][1]) # Save plot limits dataYLim = ax.get_ylim() # Find best fit distribution best_fit_name, best_fir_paramms = best_fit_distribution(data, 200, ax) best_dist = getattr(st, best_fit_name) # Update plots ax.set_ylim(dataYLim) ax.set_title(u'El Niño sea temp.\n All Fitted Distributions') ax.set_xlabel(u'Temp (°C)') ax.set_ylabel('Frequency') # Make PDF pdf = make_pdf(best_dist, best_fir_paramms) # Display plt.figure(figsize=(12,8)) ax = pdf.plot(lw=2, label='PDF', legend=True) data.plot(kind='hist', bins=50, normed=True, alpha=0.5, label='Data', legend=True, ax=ax) param_names = (best_dist.shapes + ', loc, scale').split(', ') if best_dist.shapes else ['loc', 'scale'] param_str = ', '.join(['{}={:0.2f}'.format(k,v) for k,v in zip(param_names, best_fir_paramms)]) dist_str = '{}({})'.format(best_fit_name, param_str) ax.set_title(u'El Niño sea temp. with best fit distribution \n' + dist_str) ax.set_xlabel(u'Temp. (°C)') ax.set_ylabel('Frequency') </code></pre>
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 need to remove the top line of the file:</p> <pre><code>%matplotlib inline </code></pre> <p>Because it is for Ipython notebooks and you are using a python interpreter not a notebook</p>
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_sort(lst) [1, 3, 4, 5, 6] """ if len(lst) &lt;= 1: return lst mid = len(lst) // 2 left = merge_sort(lst[:mid]) right = merge_sort(lst[mid:]) return merge(left, right), counter def merge(left, right): """Takes two sorted lists and returns a single sorted list by comparing the elements one at a time. &gt;&gt;&gt; left = [1, 5, 6] &gt;&gt;&gt; right = [2, 3, 4] &gt;&gt;&gt; merge(left, right) [1, 2, 3, 4, 5, 6] """ global counter if not left: return right if not right: return left counter += 1 if left[0] &lt; right[0]: return [left[0]] + merge(left[1:], right) return [right[0]] + merge(left, right[1:]) lst = [4, 5, 1, 6, 3] print(merge_sort(lst)) </code></pre> <p>Output: </p> <pre><code>([1,3,4,5,6], counter) </code></pre>
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: counter += 1 # increment counter when we dividing array on two return lst mid = len(lst) // 2 left = merge_sort(lst[:mid]) right = merge_sort(lst[mid:]) return merge(left, right) def merge(left, right): global counter if not left: counter += 1 # increment counter when not left (not left - is also comparison) return right if not right: counter += 1 # the same as above for right return left if left[0] &lt; right[0]: counter += 1 # and the final one increment return [left[0]] + merge(left[1:], right) return [right[0]] + merge(left, right[1:]) lst = [4, 5, 1, 6, 3] # also you don't need to return counter since you are using global value print(merge_sort(lst), counter) </code></pre> <p><a href="http://codereview.stackexchange.com/questions/12922/inversion-count-using-merge-sort">Also you may try to look here!</a></p>
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_sort(lst) [1, 3, 4, 5, 6] """ if len(lst) &lt;= 1: return lst mid = len(lst) // 2 left = merge_sort(lst[:mid]) right = merge_sort(lst[mid:]) return merge(left, right), counter def merge(left, right): """Takes two sorted lists and returns a single sorted list by comparing the elements one at a time. &gt;&gt;&gt; left = [1, 5, 6] &gt;&gt;&gt; right = [2, 3, 4] &gt;&gt;&gt; merge(left, right) [1, 2, 3, 4, 5, 6] """ global counter if not left: return right if not right: return left counter += 1 if left[0] &lt; right[0]: return [left[0]] + merge(left[1:], right) return [right[0]] + merge(left, right[1:]) lst = [4, 5, 1, 6, 3] print(merge_sort(lst)) </code></pre> <p>Output: </p> <pre><code>([1,3,4,5,6], counter) </code></pre>
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] left_ndx = 0 right_ndx = 0 final_ndx = 0 while left_ndx &lt; len(left_part[0]) and right_ndx &lt; len(right_part[0]): counter += 1 if left_part[0][left_ndx] &lt; right_part[0][right_ndx]: input_array[final_ndx] = left_part[0][left_ndx] left_ndx += 1 else: input_array[final_ndx] = right_part[0][right_ndx] right_ndx += 1 final_ndx += 1 while left_ndx &lt; len(left_part[0]): input_array[final_ndx] = left_part[0][left_ndx] left_ndx += 1 final_ndx += 1 counter += 1 while right_ndx &lt; len(right_part[0]): input_array[final_ndx] = right_part[0][right_ndx] right_ndx += 1 final_ndx += 1 counter += 1 return input_array, counter </code></pre> <p>So the output would be:</p> <pre><code>([1,3,4,5,6], counter) </code></pre>
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 product of numerator and inverse of denominator. Both items are of format <code>sp.csr_matrix(([],([],[])),shape=[R,R])</code>.</p> <p>The calculation for k itself is </p> <pre><code>k = sp.csr_matrix(numerator.dot(sp.linalg.inv(denominator))) </code></pre> <p>Doing this returns the warning:</p> <pre><code>SparseEfficiencyWarning: splu requires CSC matrix format warn('splu requires CSC matrix format', SparseEfficiencyWarning) </code></pre> <p><strong>What does the above warning mean</strong> in relation to determining the identity of <code>k</code> as the quotient between two sparse matrices? </p> <p><strong>Is there a more efficient way</strong> to generate the dot product of a sparse matrix and a sparse matrix inverse in python (the quotient of two sparse matrices)?</p> <p>I had previously found <a href="http://stackoverflow.com/questions/15118177/inverting-large-sparse-matrices-with-scipy">Inverting large sparse matrices with scipy</a>, however I wonder if this may be outdated.</p>
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> <p>The <code>np</code> inv is not <code>sparse-aware</code>:</p> <pre><code>In [412]: np.linalg.inv(A) .... LinAlgError: 0-dimensional array given. Array must be at least two-dimensional </code></pre> <p>With <code>from scipy.sparse import linalg</code>:</p> <pre><code>In [414]: linalg.inv(A).A /usr/lib/python3/dist-packages/scipy/sparse/linalg/dsolve/linsolve.py:243: SparseEfficiencyWarning: splu requires CSC matrix format warn('splu requires CSC matrix format', SparseEfficiencyWarning) /usr/lib/python3/dist-packages/scipy/sparse/linalg/dsolve/linsolve.py:161: SparseEfficiencyWarning: spsolve is more efficient when sparse b is in the CSC matrix format 'is in the CSC matrix format', SparseEfficiencyWarning) Out[414]: array([[ 26.11275413, -4.17749006, -9.82626551], [-37.22611759, 9.38404027, 13.80073216], [ 7.59314843, -2.04314605, -1.58410661]]) </code></pre> <p>So use the <code>csc</code> format instead of <code>csr</code>:</p> <pre><code>In [415]: A1=sparse.csc_matrix(a) In [416]: linalg.inv(A1).A Out[416]: array([[ 26.11275413, -4.17749006, -9.82626551], [-37.22611759, 9.38404027, 13.80073216], [ 7.59314843, -2.04314605, -1.58410661]]) </code></pre> <p>Same thing, but without the sparsity warning. Without getting into details, the <code>inv</code> must be using a method that iterates on columns rather than rows. It does <code>spsolve(A, I)</code> (<code>I</code> is a sparse <code>eye</code> matrix).</p>
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 address 192.168.20.45 netmask 255.255.255.0 gateway 192.168.20.1 </code></pre> <p>Raspberry Pi (TCP client) has the following script to connect:</p> <pre><code>import socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(('192.168.20.48',1234)) </code></pre> <p>And frankly, it get stuck in the connect step, doesnt even get past that. On the TCP server side running on Windows, IPv4 setup is as follows:</p> <pre><code>192.168.20.48 255.255.255.0 192.168.20.1 </code></pre> <p>with Google DNS</p> <pre><code>8.8.8.8 8.8.4.4 </code></pre> <p>Weird thing is that it works the other way around, if I set up my computer as client and connect to raspberry pi. Could you give me some ideas as to what could be the problem? I really could use some opinion. Thanks in advance to everyone.</p>
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>This is how I'm calling the script from my python script:</p> <pre><code>req = subprocess.Popen([r'C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe', '-ExecutionPolicy', 'Unrestricted', './call.ps1', param1, param2], cwd=os.getcwd()) print("^^^^^^^") result = req.wait() #something is going wrong here print("****************") print(result) if result == 0: # do something else: # do something else </code></pre> <p>Now this is where its going wrong... even when the POST request is failing the "result" variable still has "0" and not "99". When I separately run the powershell script I can see that its returning 99 when the POST request is failing. So the problem is not with the powershell file it seems.</p> <p>On debugging python file, this is what i see on console: (notice the order of print statements in the python code)</p> <pre><code>^^^^^^^ 99 **************** 0 </code></pre> <p>One thing that I don't understand is.. what is "99" doing in the output? I'm not even printing the result between "^^^^^" and "*****". So if the powershell script is returning 99, why does it change to 0 after "*****".</p> <p>I'm really lost here. Please help.</p>
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>This is how I'm calling the script from my python script:</p> <pre><code>req = subprocess.Popen([r'C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe', '-ExecutionPolicy', 'Unrestricted', './call.ps1', param1, param2], cwd=os.getcwd()) print("^^^^^^^") result = req.wait() #something is going wrong here print("****************") print(result) if result == 0: # do something else: # do something else </code></pre> <p>Now this is where its going wrong... even when the POST request is failing the "result" variable still has "0" and not "99". When I separately run the powershell script I can see that its returning 99 when the POST request is failing. So the problem is not with the powershell file it seems.</p> <p>On debugging python file, this is what i see on console: (notice the order of print statements in the python code)</p> <pre><code>^^^^^^^ 99 **************** 0 </code></pre> <p>One thing that I don't understand is.. what is "99" doing in the output? I'm not even printing the result between "^^^^^" and "*****". So if the powershell script is returning 99, why does it change to 0 after "*****".</p> <p>I'm really lost here. Please help.</p>
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 code from a script, so even if you had used <code>exit</code> instead of <code>return</code> the process would only have returned 0 on success or 1 in case of an error.</p> <p>To have PowerShell return a script's exit code you need to either return the exit code yourself</p> <pre class="lang-none prettyprint-override"><code>powershell.exe -Command "&amp;{.\call.ps1; exit $LASTEXITCODE}" </code></pre> <p>or call the script using the <code>-File</code> parameter</p> <pre class="lang-none prettyprint-override"><code>powershell.exe -File .\call.ps1 </code></pre> <p>To fix the problem change your PowerShell code to this:</p> <pre class="lang-bsh prettyprint-override"><code>try { Invoke-RestMethod -uri $url -Method Post -Body $body -ContentType 'application/json' -ErrorAction Stop exit 0 } catch { exit 99 } </code></pre> <p>and your Python code to this:</p> <pre class="lang-py prettyprint-override"><code>req = subprocess.Popen([r'C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe', '-ExecutionPolicy', 'Unrestricted', '-File', './test.ps1', param1, param2], cwd=os.getcwd()) print("^^^^^^^") result = req.wait() print("****************") print(result) </code></pre>
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 can't show the rest of the code. When a certain condition is met, then n is set to 0.<br> Problem is that when a new code for w is entered, w is overwritten. For example, if w = 24, then w = 54, if you print(w) it will just print 54, since it's the latest input. How do you make it so that it prints all inputs for w? <strong><em>FOR ALL YOU AWESOME PEOPLE THAT CONTRIBUTED THANK YOU!!</em></strong></p>
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 can't show the rest of the code. When a certain condition is met, then n is set to 0.<br> Problem is that when a new code for w is entered, w is overwritten. For example, if w = 24, then w = 54, if you print(w) it will just print 54, since it's the latest input. How do you make it so that it prints all inputs for w? <strong><em>FOR ALL YOU AWESOME PEOPLE THAT CONTRIBUTED THANK YOU!!</em></strong></p>
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><code>w = [] w.append(input("value1")) w.append(input("value2")) print(w[0]) print(w[1]) </code></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 can't show the rest of the code. When a certain condition is met, then n is set to 0.<br> Problem is that when a new code for w is entered, w is overwritten. For example, if w = 24, then w = 54, if you print(w) it will just print 54, since it's the latest input. How do you make it so that it prints all inputs for w? <strong><em>FOR ALL YOU AWESOME PEOPLE THAT CONTRIBUTED THANK YOU!!</em></strong></p>
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 in inputs: # for each item in the inputs list print(i) # print the item </code></pre> <p><strong>Note:</strong> The above code will not compile. You need to fill in the value for the variable <code>n</code>.</p>
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 able to keep the hierarchy of keys/indexes if possible. This will be used to assess the scope of the data and it's availability. The data comes from a JSON file and it's contents are subject to change.</p> <p>My latest attempt is to do this through a series of type checks within a function, <code>skim()</code>, as seen below.</p> <pre><code>def skim(obj, header='', level=0): if obj is None: return def skim_iterable(iterable): lvl = level +1 if isinstance(iterable, (list, tuple)): for value in iterable: h = ':'.join([header, iterable.index(value)]) return skim(value, header=h, level=lvl) elif isinstance(iterable, dict): for key, value in iterable.items(): h = ':'.join([header, key]) return skim(value, header=h, level=lvl) if isinstance(obj, (int, float, str, bool)): return ':'.join([header, obj, level]) elif isinstance(obj, (list, dict, tuple)): return skim_iterable(obj) </code></pre> <p>The intent is to make a recursive call to <code>skim()</code> until the key or list index position at the deepest level is passed and then returned. <code>skim</code> has a inner function that handles iterable objects which carries the level along with the key value or list index position forward through each nestled iterable object. </p> <p>An example below</p> <pre><code>test = {"level_0Item_1": { "level_1Item_1": { "level_2Item_1": "value", "level_2Item_2": "value" }, "level_1Item_2": { "level_2Item_1": "value", "level_2Item_2": {} }}, "level_0Item_2": [ { "level_1Item_1": "value", "level_1Item_2": 569028742 } ], "level_0Item_3": [] } collection = [skim(test)] </code></pre> <p>Right now I'm getting a return of <code>[None]</code> on the above code and would like some help troubleshooting or guidance on how best to approach this. What I was expecting is something like this:</p> <pre><code>['level_0Item_1:level_1Item_1:level_2Item_1', 'level_0Item_1:level_1Item_1:level_2Item_2', 'level_0Item_1:level_1Item_2:level_2Item_1', 'level_0Item_1:level_1Item_2:level_2Item_2', 'level_0Item_2:level_1Item_1', 'level_0Item_2:level_1Item_2', 'level_0Item_3] </code></pre> <p>Among other resources, I recently came across this question <a href="http://stackoverflow.com/questions/29283267/python-json-complex-objects-accounting-for-subclassing">(python JSON complex objects (accounting for subclassing)</a>), read it and it's included references. Full disclosure here, I've only began coding recently.</p> <p>Thank you for your help.</p>
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 isinstance(v, list) and v: yield from skim(v[0], connector, level + 1, builded_str + k + connector) else: yield builded_str + k else: yield builded_str </code></pre> <p>Test:</p> <pre><code>test = {"level_0Item_1": { "level_1Item_1": { "level_2Item_1": "value", "level_2Item_2": "value" }, "level_1Item_2": { "level_2Item_1": "value", "level_2Item_2": {} }}, "level_0Item_2": [ { "level_1Item_1": "value", "level_1Item_2": 569028742 } ], "level_0Item_3": [] } lst = list(skim(test)) print(lst) ['level_0Item_1:level_1Item_2:level_2Item_1`', 'level_0Item_1:level_1Item_2:level_2Item_2', 'level_0Item_1:level_1Item_1:level_2Item_1', 'level_0Item_1:level_1Item_1:level_2Item_2', 'level_0Item_2:level_1Item_2', 'level_0Item_2:level_1Item_1', 'level_0Item_3']` </code></pre>
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="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;input type="text" placeholder= $:name2 value= $:name2 name="name3" id="nome3" readonly&gt;</code></pre> </div> </div> </p> <p>I tried $:name2 and $name2, maybe because of some string format.</p>
-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', 'goodbye thank you hello', 'i am going home goodbye thanks', 'thank you very much sir', 'good golly i am going home finally'] vectorizer = HashingVectorizer() X = vectorizer.fit_transform(docs) for k in range(5): model = MiniBatchKMeans(n_clusters = k) model.fit(X) </code></pre> <p>And I receive this error:</p> <pre><code>Warning (from warnings module): File "C:\Python34\lib\site-packages\sklearn\cluster\k_means_.py", line 1279 0, n_samples - 1, init_size) DeprecationWarning: This function is deprecated. Please call randint(0, 4 + 1) instead Traceback (most recent call last): File "&lt;pyshell#85&gt;", line 3, in &lt;module&gt; model.fit(X) File "C:\Python34\lib\site-packages\sklearn\cluster\k_means_.py", line 1300, in fit init_size=init_size) File "C:\Python34\lib\site-packages\sklearn\cluster\k_means_.py", line 640, in _init_centroids x_squared_norms=x_squared_norms) File "C:\Python34\lib\site-packages\sklearn\cluster\k_means_.py", line 88, in _k_init n_local_trials = 2 + int(np.log(n_clusters)) OverflowError: cannot convert float infinity to integer </code></pre> <p>I know the <code>type(k)</code> is <code>int</code>, so I don't know where this issue is coming from. I can run the following just fine, but I can't seem to iterate through integers in a list, even though the <code>type(2)</code> is equal to <code>k = 2; type(k)</code></p> <pre><code>model = MiniBatchKMeans(n_clusters = 2) model.fit(X) </code></pre> <p>Even running a different <code>model</code> works:</p> <pre><code>&gt;&gt;&gt; model = KMeans(n_clusters = 2) &gt;&gt;&gt; model.fit(X) KMeans(copy_x=True, init='k-means++', max_iter=300, n_clusters=2, n_init=10, n_jobs=1, precompute_distances='auto', random_state=None, tol=0.0001, verbose=0) </code></pre>
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_clusters=0</code> is used</li> <li>Within the optimization-code (look at the output):</li> <li><code>int(np.log(n_clusters))</code></li> <li>= <code>int(np.log(0))</code></li> <li>= <code>int(-inf)</code></li> <li>ERROR: no infinity definition for integers!</li> <li>-> casting floating-point value of -inf to int not possible!</li> </ul></li> </ul> <p>Setting <code>n_clusters=0</code> does not make sense!</p>
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> <p>Thank you!!!</p> <pre><code>import random def main(): print "Hello what is your name?" name = raw_input() print "" number = input("Well, "+name+", I am thinking of a number between 1 and 100. Please type your first guess: ") guess(number) def guessing(number1): guessed = False num_guesses = 0 randomNumber = random.randrange(1, 100) while num_guesses &lt; 7 and not guessed: print "Please enter a guess." guess = int(raw_input()) num_guesses += 1 if guess == num: guessed = True elif guess &gt; num: print "Too High" else: print "Too Low" if guessed: if num_guesses &gt; 1: print "Congratulations! You got the number in", num_guesses, "guesses." else: print "Congratulations! You got the number in 1 guess." else: print "You did not guess the number in",num_guesses,"guesses." playAagain = raw_input ("Excellent! You guessed the number! Would you like to play again (y or n)? ") if playAagain == "y": main() main() </code></pre>
-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 the strange errors you're experiencing.</p> <p>Quit your editor (or just type <code>del guess</code> in the editor python console) and you'll have coherent errors, the first one being calling <code>guess(number)</code> instead of <code>guessing(number)</code>, but there are others... Good luck with your program.</p>
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> <p>Thank you!!!</p> <pre><code>import random def main(): print "Hello what is your name?" name = raw_input() print "" number = input("Well, "+name+", I am thinking of a number between 1 and 100. Please type your first guess: ") guess(number) def guessing(number1): guessed = False num_guesses = 0 randomNumber = random.randrange(1, 100) while num_guesses &lt; 7 and not guessed: print "Please enter a guess." guess = int(raw_input()) num_guesses += 1 if guess == num: guessed = True elif guess &gt; num: print "Too High" else: print "Too Low" if guessed: if num_guesses &gt; 1: print "Congratulations! You got the number in", num_guesses, "guesses." else: print "Congratulations! You got the number in 1 guess." else: print "You did not guess the number in",num_guesses,"guesses." playAagain = raw_input ("Excellent! You guessed the number! Would you like to play again (y or n)? ") if playAagain == "y": main() main() </code></pre>
-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 = input() print ("") print ("Well, "+name+", I am thinking of a number between 1 and 100. Please type your first guess: ") guessed = False num_guesses = 0 num = random.randrange(1, 100) while num_guesses &lt; 7 and not guessed: print ("Please enter a guess.") guess = int(input()) num_guesses += 1 if guess == num: guessed = True elif guess &gt; num: print ("Too High") else: print ("Too Low") if guessed: if num_guesses &gt; 1: print ("Congratulations! You got the number in", num_guesses, "guesses.") else: print ("Congratulations! You got the number in 1 guess.") else: print ("You did not guess the number in",num_guesses,"guesses.") playAagain = input ("Excellent! You guessed the number! Would you like to play again (y or n)? ") if playAagain == "y": main() main() </code></pre>
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 absolute path to the previous path (before renaming).</p> <p>Using grep I found out multiple references to absolute paths relative to the <code>--prefix</code> folder.</p> <p>I tried to override it by setting the <code>PATH</code>,<code>PYTHONPATH</code> and <code>PYTHONHOME</code> environment variables but it's not better.</p> <p>Is there a way to compile the python sources in a way that I can freely moves it after ?</p>
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 into a new <strong>virtualenv</strong>.</p>
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", "http://pitchfork.com/reviews/best/tracks/?page=2", "http://pitchfork.com/reviews/best/tracks/?page=3", ] </code></pre> <p>everything is working fine.</p> <p>now, instead of hitting the pages directely, I would like to scrape <code>google</code> <code>caches</code> of the same pages. </p> <p>what is the proper <code>syntax</code>to achieve that?</p> <p><strong>PS:</strong> I have tried <code>"cache:http://pitchfork.com/reviews/best/tracks/?page=1",</code>, to no avail.</p>
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 render(request, 'borsa/car_list.html', {'cars': cars}) </code></pre> <p>in car_list.html:</p> <pre><code> {% for car in cars %} &lt;a href="car/{{ car.pk }}/view/"&gt; &lt;img class="media-object tmbpic" src="{{ car.carphotos_set.all.0.image.url }}" alt="kola"&gt; &lt;/a&gt; </code></pre> <p>The first method I've used was to use inline formsets but I had no clue how to access the images. Can you please point me in the right direction of how to access images according to Car objects ? I mean every Car must have a couple of images and I need to display only the first one in list view, but then I need to display all of them in Detail view. </p>
-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 any way I make it the same random number initialization, so that I could reoccur the exprinment result and analyze? </p>
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>The output of <code>python args.py</code> is:</p> <pre><code>usage: args.py [-h] [--optional1 OPTIONAL1] [--optional2 OPTIONAL2] positional </code></pre> <p>however I would like to have:</p> <pre><code>usage: args.py [-h] positional [--optional1 OPTIONAL1] [--optional2 OPTIONAL2] </code></pre> <p>How could I have that reordering?</p>
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, though, does not affect the order in which you can specify the arguments. <code>argparse</code> processes any defined options left-to-right, then assigns any remaining arguments to the positional parameters from left to right. Options and positional arguments can, for the most part, be mixed.</p>
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>The output of <code>python args.py</code> is:</p> <pre><code>usage: args.py [-h] [--optional1 OPTIONAL1] [--optional2 OPTIONAL2] positional </code></pre> <p>however I would like to have:</p> <pre><code>usage: args.py [-h] positional [--optional1 OPTIONAL1] [--optional2 OPTIONAL2] </code></pre> <p>How could I have that reordering?</p>
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</code>.)</p> <p>For the <code>usage</code> line, <code>argparse</code> moves the <code>positionals</code> to the end of the list, but that just a display convention.</p> <p>There have been SO questions about changing that display order, but I think that is usually not needed. If you must change the display order, using a custom <code>usage</code> parameter is the simplest option. The programming way requires subclassing the help formatter and modifying a key method.</p>
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 broken into many functions so I combined it here)</p> <pre><code>import xml.etree.ElementTree as ElementTree def AddSubElement(parent, tag, text='', attributes = None): XMLelement = ElementTree.SubElement(parent, tag) XMLelement.text = text if attributes != None: for key, value in attributes: XMLelement.set(key, value) print("attributes =",attributes) return XMLelement descriptionTags = ([('xmlns:g' , 'http://base.google.com/ns/1.0')]) XMLroot = ElementTree.Element('rss') XMLroot.set('version', '2.0') XMLchannel = ElementTree.SubElement(XMLroot,'channel') AddSubElement(XMLchannel,'g:description', 'sporting goods', attributes=descriptionTags ) AddSubElement(XMLchannel,'link', 'http://'+ domain +'/') XMLitem = AddSubElement(XMLchannel,'item') AddSubElement(XMLitem, 'g:brand', Product['ProductManufacturer'], attributes=bindingParam) AddSubElement(XMLitem, 'g:description', Product['ProductDescriptionShort'], attributes=bindingParam) AddSubElement(XMLitem, 'g:price', Product['ProductPrice'] + ' USD', attributes=bindingParam) </code></pre> <p>The key and value does get switched! Because I'll see this in the console sometimes:</p> <pre><code>attributes = [{'xmlns:g', 'http://base.google.com/ns/1.0'}] attributes = [{'http://base.google.com/ns/1.0', 'xmlns:g'}] attributes = [{'http://base.google.com/ns/1.0', 'xmlns:g'}] ... </code></pre> <p>And here is the xml string that sometimes comes out:</p> <pre><code>&lt;rss version="2.0"&gt; &lt;channel&gt; &lt;title&gt;example.com&lt;/title&gt; &lt;g:description xmlns:g="http://base.google.com/ns/1.0"&gt;sporting goods&lt;/g:description&gt; &lt;link&gt;http://www.example.com/&lt;/link&gt; &lt;item&gt; &lt;g:id http://base.google.com/ns/1.0="xmlns:g"&gt;8987983&lt;/g:id&gt; &lt;title&gt;Some cool product&lt;/title&gt; &lt;g:brand http://base.google.com/ns/1.0="xmlns:g"&gt;Cool&lt;/g:brand&gt; &lt;g:description http://base.google.com/ns/1.0="xmlns:g"&gt;Why is this so cool?&lt;/g:description&gt; &lt;g:price http://base.google.com/ns/1.0="xmlns:g"&gt;69.00 USD&lt;/g:price&gt; ... </code></pre> <p>What is causing this to flip?</p>
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 and then as my loop iterates, I am attempting to add a new column. This adds the column names but doesn't add values to the rows.</p> <p><strong>Note</strong> matrix is a multi-level hash </p> <pre><code> {'ABC10059536': {'577908224': '0.5902'}, 'ABC10799208': {'577908224': '0.369'}, 'ABC12564102': {'577908224': '0.163'}, 'ABC17441804': {'577908224': '0.4233'}, 'ABC20764275': {'577908224': '0.349'}, 'ABC21090866': {'577908224': '0.4704'}} </code></pre>
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'}, 'ABC17441804': {'577908224': '0.4233'}, 'ABC20764275': {'577908224': '0.349'}, 'ABC21090866': {'577908224': '0.4704'}} df = pd.DataFrame(d) print (df) ABC10059536 ABC10799208 ABC12564102 ABC17441804 ABC20764275 \ 577908224 0.5902 0.369 0.163 0.4233 0.349 ABC21090866 577908224 0.4704 </code></pre>
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=['A', 'B', 'C', 'D']) # Filtering df1 = df1.loc[lambda df: -0.5 &lt; df1.A &lt; 0 and 0 &lt;= df1.B &lt;= 1, :] </code></pre> <p>Any thoughts on it?</p>
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) &amp; (B &lt;= 1)', engine='python')) df1 = df1.loc[(df1.A &gt; -0.5) &amp; (df1.A &lt; 0) &amp; (df1.B &gt;= 0) &amp; (df1.B &lt;= 1)] df1 = df1[(df1.A &gt; -0.5) &amp; (df1.A &lt; 0) &amp; (df1.B &gt;= 0) &amp; (df1.B &lt;= 1)] </code></pre> <p>Consider even using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.between.html" rel="nofollow">pandas.Series.between</a>:</p> <pre><code>df1 = df1.loc[(df1.A.between(-0.5, 0, inclusive=False) &amp; (df1.B.between(0, 1))] </code></pre>
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 this:</p> <pre><code> abc xyz def 0 0.093889 0.113750 0.082923 1 -0.130293 -0.148742 -0.061890 2 0.062175 -0.005463 0.022963 3 -0.029041 -0.015918 0.006735 4 -0.048950 -0.010945 -0.034421 5 0.082868 0.080570 0.074637 6 0.048782 -0.030702 -0.003748 7 -0.027402 -0.065221 -0.054764 8 0.095154 0.063978 0.039480 9 0.059001 0.114566 0.056582 </code></pre> <p>How can I create something like this, where abc_px = previous price * (1 + abc). I know I could iterate over, but I would rather not for performance reasons.</p> <p>Something like, assuming the initial price on all of these was 100:</p> <pre><code>abc xyz def abc_px xyz_px def_px 0 0.093889 0.11375 0.082923 109.39 111.38 108.29 1 -0.130293 -0.148742 -0.06189 95.14 94.81 101.59 2 0.062175 -0.005463 0.022963 101.05 94.29 103.92 3 -0.029041 -0.015918 0.006735 98.12 92.79 104.62 4 -0.04895 -0.010945 -0.034421 93.31 91.77 101.02 5 0.082868 0.08057 0.074637 101.05 99.17 108.56 6 0.048782 -0.030702 -0.003748 105.98 96.12 108.15 7 -0.027402 -0.065221 -0.054764 103.07 89.85 102.23 8 0.095154 0.063978 0.03948 112.88 95.60 106.27 9 0.059001 0.114566 0.056582 119.54 106.56 112.28 </code></pre>
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.080570 1.074637 6 1.048782 0.969298 0.996252 7 0.972598 0.934779 0.945236 8 1.095154 1.063978 1.039480 9 1.059001 1.114566 1.056582 In [133]: df.join(new.cumprod() * 100) Out[133]: abc xyz def abc_px xyz_px def_px 0 0.093889 0.113750 0.082923 109.388900 111.375000 108.292300 1 -0.130293 -0.148742 -0.061890 95.136292 94.808860 101.590090 2 0.062175 -0.005463 0.022963 101.051391 94.290919 103.922903 3 -0.029041 -0.015918 0.006735 98.116758 92.789996 104.622824 4 -0.048950 -0.010945 -0.034421 93.313942 91.774410 101.021601 5 0.082868 0.080570 0.074637 101.046682 99.168674 108.561551 6 0.048782 -0.030702 -0.003748 105.975941 96.123997 108.154662 7 -0.027402 -0.065221 -0.054764 103.071989 89.854694 102.231680 8 0.095154 0.063978 0.039480 112.879701 95.603418 106.267787 9 0.059001 0.114566 0.056582 119.539716 106.556319 112.280631 </code></pre>
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,0) def getColor(self): return self.color </code></pre> <p>This is the parent class and child class.</p> <pre><code>from IsVisible import * class Object(IsVisible): def __init__(self): super(Object, self).__init__() self.posSize = [] def getPosSize(self): return self.posSize class Rectangle(Object): def __init__(self): super(Rectangle, self).__init__() self.color = self.blue self.posSize = [20,50,100,100] </code></pre> <p>So Im trying to call <code>getColor</code> by creating an object </p> <pre><code>rectangle = Rectangle() </code></pre> <p>and then calling </p> <pre><code>rectangle.getColor() </code></pre> <p>However I'm getting an error. Namely:</p> <pre><code>AttributeError: 'Rectangle' object has no attribute 'getColor' </code></pre> <p>Now I have no idea how to solve this. I have tried to google "python call grandparent method" but I only get instructions for how to call a method that is overrun... I believe I have stated the inheritance correctly so I don't know what the problem is. Could anyone help me?</p>
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 return self.color </code></pre> <p>But be careful about class vs. instance variables. See <a href="http://stackoverflow.com/a/3434596/2877364">this answer</a> for more (not copied here since it's not the answer to your question above). </p> <p>Also, please don't use <code>Object</code> as the name of a class :) . It is too likely to lead to confusion with the real <code>object</code>, or to confuse the reader about what you mean. How about <code>ColoredShape</code> instead of <code>IsVisible</code>, <code>PositionedShape</code> instead of <code>Object</code>, and <code>Rectangle(PositionedShape)</code>?</p>
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): req = request_class(environ=args[0]) else: req = args[0] wsgi_app = WSGIController() settings = wsgi_app.settings google_client = client.GoogleClient( settings.OAUTH2_CLIENT_ID, access_token=settings.OAUTH2_ACCESS_TOKEN, scope='email', redirect_url=settings.OAUTH2_REDIRECT_URL, login_path="/session_login/") wsgi_app = google_client.wsgi_middleware(wsgi_app, \ secret=settings.SECRET_KEY) def process_middleware(environ, start_response): return wsgi_app(environ, start_response) response = process_middleware(req.environ, f) return f(*args, **kwargs) return _wrapper </code></pre> <p>How can I handle the response object (generator) to redirect the user to the oauth login page ?</p> <p>Update: If I add the following code:</p> <blockquote> <p>redirect = [item for item in response.next()]</p> </blockquote> <p>Then I get the following error:</p> <blockquote> <p>TypeError: unhashable type: 'list'</p> </blockquote>
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_login(path, resolved_login_url, redirect_field_name) </code></pre>
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. Does something like this exist, or am I going about this the wrong way?</p>
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 across the board-- you'll probably need to use something like <a href="https://babeljs.io/" rel="nofollow">Babel</a> to transpile your code to ES5.</p>
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 temperature T is given by: </p> </blockquote> <p>Stackoverflow doesn't use MathJax for formula's, and I can't quite figure out how to write a formula on this site. So, here is a link to <a href="http://www.wolframalpha.com/input/?i=f(v)%20%3D%204*pi*((m%2F(2*pi*k*T))%5E(3%2F2))*(v%5E2)*e%5E(-(m*v%5E2)%2F(2*k*T))" rel="nofollow">WolframAlpha</a>: </p> <blockquote> <p>where k is Boltzmann's constant, k = 1.3806503 x 10-23 J/K.</p> <p>Write a Python script called maxwell.py which prints v and f(v) to standard output in two column format. For the particle mass, choose the mass of a proton, m = 1.67262158 10-27 kg. For the gas temperature, choose the temperature at the surface of the sun, T = 5778 K.</p> <p>Your output should consist of 300 data points, ranging from v = 100 m/s to v = 30,000 m/s in steps of size dv = 100 m/s.</p> </blockquote> <p>So, here is my attempt at the code. </p> <pre><code>import math as m import sys def f(v): n = 1.67262158e-27 #kg k = 1.3806503e-23 #J/K T = 5778 #Kelvin return (4*m.pi)*((n/(2*m.pi*k*T))**(3/2))*(v**2)*m.exp((-n*v**2)/(2*k*T)) v = 100 #m/s for i in range(300): a = float(f(v)) print (v, a) v = v + 100 </code></pre> <p>But, my professors solution is:</p> <pre><code>import numpy as np def f(v): m = 1.67262158e-27 # kg T = 5778. # K k = 1.3806503e-23 # J/K return 4.*np.pi * (m/(2.*np.pi*k*T))**1.5 * v**2 * np.exp(-m*v**2/(2.*k*T)) v = np.linspace(100.,30000.,300) fv = f(v) vfv = zip(v,fv) for x in vfv: print "%5.0f %.3e"%x # print np.sum(fv*100.) </code></pre> <p>So, these are very different codes. From what I can tell, they produce the same result. I guess my question is, simply, why is my code incorrect? </p> <p>Thank you!</p> <hr> <p>EDIT:</p> <p>So, I asked my professor about it and this was his response. </p> <blockquote> <p>I think your code is fine. It would run much faster using numpy, but the problem didn't specify that you needed numpy. I might have docked one point for not looping through a list of v's (your variable i doesn't do anything). Also, you should have used v += 100. Almost, these two things together would have been one point out of 10.</p> </blockquote> <p>1st: Is there any better syntax for doing the range in my code, since my variable i doesn't do anything?</p> <p>2nd: What is the purpose of v += 100? </p>
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 execute the script.</p> <p>When I execute the pipeline I get this error:</p> <blockquote> <p>/usr/bin/python: can't open file '/home/ubuntu/script.py': [Errno 2] No such file or directory</p> </blockquote> <p>This is because AWS DP create a complete new EC2 instance when it runs, and my <code>script.py</code> is not there.</p> <p>I created a Resource EC2 <a href="https://i.stack.imgur.com/DNs9G.png" rel="nofollow"><img src="https://i.stack.imgur.com/DNs9G.png" alt="enter image description here"></a></p> <p>But there is not a field to define my own EC2 instance. How can I do this? Or maybe there some other way to approach this.</p> <p>Thanks.</p>
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 containment, certain rules must be followed: The case of alphabetic characters should be ignored Leading and trailing whitespace should be ignored Any other block of contiguous whitespace should be treated as a single space non-alphanumeric character should be ignored, white space should be retained Duplicates must also be filtered - if two passages are considered equal with respect to the comparison rules listed above, only the shortest should be retained. If they are also the same length, the earlier one in the input sequence should be kept. The retained passages should be output in their original form (identical to the input passage), and in the same order.</p> <p>Input1: IBM cognitive computing|IBM "cognitive" computing is a revolution| ibm cognitive computing|'IBM Cognitive Computing' is a revolution? </p> <p>Output1: IBM "cognitive" computing is a revolution</p> <p>Input2: IBM cognitive computing|IBM "cognitive" computing is a revolution|the cognitive computing is a revolution</p> <p>Output2: IBM "cognitive" computing is a revolution|the cognitive computing is a revolution</p> <p>I wrote the following code in python, but it's giving me some other output rather than the first test case:</p> <pre><code>f = open("input.txt",'r') s = (f.read()).split('|') str = '' for a in s: for b in s: if(''.join(e for e in a.lower() if e.isalnum()))not in (''.join(e for e in b.lower() if e.isalnum())): str = a.translate(None, "'?") print str </code></pre> <p><code>input.txt</code> contains the first test case input. And I am getting the output as : <strong>IBM Cognitive Computing is a revolution</strong>. Could someone please chime in and help me. Thanks</p>
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> <pre><code>import re def clean_input(text): #non-alphanumeric character should be ignored text = re.sub('[^a-zA-Z\s]', '', text) #Any other block of contiguous whitespace should be treated as a single space #white space should be retained text = re.sub(' +',' ',text) #Leading and trailing whitespace should be ignored text = text.strip(' \t\n\r') # You probably want this too text = text.lower() return text def process(text): #If they are also the same length, the earlier one in the input sequence should be kept. # Using arrays (can use OrderedDict too, probably easier and nice, although below is clearer for you. original_parts = text.split('|') clean_parts = [clean_input(x) for x in original_parts] original_parts_to_check = [] ignore_idx = [] for idx, ele in enumerate(original_parts): if idx in ignore_idx: continue #The case of alphabetic characters should be ignored if len(ele) &lt; 2: continue #Duplicates must also be filtered -if two passages are considered equal with respect to the comparison rules listed above, only the shortest should be retained. if clean_parts[idx] in clean_parts[:idx]+clean_parts[idx+1:]: indices = [i for i, x in enumerate(clean_parts) if x == clean_parts[idx]] use = indices[0] for i in indices[1:]: if len(original_parts[i]) &lt; len(original_parts[use]): use = i if idx == use: ignore_idx += indices else: ignore_idx += [x for x in indices if x != use] continue original_parts_to_check.append(idx) # Doing the text in text matching here. Depending on size and type of dataset, # Which you should test as it would affect this, you may want this as part # of the function above, or before, etc. If you're only doing 100 bits of # data, then it doesn't matter. Optimize accordingly. text_to_return = [] clean_to_check = [clean_parts[x] for x in original_parts_to_check] for idx in original_parts_to_check: # This bit can be done better, but I have no more time to work on this. if any([(clean_parts[idx] in clean_text) for clean_text in [x for x in clean_to_check if x != clean_parts[idx]]]): continue text_to_return.append(original_parts[idx]) #The retained passages should be output in their original form (identical to the input passage), and in the same order. return '|'.join(text_to_return) assert(process('IBM cognitive computing|IBM "cognitive" computing is a revolution| ibm cognitive computing|\'IBM Cognitive Computing\' is a revolution?') == 'IBM "cognitive" computing is a revolution') print(process('IBM cognitive computing|IBM "cognitive" computing is a revolution| ibm cognitive computing|\'IBM Cognitive Computing\' is a revolution?')) assert(process('IBM cognitive computing|IBM "cognitive" computing is a revolution|the cognitive computing is a revolution') == 'IBM "cognitive" computing is a revolution|the cognitive computing is a revolution') print(process('IBM cognitive computing|IBM "cognitive" computing is a revolution|the cognitive computing is a revolution')) </code></pre> <p>Also, if this helped you, would be great to get some points, so an accept would be nice :) (I see you're new here).</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</p> <pre><code># df_a name value 0 a 1 1 b 2 2 c NaN # df_b name value 0 a 1 1 b NaN 2 c 3 3 d 4 </code></pre> <p>I want to merge these two dataframes and fill in the NaN values of the <code>value</code> column with the existing values in the other column. In other words, I want out:</p> <pre><code># DESIRED RESULT name value 0 a 1 1 b 2 2 c 3 3 d 4 </code></pre> <p>Sure, I can do this with a custom <code>.map</code> or <code>.apply</code>, but I want a solution that uses <code>merge</code> or the like, not writing a custom merge function. How can this be done?</p>
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="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.fillna.html" rel="nofollow"><code>fillna</code></a>:</p> <pre><code>print (df_b.fillna(df_a)) name value 0 a 1.0 1 b 2.0 2 c 3.0 3 d 4.0 </code></pre> <p>Solution with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.update.html" rel="nofollow"><code>update</code></a> is not so common as <code>combine_first</code>:</p> <pre><code>df_b.update(df_a) print (df_b) name value 0 a 1.0 1 b 2.0 2 c 3.0 3 d 4.0 </code></pre>
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.</em></p> <p>Following the steps presented here you'll install:</p> <ul> <li>openCV 3.1.0</li> <li>opencv_contrib 3.1.0</li> <li>numpy</li> <li>scipy</li> <li>scikit</li> <li>matplotlib</li> <li>cython</li> <li>venv</li> </ul> <p>At the end, <strong>it may take up to 20Gb of space</strong> if you haven't already installed any of those packages previously.</p> <p><em>You will need gcc-4.9+ for compiling OpenCV, I tested it with gcc-5.4</em></p> <h1>Install OpenCV dependencies</h1> <pre><code>sudo apt-get build-dep -y opencv </code></pre> <h1>Create and setup a virtualenv</h1> <pre><code>sudo apt-get install python3-venv python3.5 -m venv python35-opencv31 source ~/python35-opencv31/bin/activate pip install matplotlib pip install numpy pip install scipy pip install scikit-learn pip install cython pip install -U scikit-image </code></pre> <h1>Compile OpenCV 3.1.0 and openvc_contrib 3.1.0</h1> <h2>Dependencies</h2> <pre><code>sudo apt-get install build-essential cmake libgtk2.0-dev pkg-config libavcodec-dev libavformat-dev libswscale-dev libtbb2 libtbb-dev libjpeg-dev libpng-dev libtiff-dev libjasper-dev libdc1394-22-dev </code></pre> <h2>Getting repositories</h2> <pre><code>mkdir ~/git cd ~/git git clone https://github.com/opencv/opencv.git cd ./opencv git checkout 3.1.0 cd ~/git git clone https://github.com/Itseez/opencv_contrib.git cd ./opencv_contrib git checkout 3.1.0 </code></pre> <h2>Making sure some libs will be found</h2> <p><strong>ffmpeg libs</strong></p> <pre><code>sudo -i mkdir /usr/include/ffmpeg cd /usr/include/ffmpeg ln -sf /usr/include/x86_64-linux-gnu/libavcodec/*.h ./ ln -sf /usr/include/x86_64-linux-gnu/libavformat/*.h ./ ln -sf /usr/include/x86_64-linux-gnu/libswscale/*.h ./ </code></pre> <p>If, during compilation, occurs any problems when trying to find some ffmpeg libs, uninstall ffmpeg and <a href="https://trac.ffmpeg.org/wiki/CompilationGuide/Ubuntu" rel="nofollow">build it from source</a>.</p> <p><strong>python bindings with opencv_contrib modules</strong></p> <pre><code>echo "\nfind_package(HDF5)\ninclude_directories(\${HDF5_INCLUDE_DIRS})" &gt;&gt; ~/git/opencv/modules/python/common.cmake </code></pre> <h2>Compiling</h2> <pre><code>source ~/python35-opencv31/bin/activate mkdir ~/opencv3.1.0 cd ~/git/opencv/ mkdir release cd ./release export CC=$(which gcc) export CXX=$(which g++) cmake -D CMAKE_BUILD_TYPE=RELEASE \ -D CMAKE_INSTALL_PREFIX=~/opencv3.1.0 \ -D INSTALL_C_EXAMPLES=OFF \ -D INSTALL_PYTHON_EXAMPLES=ON \ -D OPENCV_EXTRA_MODULES_PATH=~/git/opencv_contrib/modules \ -D BUILD_EXAMPLES=ON \ -D CUDA_NVCC_FLAGS="-D_FORCE_INLINES" .. </code></pre> <p>The output should include this:</p> <pre><code>-- Python 2: -- Interpreter: /home/rodrigo/anaconda/bin/python2.7 (ver 2.7.12) -- Libraries: /usr/lib/x86_64-linux-gnu/libpython2.7.so (ver 2.7.12) -- numpy: /home/rodrigo/anaconda/lib/python2.7/site-packages/numpy/core/include (ver 1.10.4) -- packages path: lib/python2.7/site-packages -- -- Python 3: -- Interpreter: /home/rodrigo/python35-opencv/bin/python3 (ver 3.5.2) -- Libraries: /usr/lib/x86_64-linux-gnu/libpython3.5m.so (ver 3.5.2) -- numpy: /home/rodrigo/python35-opencv/lib/python3.5/site-packages/numpy/core/include (ver 1.11.2) -- packages path: lib/python3.5/site-packages -- -- Python (for build): /home/rodrigo/anaconda/bin/python2.7 </code></pre> <p>Now:</p> <pre><code>make </code></pre> <p>If it succeed, then:</p> <pre><code>make install </code></pre> <h1>Add OpenCV libs to your virtualenv</h1> <pre><code>cd ~/python35-opencv31/lib/site-packages ln -s ~/opencv3.1.0/lib/python3.5/site-packages/cv2.cpython-35m-x86_64-linux-gnu.so </code></pre> <h1>Done!</h1> <p>To test if it works as expected:</p> <pre><code>cd ~ source ~/python35-opencv31/bin/activate python import cv2 cv2.__version__ </code></pre> <p>It should import cv2 and show version number 3.1.0.</p>
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 compatibility, the RHEL 6.7 systems do have Perl and Python installed, however they have minimal libraries. So far I haven't had to use anything other than bash, but I'm not against calling a Perl or Python script from my bash script. </p> <p><strong>My Problem</strong><br> I need to retrieve the Serial Numbers and Part numbers from the drives in a Dot Hill Systems AssuredSAN 3824, as well as the Serial numbers from the equipment inside. The only way I have found to get all the information I need is to connect over SSH and run the following three commands dumping the output to a local file:</p> <ul> <li>show controllers</li> <li>show frus</li> <li>show disks</li> </ul> <p><strong>Limitations:</strong></p> <ul> <li>I don't have "sshpass" installed, and would prefer not to install it.</li> <li>The Controller is not capable of storing SSH keys ( no option in custom shell).</li> <li>The Controller also cannot write or transfer local files.</li> <li>The Rack does NOT have access to the Internet.</li> <li>I looked at paramiko, but while Python is installed I do not have pip.</li> <li>I also cannot use CPAN.</li> <li>For what its worth, the output comes back in XML format. (I've already written the code to parse it in bash)</li> </ul> <p>Right now I think my best option would be to have a library for Python or Perl in the folder with my other scripts, and write a script to dump the commands' output to files that I can parse with my bash script. Which language is easier to just provide a library in a file? I'm looking for a library that is as small and simple as possible to use. I just need a way to get the output of those commands to XML files. Right now I am just using ssh 3 times in my script and having to enter the password each time. </p>
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 current remainder</li> <li>Append floor of current remainder to list of coefficients</li> <li>Define new remainder as reciprocal of current remainder minus floor</li> <li>Go to step 2 unless new remainder is 0</li> </ol> <p>This works very well, except for later iterations, where the <code>float</code> precision is producing erroneous coefficients. Once a single coefficient is off, the remaining will automatically be as well.</p> <p>My question is therefore if there is a way to treat irrational numbers, e.g. sqrt(13), like placeholders (for later substitution) or in a more precise manner?</p> <p>My current code is as below:</p> <pre><code>import math def continued_fraction(x, upper_limit=30): a = [] # should in fact iterate until repetitive cycle is found for i in range(upper_limit): a.append(int(x)) x = 1.0/(x - a[-1]) return a if __name__ == '__main__': print continued_fraction(math.sqrt(13)) </code></pre> <p>With the resulting output:</p> <pre><code>[3, 1, 1, 1, 1, 6, 1, 1, 1, 1, 6, 1, 1, 1, 1, 6, 1, 1, 1, 1, 6, 1, 1, 1, 1, 7, 2, 1, 4, 2] </code></pre> <p>And I know for a fact, that the resulting output should be 3, followed by infinite repetitions of the cycle (1, 1, 1, 1, 6), as per <a href="https://projecteuler.net/problem=64" rel="nofollow">Project Euler Problem 64</a> (which I'm trying to solve).</p>
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</em>. Why? <a href="http://stackoverflow.com/questions/588004/is-floating-point-math-broken">Is floating point math broken?</a></p> <p>The following modification to your code provides correct results for this run up until <code>upper_limit=45</code>:</p> <pre><code>import math from decimal import Decimal def continued_fraction(x, upper_limit=30): a = [] # should in fact iterate until repetitive cycle is found for i in range(upper_limit): a.append(int(x)) x = Decimal(1.0)/(x - a[-1]) return a if __name__ == '__main__': print (continued_fraction(Decimal(13).sqrt())) </code></pre>
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 current remainder</li> <li>Append floor of current remainder to list of coefficients</li> <li>Define new remainder as reciprocal of current remainder minus floor</li> <li>Go to step 2 unless new remainder is 0</li> </ol> <p>This works very well, except for later iterations, where the <code>float</code> precision is producing erroneous coefficients. Once a single coefficient is off, the remaining will automatically be as well.</p> <p>My question is therefore if there is a way to treat irrational numbers, e.g. sqrt(13), like placeholders (for later substitution) or in a more precise manner?</p> <p>My current code is as below:</p> <pre><code>import math def continued_fraction(x, upper_limit=30): a = [] # should in fact iterate until repetitive cycle is found for i in range(upper_limit): a.append(int(x)) x = 1.0/(x - a[-1]) return a if __name__ == '__main__': print continued_fraction(math.sqrt(13)) </code></pre> <p>With the resulting output:</p> <pre><code>[3, 1, 1, 1, 1, 6, 1, 1, 1, 1, 6, 1, 1, 1, 1, 6, 1, 1, 1, 1, 6, 1, 1, 1, 1, 7, 2, 1, 4, 2] </code></pre> <p>And I know for a fact, that the resulting output should be 3, followed by infinite repetitions of the cycle (1, 1, 1, 1, 6), as per <a href="https://projecteuler.net/problem=64" rel="nofollow">Project Euler Problem 64</a> (which I'm trying to solve).</p>
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 current remainder</li> <li>Append floor of current remainder to list of coefficients</li> <li>Define new remainder as reciprocal of current remainder minus floor</li> <li>Go to step 2 unless new remainder is 0</li> </ol> <p>This works very well, except for later iterations, where the <code>float</code> precision is producing erroneous coefficients. Once a single coefficient is off, the remaining will automatically be as well.</p> <p>My question is therefore if there is a way to treat irrational numbers, e.g. sqrt(13), like placeholders (for later substitution) or in a more precise manner?</p> <p>My current code is as below:</p> <pre><code>import math def continued_fraction(x, upper_limit=30): a = [] # should in fact iterate until repetitive cycle is found for i in range(upper_limit): a.append(int(x)) x = 1.0/(x - a[-1]) return a if __name__ == '__main__': print continued_fraction(math.sqrt(13)) </code></pre> <p>With the resulting output:</p> <pre><code>[3, 1, 1, 1, 1, 6, 1, 1, 1, 1, 6, 1, 1, 1, 1, 6, 1, 1, 1, 1, 6, 1, 1, 1, 1, 7, 2, 1, 4, 2] </code></pre> <p>And I know for a fact, that the resulting output should be 3, followed by infinite repetitions of the cycle (1, 1, 1, 1, 6), as per <a href="https://projecteuler.net/problem=64" rel="nofollow">Project Euler Problem 64</a> (which I'm trying to solve).</p>
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 of any floating points.</p>
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 don't want to go into right now. My question is: can I do it? If yes, then how?</p>
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 installed.</p> <p>Hence, whichever machine is running your web app, must have Django installed. It presumably also needs to have the database too. It might be quite a hassling process but it's possible.</p> <p>Just like as a developer, you may have multiple users working on 1 project. So, they all need to have that project 'installed' on their devices so they can run it locally.</p>
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 don't want to go into right now. My question is: can I do it? If yes, then how?</p>
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 Django (I'm too lazy to actually write one), and you want to share it with someone who doesn't have Python and Django on his/her computer.</p>
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 images stream an LED image in the 'on' state left to right along the row of images, like the Knight Rider car's front lights. I've tried a few things in the while loop but can't quite see how to achieve it without a lot of lines of code. I think there must be a way to do it in the same way that the digital write is incremented to create the streaming LED on the piface expansion board. Here is my code...</p> <pre><code>class App2: def __init__(self, master): self.signal = False #added to stop thread print('self.signal', self.signal) self.master=master # I added this line to make the exit button work frame = Frame(master) frame.pack() Label(frame, text='Turn LED ON').grid(row=0, column=0) Label(frame, text='Turn LED OFF').grid(row=0, column=1) self.button0 = Button(frame, text='Knight Rider OFF', command=self.convert0) self.button0.grid(row=2, column=0) self.LED0 = Label(frame, image=logo2) #added to create a row of images self.LED1 = Label(frame, image=logo2) self.LED2 = Label(frame, image=logo2) self.LED3 = Label(frame, image=logo2) self.LED4 = Label(frame, image=logo2) self.LED5 = Label(frame, image=logo2) self.LED6 = Label(frame, image=logo2) self.LED7 = Label(frame, image=logo2) self.LED0.grid(row=2, column=1) self.LED1.grid(row=2, column=2) self.LED2.grid(row=2, column=3) self.LED3.grid(row=2, column=4) self.LED4.grid(row=2, column=5) self.LED5.grid(row=2, column=6) self.LED6.grid(row=2, column=7) self.LED7.grid(row=2, column=8) self.button9 = Button(frame, text='Exit', command=self.close_window) self.button9.grid(row=3, column=0) def convert0(self, tog=[0]): tog[0] = not tog[0] if tog[0]: print('Knight Rider ON') self.button0.config(text='Knight Rider ON') t=threading.Thread(target=self.LED) t.start() self.signal = True #added to stop thread print('self.signal', self.signal) print('tog[0]', tog[0]) self.LED0.config(image = logo) else: print('Knight Rider OFF') self.button0.config(text='Knight Rider OFF') self.signal = False #added to stop thread print('self.signal', self.signal) print('tog[0]', tog[0]) self.LED0.config(image = logo2) def LED(self): while self.signal: #added to stop thread a=0 while self.signal: #added to stop thread pfio.digital_write(a,1) #turn on sleep(0.05) pfio.digital_write(a,0) #turn off sleep(0.05) a=a+1 if a==7: break while self.signal: #added to stop thread pfio.digital_write(a,1) #turn on sleep(0.05) pfio.digital_write(a,0) #turn off sleep(0.05) a=a-1 if a==0: break def close_window(self): print('Knight Rider OFF') print('self.signal', self.signal) self.button0.config(text='Knight Rider OFF') self.LED0.config(image = logo2) self.signal = False #added to stop thread print('self.signal', self.signal) sleep(1) print('Close Child window') self.master.destroy() # I added this line to make the exit button work root = Tk() logo2 = PhotoImage(file="/home/pi/Off LED.gif") logo = PhotoImage(file="/home/pi/Red LED.gif") root.wm_title('LED on &amp; off program') app = App(root) root.mainloop() </code></pre>
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 that function cause itself to be called again using <code>after</code>. For example:</p> <pre><code>def animate(): # do something, such as turn an led on or off &lt;some code here to turn one led on or off&gt; # run this again in 100 ms root.after(100, animate) </code></pre> <p>The above will create an infinite loop that runs inside tkinter's mainloop. As long as <code>&lt;some code here... &gt;</code> doesn't take too long, the animation will appear fluid and your UI won't be laggy.</p> <h2>Example</h2> <p>Here's a simple working example of the technique. It uses a simple iterator to cycle through the leds, but you can use any algorithm you want to pick the next led to light up. You could also turn on or off both the on screen and hardware led at the same time, or turn on or off multiple leds, etc. </p> <p>To make this code copy/paste-able, it uses colored frames rather than images, but you can use images if you want. </p> <pre><code>import tkinter as tk # Tkinter for python 2 from itertools import cycle class LEDStrip(tk.Frame): segments = 16 speed = 100 # ms def __init__(self, parent): tk.Frame.__init__(self, parent) leds = [] for i in range(self.segments): led = tk.Frame(self, width=12, height=8, borderwidth=1, relief="raised", background="black") led.pack(side="left", fill="both", expand=True) leds.append(led) self.current_segment = None self.iterator = cycle(leds) def animate(self): # turn off the current segment if self.current_segment: self.current_segment.configure(background="black") # turn on the next segment self.current_segment = next(self.iterator) # self.iterator.next() for python 2 self.current_segment.configure(background="red") # run again in the future self.after(self.speed, self.animate) root = tk.Tk() strip = LEDStrip(root) strip.pack(side="top", fill="x") # start the loop strip.animate() root.mainloop() </code></pre>
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 images stream an LED image in the 'on' state left to right along the row of images, like the Knight Rider car's front lights. I've tried a few things in the while loop but can't quite see how to achieve it without a lot of lines of code. I think there must be a way to do it in the same way that the digital write is incremented to create the streaming LED on the piface expansion board. Here is my code...</p> <pre><code>class App2: def __init__(self, master): self.signal = False #added to stop thread print('self.signal', self.signal) self.master=master # I added this line to make the exit button work frame = Frame(master) frame.pack() Label(frame, text='Turn LED ON').grid(row=0, column=0) Label(frame, text='Turn LED OFF').grid(row=0, column=1) self.button0 = Button(frame, text='Knight Rider OFF', command=self.convert0) self.button0.grid(row=2, column=0) self.LED0 = Label(frame, image=logo2) #added to create a row of images self.LED1 = Label(frame, image=logo2) self.LED2 = Label(frame, image=logo2) self.LED3 = Label(frame, image=logo2) self.LED4 = Label(frame, image=logo2) self.LED5 = Label(frame, image=logo2) self.LED6 = Label(frame, image=logo2) self.LED7 = Label(frame, image=logo2) self.LED0.grid(row=2, column=1) self.LED1.grid(row=2, column=2) self.LED2.grid(row=2, column=3) self.LED3.grid(row=2, column=4) self.LED4.grid(row=2, column=5) self.LED5.grid(row=2, column=6) self.LED6.grid(row=2, column=7) self.LED7.grid(row=2, column=8) self.button9 = Button(frame, text='Exit', command=self.close_window) self.button9.grid(row=3, column=0) def convert0(self, tog=[0]): tog[0] = not tog[0] if tog[0]: print('Knight Rider ON') self.button0.config(text='Knight Rider ON') t=threading.Thread(target=self.LED) t.start() self.signal = True #added to stop thread print('self.signal', self.signal) print('tog[0]', tog[0]) self.LED0.config(image = logo) else: print('Knight Rider OFF') self.button0.config(text='Knight Rider OFF') self.signal = False #added to stop thread print('self.signal', self.signal) print('tog[0]', tog[0]) self.LED0.config(image = logo2) def LED(self): while self.signal: #added to stop thread a=0 while self.signal: #added to stop thread pfio.digital_write(a,1) #turn on sleep(0.05) pfio.digital_write(a,0) #turn off sleep(0.05) a=a+1 if a==7: break while self.signal: #added to stop thread pfio.digital_write(a,1) #turn on sleep(0.05) pfio.digital_write(a,0) #turn off sleep(0.05) a=a-1 if a==0: break def close_window(self): print('Knight Rider OFF') print('self.signal', self.signal) self.button0.config(text='Knight Rider OFF') self.LED0.config(image = logo2) self.signal = False #added to stop thread print('self.signal', self.signal) sleep(1) print('Close Child window') self.master.destroy() # I added this line to make the exit button work root = Tk() logo2 = PhotoImage(file="/home/pi/Off LED.gif") logo = PhotoImage(file="/home/pi/Red LED.gif") root.wm_title('LED on &amp; off program') app = App(root) root.mainloop() </code></pre>
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' ▁▂▃▄▅▆▇' # possible color values L = 8 # number of items B = L*[0] # indices of items A = [0] + list(range(7)) + list(range(7,0,-1)) + 6*[0] # light sequence C = L*[' '] # start blank while 1: B[A[0]]=L # set the most brilliant light for x in range(L): B[x]-= 1 # decrease all lights values B[x] = max(0,B[x]) # not under 0 C[x] = c[B[x]] # get the corresponding 'color' A = shift(A,-1) # shift the array to the right sys.stdout.write(('%s%s%s')%(' ',''.join(C[1:]),'\r')) time.sleep(0.1) </code></pre> <p>Or try that one <a href="https://www.trinket.io/python/79b8a588aa" rel="nofollow">https://www.trinket.io/python/79b8a588aa</a></p>
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 command?</p> <pre><code>script print lldb.frame.FindVariable('a').GetChildMemberWithName('y').GetChildAtIndex(1) </code></pre> <p>I've written this function to help me when I want to print members of struct variables in C:</p> <pre><code># lldb_cmds.py import lldb def get_nested_val_c(vnames,idx=None): """ vnames is a list of strings ['a','b','c',...] that will be evaluated as if you called a.b.c.,... So for [a,b,c] you get: a.b.c If idx is given, it is evaluated as a.b.c[idx] """ try: x=lldb.frame.FindVariable(vnames[0]) for v_ in vnames[1:]: x=x.GetChildMemberWithName(v_) except TypeError: x=lldb.frame.FindVariable(vnames) if idx == None: return x try: x=x.GetChildAtIndex(idx[0]) for i_ in idx[1:]: x=x.GetChildAtIndex(i_,False,True) except TypeError: x=x.GetChildAtIndex(idx) </code></pre> <p>which can then be loaded with</p> <pre><code>command script import lldb_cmds.py </code></pre> <p>and called (like above) with</p> <pre><code>python lldb_cmds.get_nested_val_c[['a','y'],1) </code></pre> <p>But is there a shorter way? Yes I know you can write</p> <pre><code>p a.y[1] </code></pre> <p>but since there don't seem to be any while loops in lldb, how could I print this with a variable index without resorting to such long statements?</p> <p>(And yes I know you can write for this example: <code>p *(int(*)[2])a.y</code> but I am asking in general.)</p>
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").GetValueForExpressionPath("y[0]") </code></pre> <p>If what you are trying to do is run command line commands in Python scripts, there are two ways to do this:</p> <pre><code>lldb.debugger.HandleCommand("command") </code></pre> <p>That just runs the command, and prints the results to lldb's stdout, or:</p> <pre><code>ret_val = lldb.SBCommandReturnObject() lldb.debugger.GetCommandInterpreter().HandleCommand("command", ret_val) </code></pre> <p>That will run the command, and return the result of the command (which is what in the lldb driver gets printed as the command runs) into the <code>ret_val</code> object. That's convenient if you want to inspect the results of the command. The ReturnObject also tells you whether the command was successful or not, and holds the error if it wasn't.</p> <p>If you are trying to print statically allocated arrays - as in your example - you shouldn't need to do the cast you show above, you should just be able to do:</p> <p>(lldb) p a.y</p> <p>and that should print all the elements. If you are dealing with dynamically sized arrays (e.g. an int * that you point at a malloc'ed array) the lldb in Xcode 8.0 has a new command <code>parray</code> which would let you say:</p> <p>(lldb) parray 10 a.y</p> <p>to print 10 elements of the array of ints pointed to by y.</p>
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, 1, 1, 3] #The output I want is sortlst = ['Hi','Ho','Ho','Hi','Hi','Hi','Ho','!'] </code></pre> <p>I have tried searching for methods to resolve this, but could not find any. List comprehensions and the like has been able to call elements in sent, but not by the actual integers of pos, rather the position.</p> <pre><code>for i in pos: T.append(sent[i]) recreate = " ".join(T) print (recreate) </code></pre> <p>Running this segment will output:</p> <pre><code>Ho Ho Ho Ho Ho Ho Ho Hi </code></pre> <p>Any help would be greatly appreciated!</p>
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> here) that would be matched in order with numbers. 1 to 'Hi', 2 to 'Ho' and 3 to '!', etc. </p>
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, 1, 1, 3] #The output I want is sortlst = ['Hi','Ho','Ho','Hi','Hi','Hi','Ho','!'] </code></pre> <p>I have tried searching for methods to resolve this, but could not find any. List comprehensions and the like has been able to call elements in sent, but not by the actual integers of pos, rather the position.</p> <pre><code>for i in pos: T.append(sent[i]) recreate = " ".join(T) print (recreate) </code></pre> <p>Running this segment will output:</p> <pre><code>Ho Ho Ho Ho Ho Ho Ho Hi </code></pre> <p>Any help would be greatly appreciated!</p>
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>after</em> 'Ho', even though it is <em>before</em> in lexicographical order. I will use lexicographical order unless you propose an alternative.</li> </ul> <p>Therefore, <code>post = [1,2,3]</code> is telling me:</p> <blockquote> <p>Give me an array with the first, second, and third unique sorted values of <code>sent</code>.</p> </blockquote> <p>With this definition in mind:</p> <pre><code>&gt;&gt;&gt; sent = ['Ho','Hi','Hi','Ho','Hi','Ho','!','Hi'] &gt;&gt;&gt; pos = [1, 2, 2, 1, 1, 1, 3] &gt;&gt;&gt; elements = sorted(set(sent)) &gt;&gt;&gt; elements ['!', 'Hi', 'Ho'] &gt;&gt;&gt; [elements[i - 1] for i in pos] ['!', 'Hi', 'Hi', '!', '!', '!', 'Ho'] </code></pre>
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.component.spec.ts | │ ├── app.component.ts | │ ├── app.route.ts │ │ ├── component1.component.ts | │ ├── component2.component.ts │ │ └── main.ts | ├── system.config.json │ ├── tsconfig.json │ └── typings.json ├── db.sqlite3 ├── LICENSE ├── manage.py </code></pre> <p>and I'm trying to load angular2 files into my django template <code>index.html</code>, so the file looks like this:</p> <pre><code>{% load static from staticfiles %} &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;base href=/ &gt; &lt;title&gt;Hello! &lt;/title&gt; &lt;meta charset=UTF-8&gt; &lt;meta name=viewport content="width=device-width,initial-scale=1"&gt; &lt;script src="https://unpkg.com/core-js/client/shim.min.js"&gt;&lt;/script&gt; &lt;script src="https://unpkg.com/[email protected]?main=browser"&gt;&lt;/script&gt; &lt;script src="https://unpkg.com/[email protected]"&gt;&lt;/script&gt; &lt;script src="https://unpkg.com/[email protected]/dist/system.src.js"&gt;&lt;/script&gt; &lt;script&gt; System.import('{%static '/app/main' %}').catch(function(err){ console.error(err); }); &lt;/script&gt; &lt;link href="{%static '/css/stylesheet.css' %}"&gt; &lt;link href="{%static '/css/bootstrap.min.css' %}"&gt; &lt;/head&gt; &lt;body&gt; &lt;img src="{%static '/assets/logo.png' %}"&gt;&lt;/img&gt; &lt;as-my-app&gt;Loading...&lt;/as-my-app&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>My problem is that all the static files load just fine, but my browser constantly shows error while loading <code>/static/app/main</code> saying it wasn't found. How come Django can't find it if it finds other static files?</p>
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 meant in the sense of "having similar regex", "including similar characters", or some sort of pattern.</p> <p>Example of key-values: </p> <pre><code>ADSF33344 : G1112 AWDX45603 : G1112 D99991111222 : X3334 E98881188393 : X3334 A30-00005-01 : B0007 B45-00234-07A : B0007 F50-01120-06 : B0007 </code></pre> <p>The final goal is to feed an algorithm with a list of new references (never seen before) and the algorithm would return a suggested family for each reference, ideally together with a percentage of confidence, based on what it learned from the dataset.<br> The suggested family can only come from the existing families found in the dataset. No need to "invent" new family name.</p> <p>I'm not familiar with machine learning so I don't really know where to start. I saw some solutions through Sklearn or TextBlob and I understand that I'm looking for a classifier algorithm but every tutorial is oriented toward analysis of large texts.<br> Somehow, I don't find how to handle my problem, although it seems to be a "simpler" problem than analysing newspaper articles in natural language... </p> <p>Could you indicate me sources or tutorials that could help me?</p>
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 features and the classifier decides how important each feature is, and how to interpret their combinations.</p> <p>By way of a tutorial you can look at <a href="http://www.nltk.org/book/ch06.html" rel="nofollow">chapter 6</a> of the NLTK book. The example task, the classification of names into male and female, is structurally very close to yours: Based on the form of short strings (names), classify them into categories (genders). </p> <p>You will translate each part number into a dictionary of features. Since you don't show us the real data, nobody give you concrete suggestions, but you should definitely make general-purpose features as in the book, and in addition you should make a feature out of every clue, strong or weak, that you are aware of. If supplier IDS differ in length, make a length feature. If the presence (or number or position) of hyphens is a clue, make that into a feature. If some suppliers' parts use a lot of zeros, ditto. Then make additional features for anything else, e.g. "first three letters" that <em>might</em> be useful. Once you have a working system, experiment with different feature sets and different classifier engines and algorithms, until you get acceptable performance. </p> <p>To get good results with new data, don't forget to split up your training data into training, testing and evaluation subsets. You could use all this with any classifier, but the NLTK's Naive Bayes classifier is pretty quick to train so you could start with that. (Note that the features can be discrete values, e.g. <code>first_letter</code> can be the actual letter; you don't need to stick to boolean features.)</p>
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 separate components for year, month, day etc. This is easy to manipulate directly to advance to the next month, etc.</p> <p>If you don't mind using an extension, check out <a href="https://dateutil.readthedocs.io/en/stable/" rel="nofollow"><code>dateutil</code></a>. The list of features starts with:</p> <blockquote> <ul> <li>Computing of relative deltas (next month, next year, next monday, last week of month, etc); </li> </ul> </blockquote> <p>The documentation for <a href="https://dateutil.readthedocs.io/en/stable/examples.html#relativedelta-examples" rel="nofollow"><code>dateutil.relativedelta</code></a> shows how to advance to various points.</p>
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.monthrange(year, month)[1]) &gt;&gt;&gt; endOfMonthDate datetime.date(2012, 3, 31) &gt;&gt;&gt; </code></pre> <p>You might find other helpful functions here: <a href="https://docs.python.org/2/library/calendar.html" rel="nofollow">https://docs.python.org/2/library/calendar.html</a> and here: <a href="https://docs.python.org/2/library/datetime.html" rel="nofollow">https://docs.python.org/2/library/datetime.html</a></p>
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 Clegane 47226 Y PPOI Khal Drogo 133594 N PPOI Hodor 162581 Y PPOF Cersei Lannister 163985 N PPOI Tyrion Lannister 109253 N PPOF Jorah Mormont 61078 Y None Jon Snow 123222 N None </code></pre> <p>How can I take this file data and extract each data type (name, salary, life insurance, health insurance) into four separate lists?<br> Currently, my code is creating a multidimensional list by employee, but I ultimately want four separate lists. My current code is below:</p> <pre><code>def fileread(text): in_file = open(text, "r") permlist = [] x = 1 templist = [] for line in in_file: line = line.strip() templist.append(line) if x == 4: permlist.append(templist) templist = [] x = 1 else: x+=1 return (permlist) def main (): EmpData = fileread("EmployeeData.txt") index = 0 print (EmpData[index]) </code></pre>
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 like this. Its easy to get confused. You might be better off storing this data into a database.</p>
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 Clegane 47226 Y PPOI Khal Drogo 133594 N PPOI Hodor 162581 Y PPOF Cersei Lannister 163985 N PPOI Tyrion Lannister 109253 N PPOF Jorah Mormont 61078 Y None Jon Snow 123222 N None </code></pre> <p>How can I take this file data and extract each data type (name, salary, life insurance, health insurance) into four separate lists?<br> Currently, my code is creating a multidimensional list by employee, but I ultimately want four separate lists. My current code is below:</p> <pre><code>def fileread(text): in_file = open(text, "r") permlist = [] x = 1 templist = [] for line in in_file: line = line.strip() templist.append(line) if x == 4: permlist.append(templist) templist = [] x = 1 else: x+=1 return (permlist) def main (): EmpData = fileread("EmployeeData.txt") index = 0 print (EmpData[index]) </code></pre>
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)] health_ins_list = [lines[i].rstrip() for i in range(3,len(lines),4)] </code></pre>
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 Clegane 47226 Y PPOI Khal Drogo 133594 N PPOI Hodor 162581 Y PPOF Cersei Lannister 163985 N PPOI Tyrion Lannister 109253 N PPOF Jorah Mormont 61078 Y None Jon Snow 123222 N None </code></pre> <p>How can I take this file data and extract each data type (name, salary, life insurance, health insurance) into four separate lists?<br> Currently, my code is creating a multidimensional list by employee, but I ultimately want four separate lists. My current code is below:</p> <pre><code>def fileread(text): in_file = open(text, "r") permlist = [] x = 1 templist = [] for line in in_file: line = line.strip() templist.append(line) if x == 4: permlist.append(templist) templist = [] x = 1 else: x+=1 return (permlist) def main (): EmpData = fileread("EmployeeData.txt") index = 0 print (EmpData[index]) </code></pre>
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 infile: while counter&gt;0: lines_gen = islice(infile, 4) counter = 0 hasLines = False; for line in lines_gen: record[headers[counter]] = line.strip() counter += 1 EmpData.append(record) index = 0 print (EmpData[index]) </code></pre> <p>As someone has complained about scholastic dishonesty violations in this post, I would make to clear that is a simplified version of a production code snippet that was inspired by this SO answer: <a href="http://stackoverflow.com/questions/5832856/how-to-read-file-n-lines-at-a-time-in-python">How to read file N lines at a time in Python?</a>. </p>
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 char in i: if char == '!': del char ''.join(i) ' '.join(string) return string </code></pre> <p>For instance, I create this code to take a string as its parameter, remove any exclamation in it, the return it changed. The input and output should look like this:</p> <pre><code>&gt;&gt;&gt;remove_exclamation('This is an example!') 'This is an example' </code></pre> <p>But instead I get this:</p> <pre><code>&gt;&gt;&gt;remove_exclamation('This is an example!') 'This is an example!' </code></pre> <p>The function is not removing the exclamation in the output, and is not doing what I intended for it to day.</p> <p>How can I keep avoiding this when I make for loops, nested for loops etc?</p>
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 not using the result:</p> <pre><code>string.split(' ') </code></pre> <p>This also:</p> <pre><code>i.split() </code></pre> <p>This deletes the variable named <code>char</code>. It does not affect the char itself:</p> <pre><code> del char </code></pre> <p>This creates a new string which you do not use:</p> <pre><code> ''.join(i) </code></pre> <p>This also:</p> <pre><code> ' '.join(string) </code></pre> <p>All in all, almost every line of the code is wrong.</p> <p>You probably wanted to do this:</p> <pre><code>def remove_exclamation(string): words = string.split(' ') rtn_words = [] for word in words: word_without_exclamation = ''.join(ch for ch in word if ch != '!') rtn_words.append(word_without_exclamation) return ' '.join(rtn_words) </code></pre> <p>But in the end, this does the same thing:</p> <pre><code>def remove_exclamation(string): return string.replace('!', '') </code></pre>
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 char in i: if char == '!': del char ''.join(i) ' '.join(string) return string </code></pre> <p>For instance, I create this code to take a string as its parameter, remove any exclamation in it, the return it changed. The input and output should look like this:</p> <pre><code>&gt;&gt;&gt;remove_exclamation('This is an example!') 'This is an example' </code></pre> <p>But instead I get this:</p> <pre><code>&gt;&gt;&gt;remove_exclamation('This is an example!') 'This is an example!' </code></pre> <p>The function is not removing the exclamation in the output, and is not doing what I intended for it to day.</p> <p>How can I keep avoiding this when I make for loops, nested for loops etc?</p>
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 = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ " test_string = "This is an example!" test_string = ''.join(list(filter(lambda x: x in characters, test_string))) print(test_string) </code></pre> <p>This outputs:</p> <blockquote> <p>This is an example</p> </blockquote> <p>Note, this is the Python 3 version.</p> <p>Python 2, you do not need the <code>''.join(list())</code></p> <p>Doing it this way would allow you to define any character that you do not want present in your string, and it will remove them. </p> <p>You can even do the reverse:</p> <pre><code>ignore_characters= "!" test_string = "This is an example!" test_string = ''.join(list(filter(lambda x: x not in ignore_characters, test_string))) print(test_string) </code></pre>
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 char in i: if char == '!': del char ''.join(i) ' '.join(string) return string </code></pre> <p>For instance, I create this code to take a string as its parameter, remove any exclamation in it, the return it changed. The input and output should look like this:</p> <pre><code>&gt;&gt;&gt;remove_exclamation('This is an example!') 'This is an example' </code></pre> <p>But instead I get this:</p> <pre><code>&gt;&gt;&gt;remove_exclamation('This is an example!') 'This is an example!' </code></pre> <p>The function is not removing the exclamation in the output, and is not doing what I intended for it to day.</p> <p>How can I keep avoiding this when I make for loops, nested for loops etc?</p>
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>Your indention</li> <li>The fact that your just returning the string thats passed into the function</li> <li>Your use of the <code>del</code> statement</li> <li>etc.</li> </ul> <p>Instead, create a new string by iterating through the old one and filtering out the character(s) you do not want, via list comprehension and <code>''.join()</code>.</p> <pre><code>def remove_exclamation(string): return ''.join([char for char in string if char != '!']) </code></pre> <p>But as @Moses has already said in the comments, why not just use <code>str.replace()</code>?:</p> <p><code>string = string.replace('!', '')</code></p>
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 char in i: if char == '!': del char ''.join(i) ' '.join(string) return string </code></pre> <p>For instance, I create this code to take a string as its parameter, remove any exclamation in it, the return it changed. The input and output should look like this:</p> <pre><code>&gt;&gt;&gt;remove_exclamation('This is an example!') 'This is an example' </code></pre> <p>But instead I get this:</p> <pre><code>&gt;&gt;&gt;remove_exclamation('This is an example!') 'This is an example!' </code></pre> <p>The function is not removing the exclamation in the output, and is not doing what I intended for it to day.</p> <p>How can I keep avoiding this when I make for loops, nested for loops etc?</p>
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 now you are splitting a 1-char string and again not assigning it. i.split() </code></pre> <p>And <code>string</code> is still your input param, which I assume is of <code>type str</code>. And immutable.</p> <p>On top of which, if you were import/using the <code>string</code> <strong>module</strong>, you would be shadowing it</p> <p>A big part of your confusion is knowing when the methods mutate the objects and when they return a new object. In the case of strings, they never mutate, you need to assign the results to a new variable.</p> <p>On a list however, and the <code>join()</code> somewhere makes me think you want to use a list, then methods generally change the object in place.</p> <p>Anyway, on to your question:</p> <pre><code>def remove_exclamation(inputstring, to_remove="!"): return "".join([c for c in inputstring if c != to_remove]) print (remove_exclamation('This is an example!')) </code></pre> <p>output:<br> <code>This is an example</code></p>
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 2345 4343 2 76 33 33 3 4 5 5 </code></pre> <p>And say I have 3 values of interest:</p> <pre><code>&gt;&gt;&gt; vals=['123','76'] </code></pre> <p>I am interested in determining which values in my dataframe start with any of the values in my list. There are 3 cases in my example: (0,A) starts with 123; (1,A) starts with 123; and (2,A) starts with 76. </p> <p>Is there a way I can do this without looping through each of my values?</p> <p>If I were interested in matching values exactly I could just do:</p> <pre><code>&gt;&gt;&gt; d.isin(vals) A B C 0 False False False 1 False False False 2 True False False 3 False False False &gt;&gt;&gt; </code></pre> <p>And if I was interested in whether the values start with 1 particular value I could do:</p> <pre><code>&gt;&gt;&gt; d.applymap(lambda x:x.startswith('123')) A B C 0 True False False 1 True False False 2 False False False 3 False False False &gt;&gt;&gt; </code></pre> <p>But how can I combine these two to find any value that starts with any value in my list?</p>
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 False False 2 True False False 3 False False False </code></pre> <p>The resulting regex pattern:</p> <pre><code>In [10]: '|'.join(v) Out[10]: '^123|^76' </code></pre>
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 2345 4343 2 76 33 33 3 4 5 5 </code></pre> <p>And say I have 3 values of interest:</p> <pre><code>&gt;&gt;&gt; vals=['123','76'] </code></pre> <p>I am interested in determining which values in my dataframe start with any of the values in my list. There are 3 cases in my example: (0,A) starts with 123; (1,A) starts with 123; and (2,A) starts with 76. </p> <p>Is there a way I can do this without looping through each of my values?</p> <p>If I were interested in matching values exactly I could just do:</p> <pre><code>&gt;&gt;&gt; d.isin(vals) A B C 0 False False False 1 False False False 2 True False False 3 False False False &gt;&gt;&gt; </code></pre> <p>And if I was interested in whether the values start with 1 particular value I could do:</p> <pre><code>&gt;&gt;&gt; d.applymap(lambda x:x.startswith('123')) A B C 0 True False False 1 True False False 2 False False False 3 False False False &gt;&gt;&gt; </code></pre> <p>But how can I combine these two to find any value that starts with any value in my list?</p>
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 2345 4343 2 76 33 33 3 4 5 5 </code></pre> <p>And say I have 3 values of interest:</p> <pre><code>&gt;&gt;&gt; vals=['123','76'] </code></pre> <p>I am interested in determining which values in my dataframe start with any of the values in my list. There are 3 cases in my example: (0,A) starts with 123; (1,A) starts with 123; and (2,A) starts with 76. </p> <p>Is there a way I can do this without looping through each of my values?</p> <p>If I were interested in matching values exactly I could just do:</p> <pre><code>&gt;&gt;&gt; d.isin(vals) A B C 0 False False False 1 False False False 2 True False False 3 False False False &gt;&gt;&gt; </code></pre> <p>And if I was interested in whether the values start with 1 particular value I could do:</p> <pre><code>&gt;&gt;&gt; d.applymap(lambda x:x.startswith('123')) A B C 0 True False False 1 True False False 2 False False False 3 False False False &gt;&gt;&gt; </code></pre> <p>But how can I combine these two to find any value that starts with any value in my list?</p>
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 2 True False False 3 False False False </code></pre>
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 2345 4343 2 76 33 33 3 4 5 5 </code></pre> <p>And say I have 3 values of interest:</p> <pre><code>&gt;&gt;&gt; vals=['123','76'] </code></pre> <p>I am interested in determining which values in my dataframe start with any of the values in my list. There are 3 cases in my example: (0,A) starts with 123; (1,A) starts with 123; and (2,A) starts with 76. </p> <p>Is there a way I can do this without looping through each of my values?</p> <p>If I were interested in matching values exactly I could just do:</p> <pre><code>&gt;&gt;&gt; d.isin(vals) A B C 0 False False False 1 False False False 2 True False False 3 False False False &gt;&gt;&gt; </code></pre> <p>And if I was interested in whether the values start with 1 particular value I could do:</p> <pre><code>&gt;&gt;&gt; d.applymap(lambda x:x.startswith('123')) A B C 0 True False False 1 True False False 2 False False False 3 False False False &gt;&gt;&gt; </code></pre> <p>But how can I combine these two to find any value that starts with any value in my list?</p>
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.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow"><code>concat</code></a> output. But need check more items in list <code>vals</code>, so use another list comprehension with <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.logical_or.html" rel="nofollow"><code>numpy.logical_or</code></a> with <code>reduce</code> which works with <code>numpy array</code> - convert output of <code>concat</code> and last create <code>Dataframe</code> with same column and index as original and data are output of <code>numpy.logical_or</code>:</p> <pre><code>print ([pd.concat([d[col].str.startswith(i) for col in d], axis=1).values for i in vals]) [array([[ True, False, False], [ True, False, False], [False, False, False], [False, False, False]], dtype=bool), array([[False, False, False], [False, False, False], [ True, False, False], [False, False, False]], dtype=bool)] print (np.logical_or.reduce( [pd.concat([d[col].str.startswith(i) for col in d], axis=1).values for i in vals])) [[ True False False] [ True False False] [ True False False] [False False False]] print(pd.DataFrame(np.logical_or.reduce( [pd.concat([d[col].strstartswith(i) for col in d], axis=1).values for i in vals]), index=d.index, columns=d.columns)) A B C 0 True False False 1 True False False 2 True False False 3 False False False </code></pre> <p><strong>Timings</strong>:</p> <pre><code>#[40000 rows x 3 columns] d = pd.concat([d]*10000).reset_index(drop=True) In [77]: %timeit (d.applymap(lambda x: any([x.startswith(v) for v in vals]))) 1 loop, best of 3: 228 ms per loop In [78]: %timeit (d.apply(lambda x: x.str.contains('|'.join(['^' + x for x in vals])))) 10 loops, best of 3: 147 ms per loop In [79]: %timeit (d.astype(str).stack().str.match('^(?:{})'.format('|'.join(vals))).unstack()) 10 loops, best of 3: 172 ms per loop In [80]: %timeit (pd.DataFrame(np.logical_or.reduce([pd.concat([d[col].str.startswith(i) for col in d], axis=1).values for i in vals]), index=d.index, columns=d.columns)) 10 loops, best of 3: 116 ms per loop </code></pre>
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>['', '', '', '', '', '', '', 'AB123-12a', ''] </code></pre> <p>What are all these extra empty spaces? How do I remove them?</p>
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>['', '', '', '', '', '', '', 'AB123-12a', ''] </code></pre> <p>What are all these extra empty spaces? How do I remove them?</p>
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 are trying to match. Are all those parts of your match really optional?</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>['', '', '', '', '', '', '', 'AB123-12a', ''] </code></pre> <p>What are all these extra empty spaces? How do I remove them?</p>
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 one and <em>maximum</em> of 9 and 5 for each pattern yields correct results:</p> <pre><code>&gt;&gt;&gt; test='text-AB123-12a' &gt;&gt;&gt; import re &gt;&gt;&gt; re.findall("[A-Z]{1,9}\d{1,5}(?:-\d{0,2}a)?", test) ['AB123-12a'] </code></pre> <p>Without further detail about <em>what exactly</em> the strings you are matching look like, I can't give a better answer.</p>
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>['', '', '', '', '', '', '', 'AB123-12a', ''] </code></pre> <p>What are all these extra empty spaces? How do I remove them?</p>
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("[A-Z]{1,9}\d{1,5}(?:-\d{0,2}a)?", test) ['AB123-12a', 'AB123'] </code></pre>
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>['', '', '', '', '', '', '', 'AB123-12a', ''] </code></pre> <p>What are all these extra empty spaces? How do I remove them?</p>
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,5}(?:-\d\d?)?(?=a)', test) </code></pre> <p>In this way the match can start with a letter or with a digit.</p> <p>I assume that when there's an hyphen, it is followed by at least one digit (otherwise what is the reason of this hyphen?). In other words, I assume that <code>-a</code> isn't possible at the end. (correct me if I'm wrong.)</p> <p>To exclude the "a" from the match result, I putted it in a lookahead.</p>
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 = initialPage.find('div', {'id': 'unitType'}).h2.contents print('Device Info: ', deviceInfo) for i in deviceInfo: print i </code></pre> <p>Which outputs:</p> <pre><code>('Device Info: ', [u'BB100 ', &lt;br&gt;v1.4.3&lt;/br&gt;]) BB100 &lt;br&gt;v1.4.3&lt;/br&gt; </code></pre> <p>How do I remove the <code>&lt;h2&gt;</code>,<code>&lt;/h2&gt;</code>,<code>&lt;br&gt;</code> and <code>&lt;/br&gt;</code> html tags, using BeautifulSoup rather than regex? I've tried <code>i.decompose()</code> and <code>i.strip()</code> but neither has worked. It would throw <code>'NoneType' object is not callable</code>.</p>
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 list.</p> <pre><code>for n, i in enumerate(deviceInfo): if i.name == 'br': i = i.contents deviceInfo[n] = i </code></pre>
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 = initialPage.find('div', {'id': 'unitType'}).h2.contents print('Device Info: ', deviceInfo) for i in deviceInfo: print i </code></pre> <p>Which outputs:</p> <pre><code>('Device Info: ', [u'BB100 ', &lt;br&gt;v1.4.3&lt;/br&gt;]) BB100 &lt;br&gt;v1.4.3&lt;/br&gt; </code></pre> <p>How do I remove the <code>&lt;h2&gt;</code>,<code>&lt;/h2&gt;</code>,<code>&lt;br&gt;</code> and <code>&lt;/br&gt;</code> html tags, using BeautifulSoup rather than regex? I've tried <code>i.decompose()</code> and <code>i.strip()</code> but neither has worked. It would throw <code>'NoneType' object is not callable</code>.</p>
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.find(id="unitType").h2 ...: h2.find("br").extract() ...: print(h2) ...: &lt;h2&gt;BB10&lt;/h2&gt; </code></pre> <p>Or to replace the tag with just the text using <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#replace-with" rel="nofollow">replace-with</a>:</p> <pre><code>In [16]: from bs4 import BeautifulSoup ...: ...: h = """&lt;div id='unitType'&gt;&lt;h2&lt;br&gt;v1.4.3 BB10&lt;/h2&gt;&lt;/d ...: iv&gt;""" ...: ...: soup = BeautifulSoup(h, "html.parser") ...: ...: h2 = soup.find(id="unitType").h2 ...: ...: br = h2.find("br") ...: br.replace_with(br.text) ...: print(h2) ...: &lt;h2&gt;v1.4.3 BB10&lt;/h2&gt; </code></pre> <p>To remove the <em>h2</em> and keep the text:</p> <pre><code>In [37]: h = """&lt;div id='unitType'&gt;&lt;h2&gt;&lt;br&gt;v1.4.3&lt;/h2&gt;&lt;/d ...: ...: iv&gt;""" ...: ...: soup = BeautifulSoup(h, "html.parser") ...: ...: unit = soup.find(id="unitType") ...: ...: h2 = unit.find("h2") ...: h2.replace_with(h2.text) ...: print(unit) ...: &lt;div id="unitType"&gt;v1.4.3 BB10&lt;/div&gt; </code></pre> <p>If you just want <code>"v1.4.3"</code> and <code>"BB10"</code>, there are many ways to hey them:</p> <pre><code>In [60]: h = """&lt;div id="unitType"&gt; ...: &lt;h2&gt;BB100 &lt;br&gt;v1.4.3&lt;/h2&gt; ...: &lt;/div&gt;""" ...: ...: soup = BeautifulSoup(h, "html.parser") ...: ...: h2 = soup.find(id="unitType").h2 # just find all strings ...: a,b = h2.find_all(text=True) ...: print(a, b) # get the br ...: br = h2.find("br") # get br text and just the h2 text ignoring any text from children ...: a, b = h2.find(text=True, recursive=False), br.text ...: print(a, b) ...: BB100 v1.4.3 BB100 v1.4.3 </code></pre> <p>Why you end up with text ins</p>
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 = api.search( q = 'terrorist attack') print(articles['response'],['docs'],['web_url']) </code></pre>
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>.</p>
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/stdtypes.html" rel="nofollow">https://docs.python.org/2/library/stdtypes.html</a></p> <p>If I use <code>isinstance(X, type)</code> or <code>type(X) == type</code>, it also catches all classes too, but I only want to detect type functions (or any names that's assigned to one of them (i.e. <code>my_int = int</code>).</p> <p>The only idea that comes to my mind is checking if <code>X.__name__</code> is in <code>__builtins__</code> but I'm not sure if that's a clean nor correct solution.</p>
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_builtin(tested_object): return tested_object.__class__.__module__ == '__builtin__' </code></pre>
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', 'string2', 'string3', ... 'string1000'] with open('some_text_file') as file: for line in file: if &lt;any matchstr&gt; in line: print( 'Found a match!', matchstr[x]) </code></pre>
-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 for line in lines: matches.append([match, line] for match in matchstr if match in line) </code></pre> <p>Note that this will create generators inside generators so to loop through it use:</p> <pre><code>for i in matches: for j in i: #do stuff </code></pre>
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't defined.</p> <p>How can I append to the original list by using values stored in another file?</p>
-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 calculations?</p>
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 write your own function to string them together differently.</p> <p>I'm not sure what you're asking makes sense, though. If you apply the POS tagger to lemmatized text, the statistical model probably won't perform very well. The inflectional suffixes are important features.</p>
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 axis) and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.all.html" rel="nofollow">all</a> (Return whether all elements are True over requested axis) is similar, but the difference in behavior doesn't seem to make sense to me.</p> <p>What gives?</p>
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>Note, <code>NaN</code> is falsey:</p> <pre><code>&gt;&gt;&gt; bool(float('nan')) True </code></pre> <p>Also note: this is consistent with the built-in <code>any</code> and <code>all</code>. Empty iterables return <code>True</code> for <code>all</code> and <code>False</code> for <code>any</code>. <a href="http://stackoverflow.com/questions/3275058/reason-for-all-and-any-result-on-empty-lists">Here is a relevant question on that topic.</a></p> <p>Interestingly, the default behavior appears to be inconsistent with the documentation:</p> <blockquote> <p>skipna : boolean, default True Exclude NA/null values. If an entire row/column is NA, the result will be NA</p> </blockquote> <p>But observe:</p> <pre><code>&gt;&gt;&gt; pd.Series([float('nan')]).any(skipna=None) False &gt;&gt;&gt; pd.Series([float('nan')]).any(skipna=True) False &gt;&gt;&gt; pd.Series([float('nan')]).any(skipna=False) True &gt;&gt;&gt; </code></pre>
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 column in df[[0, 1]]: groups[grp] = df[column][df['group']==grp].values args = groups.values() g = scipy.stats.kruskal(*args) res.append(g) print (res) </code></pre> <p>I get </p> <pre><code>[KruskalResult(statistic=8.0000000000000036, pvalue=0.018315638888734137)] </code></pre> <p>But i want</p> <pre><code>[KruskalResult(statistic=0.80000000000000071, pvalue=0.67032004603563911)] [KruskalResult(statistic=8.0000000000000036, pvalue=0.018315638888734137)] </code></pre> <p>Where is my mistake?</p> <p>for a single column i do as below</p> <pre><code>import pandas as pd import scipy df = pd.DataFrame({'numbers':range(9), 'group':['a', 'b', 'c']*3}) groups = {} for grp in df['group'].unique(): groups[grp] = df['numbers'][df['group']==grp].values print(groups) args = groups.values() scipy.stats.kruskal(*args) </code></pre>
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 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>
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 column in df[[0, 1]]: groups[grp] = df[column][df['group']==grp].values args = groups.values() g = scipy.stats.kruskal(*args) res.append(g) print (res) </code></pre> <p>I get </p> <pre><code>[KruskalResult(statistic=8.0000000000000036, pvalue=0.018315638888734137)] </code></pre> <p>But i want</p> <pre><code>[KruskalResult(statistic=0.80000000000000071, pvalue=0.67032004603563911)] [KruskalResult(statistic=8.0000000000000036, pvalue=0.018315638888734137)] </code></pre> <p>Where is my mistake?</p> <p>for a single column i do as below</p> <pre><code>import pandas as pd import scipy df = pd.DataFrame({'numbers':range(9), 'group':['a', 'b', 'c']*3}) groups = {} for grp in df['group'].unique(): groups[grp] = df['numbers'][df['group']==grp].values print(groups) args = groups.values() scipy.stats.kruskal(*args) </code></pre>
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>[KruskalResult(statistic=8.0000000000000036, pvalue=0.018315638888734137)] </code></pre> <p>The problem was in indent ((( </p>
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 on the definitions of arrow notation, shown below:</p> <pre><code>def arrow2(a,b): c=1 for i in np.arange(b): c=a**c return c def arrow3(a,b): c=1 for i in np.arange(b): c=arrow2(a,c) return c </code></pre> <p>Although "long" integers (limitless) and numpy arrays (limitless) were used, naturally the code takes up far too much memory while running and will take a very long time to process. Is there a solution to this? (or does someone already know the answer?) Thank you!</p>
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</code>) on a computer, i.e. in binary. This will require <code>k</code> bits, where <code>2^k ~ N</code>. That means <code>k</code> is itself extremely large (just compare <code>2^k</code> with the tower at the end), much too large to be stored on all the hard drives in the world.</p>
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 on the definitions of arrow notation, shown below:</p> <pre><code>def arrow2(a,b): c=1 for i in np.arange(b): c=a**c return c def arrow3(a,b): c=1 for i in np.arange(b): c=arrow2(a,c) return c </code></pre> <p>Although "long" integers (limitless) and numpy arrays (limitless) were used, naturally the code takes up far too much memory while running and will take a very long time to process. Is there a solution to this? (or does someone already know the answer?) Thank you!</p>
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 </code></pre> <p>So this reduces to studying the growth of <code>3 ↑↑ i</code>. Let's see how that grows:</p> <pre><code>3 ↑↑ 0 = 1 3 ↑↑ 1 = 3**(3↑↑0) = 3**1 = 3 3 ↑↑ 2 = 3**(3↑↑1) = 3**3 = 27 3 ↑↑ 3 = 3**(3↑↑2) = 3**27 = 7625597484987 3 ↑↑ 4 = 3**(3↑↑3) = 3**7625597484987 = ...? </code></pre> <p>We're already beyond the limit of what's feasible to compute on most personal computers. </p> <pre><code>&gt;&gt;&gt; import math &gt;&gt;&gt; math.log10(3) * 3**27 3638334640024.0996 </code></pre> <p>That's the base 10 logarithm of <code>3 ↑↑ 4</code>, showing that the latter has over 3 trillion (decimal) digits. Even with a custom encoding using 4 bits per decimal digit, it would require over 1.5 terabytes of disk space to store it - and very few computers have enough RAM to compute it in a straightforward way.</p> <p>Then <code>3 ↑↑ 5</code> is in turn 3 raised to that multi-trillion digit power. The words and notations we normally use are <em>already</em> inadequate to give any real idea of just how large that is, and there is no computer with enough RAM or disk space to deal with it.</p> <p>And we're only up to <code>3 ↑↑ 5</code>! There are still <em>trillions</em> of layers to go to reach <code>3 ↑↑ 7625597484987</code> = <code>3↑↑↑3</code>. It's beyond human comprehension. Although, yes, infinitely many integers are even larger ;-)</p>
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 optimise it?</p> <pre><code>#!/bin/python3 import sys n,k,q = input().strip().split(' ') n,k,q = [int(n),int(k),int(q)] a = [int(a_temp) for a_temp in input().strip().split(' ')] m = [] for a0 in range(q): m.append(int(input().strip())) for i in range (0, k % n): temp = a[n-1] # Stores the last element temporarily a.pop(n-1) # Removes the last element a = [temp] + a # Appends the temporary element to the start (prepends) for i in range (0, q): print(a[m[i]]) </code></pre>
-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 the actual list, there's no need to do it one element at a time (which will require <code>k</code> operations that each take <code>O(n)</code> time, so <code>O(n*k)</code> total). You can simply concatenate <code>a[-k:]</code> and <code>a[:-k]</code> (again, perhaps with a modulus to fix the <code>k &gt; n</code> case), taking <code>O(n)</code> time just once.</p>
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 one row below it. So on click, it should display next row information in same row. I am posting code below with little different syntax. I displayed syntax of db for header which i also want to exclude it.</p> <p>I added .ui file. you can save it directly as .ui:</p> <pre class="lang-xml prettyprint-override"><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;ui version="4.0"&gt; &lt;class&gt;remarks&lt;/class&gt; &lt;widget class="QMainWindow" name="remarks"&gt; &lt;property name="geometry"&gt; &lt;rect&gt; &lt;x&gt;0&lt;/x&gt; &lt;y&gt;0&lt;/y&gt; &lt;width&gt;1073&lt;/width&gt; &lt;height&gt;862&lt;/height&gt; &lt;/rect&gt; &lt;/property&gt; &lt;property name="windowTitle"&gt; &lt;string&gt;MainWindow&lt;/string&gt; &lt;/property&gt; &lt;widget class="QWidget" name="centralwidget"&gt; &lt;widget class="QComboBox" name="compcb"&gt; &lt;property name="geometry"&gt; &lt;rect&gt; &lt;x&gt;60&lt;/x&gt; &lt;y&gt;360&lt;/y&gt; &lt;width&gt;131&lt;/width&gt; &lt;height&gt;27&lt;/height&gt; &lt;/rect&gt; &lt;/property&gt; &lt;/widget&gt; &lt;widget class="QComboBox" name="loccb"&gt; &lt;property name="geometry"&gt; &lt;rect&gt; &lt;x&gt;60&lt;/x&gt; &lt;y&gt;410&lt;/y&gt; &lt;width&gt;131&lt;/width&gt; &lt;height&gt;27&lt;/height&gt; &lt;/rect&gt; &lt;/property&gt; &lt;/widget&gt; &lt;widget class="QComboBox" name="rescb"&gt; &lt;property name="geometry"&gt; &lt;rect&gt; &lt;x&gt;60&lt;/x&gt; &lt;y&gt;460&lt;/y&gt; &lt;width&gt;131&lt;/width&gt; &lt;height&gt;27&lt;/height&gt; &lt;/rect&gt; &lt;/property&gt; &lt;/widget&gt; &lt;widget class="QLineEdit" name="lat"&gt; &lt;property name="geometry"&gt; &lt;rect&gt; &lt;x&gt;60&lt;/x&gt; &lt;y&gt;540&lt;/y&gt; &lt;width&gt;113&lt;/width&gt; &lt;height&gt;27&lt;/height&gt; &lt;/rect&gt; &lt;/property&gt; &lt;/widget&gt; &lt;widget class="QLineEdit" name="lon"&gt; &lt;property name="geometry"&gt; &lt;rect&gt; &lt;x&gt;60&lt;/x&gt; &lt;y&gt;590&lt;/y&gt; &lt;width&gt;113&lt;/width&gt; &lt;height&gt;27&lt;/height&gt; &lt;/rect&gt; &lt;/property&gt; &lt;/widget&gt; &lt;widget class="QLineEdit" name="landmark"&gt; &lt;property name="geometry"&gt; &lt;rect&gt; &lt;x&gt;330&lt;/x&gt; &lt;y&gt;360&lt;/y&gt; &lt;width&gt;113&lt;/width&gt; &lt;height&gt;27&lt;/height&gt; &lt;/rect&gt; &lt;/property&gt; &lt;/widget&gt; &lt;widget class="QPlainTextEdit" name="sugges"&gt; &lt;property name="geometry"&gt; &lt;rect&gt; &lt;x&gt;330&lt;/x&gt; &lt;y&gt;410&lt;/y&gt; &lt;width&gt;121&lt;/width&gt; &lt;height&gt;78&lt;/height&gt; &lt;/rect&gt; &lt;/property&gt; &lt;/widget&gt; &lt;widget class="QPlainTextEdit" name="plainTextEdit_2"&gt; &lt;property name="geometry"&gt; &lt;rect&gt; &lt;x&gt;330&lt;/x&gt; &lt;y&gt;510&lt;/y&gt; &lt;width&gt;121&lt;/width&gt; &lt;height&gt;78&lt;/height&gt; &lt;/rect&gt; &lt;/property&gt; &lt;/widget&gt; &lt;widget class="QTableWidget" name="tableWidget"&gt; &lt;property name="geometry"&gt; &lt;rect&gt; &lt;x&gt;20&lt;/x&gt; &lt;y&gt;10&lt;/y&gt; &lt;width&gt;991&lt;/width&gt; &lt;height&gt;311&lt;/height&gt; &lt;/rect&gt; &lt;/property&gt; &lt;/widget&gt; &lt;widget class="QPushButton" name="submit"&gt; &lt;property name="geometry"&gt; &lt;rect&gt; &lt;x&gt;350&lt;/x&gt; &lt;y&gt;670&lt;/y&gt; &lt;width&gt;99&lt;/width&gt; &lt;height&gt;41&lt;/height&gt; &lt;/rect&gt; &lt;/property&gt; &lt;property name="font"&gt; &lt;font&gt; &lt;pointsize&gt;12&lt;/pointsize&gt; &lt;weight&gt;50&lt;/weight&gt; &lt;bold&gt;false&lt;/bold&gt; &lt;/font&gt; &lt;/property&gt; &lt;property name="text"&gt; &lt;string&gt;Submit&lt;/string&gt; &lt;/property&gt; &lt;/widget&gt; &lt;/widget&gt; &lt;widget class="QMenuBar" name="menubar"&gt; &lt;property name="geometry"&gt; &lt;rect&gt; &lt;x&gt;0&lt;/x&gt; &lt;y&gt;0&lt;/y&gt; &lt;width&gt;1073&lt;/width&gt; &lt;height&gt;25&lt;/height&gt; &lt;/rect&gt; &lt;/property&gt; &lt;/widget&gt; &lt;widget class="QStatusBar" name="statusbar"/&gt; &lt;/widget&gt; &lt;resources/&gt; &lt;connections/&gt; &lt;/ui&gt; </code></pre> <pre class="lang-python prettyprint-override"><code>from PyQt4 import QtCore, QtGui, uic from PyQt4.QtCore import QString from PyQt4.QtGui import * from PyQt4.QtCore import * import MySQLdb import os import time import sys import csv ### Loading .UI file ### rts_class = uic.loadUiType("main.ui")[0] class Mainwindow(QtGui.QMainWindow, rts_class): def __init__(self, parent=None): QtGui.QMainWindow.__init__(self, parent) self.setupUi(self) #self.review.clicked.connect(self, review_application) self.submit.clicked.connect(self.submit_application) #self.quit.clicked.connect(self, quit_application self.load_db() self.checkbox() def load_db(self): self.dadis.setRowCount(1) self.dadis.setColumnCount(headlen) self.dadis.setHorizontalHeaderLabels(QString('%s' % ', '.join(map(str, mainheader))).split(",")) if os.path.isfile("RTS.csv") is True: with open('RTS.csv', 'r') as fo: reader = csv.reader(fo, delimiter = ',') ncol = len(next(reader)) data = list(reader) row_count = len(data) print row_count main = data[0] print main for var in range(0, ncol): self.dadis.setItem(0, var, QTableWidgetItem(main[var])) fo.close() def checkbox(self): self.compcb.addItem(" ") self.compcb.addItem("Complete") self.compcb.addItem("InComplete") self.loccb.addItem(" ") self.loccb.addItem("Locatable") self.loccb.addItem("UnLocatable") self.rescb.addItem(" ") self.rescb.addItem("House") self.rescb.addItem("Street") self.rescb.addItem("Colony") self.rescb.addItem("Society") def submit_application(self): compout = self.compcb.currentText() locout = self.loccb.currentText() resout = self.rescb.currentText() lattxt = self.lat.text() lontxt = self.lon.text() landtxt = self.landmark.text() suggestxt = self.sugges.toPlainText() remarkstxt = self.remarks.toPlainText() print compout print locout print resout print lattxt print lontxt print landtxt print suggestxt print remarkstxt if os.path.isfile("rts_output.csv") is False: with open('rts_output.csv', 'a') as fp: b = csv.writer(fp, delimiter = ',') header = [["COMPLETENESS", "LOCATABLE", "RESOLUTION", "GEO_LAT", "GEO_LON", "LANDMARK", "SUGGESTION", "REMARKS"]] b.writerows(header) if os.path.isfile("rts_output.csv") is True: with open('rts_output.csv', 'a') as fp: a = csv.writer(fp, delimiter = ',' ) data = [[compout, locout, resout, lattxt, lontxt, landtxt, suggestxt, remarkstxt]] a.writerows(data) if os.path.isfile("RTS.csv") is True: with open('RTS.csv', 'r') as fo: reader = csv.reader(fo, delimiter = ',') ncol = len(next(reader)) data = list(reader) row_count = len(data) x = data[0][0] print x i = int(x)+1 print i if i &lt;= row_count: main = data[i-1] print main #for var in range(0, ncol): #self.dadis.setItem(0, var, QTableWidgetItem(main[var])) fo.close() if __name__ == '__main__': app = QtGui.QApplication(sys.argv) myMain = Mainwindow() myMain.show() sys.exit(app.exec_()) </code></pre>
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.QMainWindow, rts_class): def __init__(self, parent=None, *args, **kwargs): QtGui.QMainWindow.__init__(self, parent) self.setupUi(self) self.submit.clicked.connect(self.submit_application) def submit_application(self, count_clicked): staticVariable.static_count_clicked += 1 print staticVariable.static_count_clicked </code></pre>
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-project files in PyCharm?</p> <p><a href="https://i.stack.imgur.com/ETzKa.png" rel="nofollow"><img src="https://i.stack.imgur.com/ETzKa.png" alt="enter image description here"></a></p>
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" rel="nofollow"><img src="https://i.stack.imgur.com/Zo05U.png" alt="enter image description here"></a></p> <p>Looks like Arnaud P may be right, as the exact same file content in a project file raises the unresolved reference flags:</p> <blockquote> <p>I suppose Pycharm considers it doesn't know enough to complain about unresolved variables, since this file might be part of another project. – Arnaud P 22 mins ago</p> </blockquote> <p>Confirmed by JetBrains:</p> <blockquote> <p>This is the answer I've got from them: "This is expected behavior, this inspection is suspended if file is outside of current project. PyCharm doesn't know configuration, source roots, etc of other projects/other files." So I mark your suggestion as the accepted answer. – Sinan Çetinkaya 5 mins ago</p> </blockquote> <p>As a workaround you could have a (re-usable) project with one (or more) files in which you paste non-project file contents just for the purpose of running inspections. </p> <p>Or just create a project for that file.</p>
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 implemented in python while using a <code>while loop</code>. </p> <p><code>erf (x)</code> is simplified already as : <code>(2/ (sqrt(pi)) (x - x^3/3 + x^5/10 - x^7/42...)</code></p> <p>Terms in the series must be added until the absolute total is less than 10^-20.</p>
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 s = x while diff &gt; math.pow(10, -20): dividend = math.pow((-1), n) * math.pow(x, 2 * n + 1) divider = math.factorial(n) * (2 * n + 1) s += dividend / divider res = ((2 / math.sqrt(math.pi)) * s) diff = abs(res1 - res) res1 = res n += 1 return res print(erf(1)) </code></pre> <p>Please read the source code carefully and post all questions that you don't understand. </p> <p><a href="http://svn.python.org/view/python/trunk/Modules/mathmodule.c?view=markup" rel="nofollow">Also you may check python sources</a> and see how erf is implemented </p>
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/2.7/lib/python2.7/decimal.py", line 139, in &lt;module&gt; import math as _math File "math.py", line 3, in &lt;module&gt; from decimal import Decimal ImportError: cannot import name Decimal </code></pre> <p>I am using Python 2.7.11 This is making me feel pretty stupid since it seems like a simple thing to do. Is Decimal not supported or am I doing this wrong?</p>
-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>:~$ export PYTHON="${PYTHON:-python3}" </code></pre> <p>but it doesn't work.</p>
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 value -- expands instead to the value <code>bar</code> as a default. If the result is not <code>bar</code>, then that means that <code>$foo</code> must already be set to a non-<code>bar</code> value.</p> <p>The logic of this command is roughly thus:</p> <ul> <li>If no shell variable named <code>PYTHON</code> exists, or such a variable exists but with an empty value, then export an environment variable -- and also set a shell variable -- named <code>PYTHON</code>, with a value being <code>python</code>. (Not <code>/usr/bin/python2</code>, but exactly <code>python</code>, those six precise characters).</li> <li>If a shell variable named <code>PYTHON</code> does exist with a nonempty value, then export it with its current value to the environment. (If that variable is already exported, then this line has no effect).</li> </ul> <p>Since <code>echo $PYTHON</code> is emitting as output <code>/usr/bin/python2</code>, then this means that <code>PYTHON=/usr/bin/python2</code> must have been true <strong>before</strong> your original command was invoked at all.</p> <hr> <p>If, unlike your original command, you want to disregard the original value of the <code>PYTHON</code> shell variable (or environment variable, if it's already been <code>export</code>ed), then you should do something like the following:</p> <pre><code>PYTHON=$(type -P python3) || { echo "python3 not found" &gt;&amp;2 exit 1 } export PYTHON </code></pre> <p>The <code>export</code> is done as a separate command here so that the exit status of <code>export</code> does not override the exit status of <code>type</code>, which would prevent errors from being detected.</p>
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 ctypes.ArgumentError?: "argument 2: &lt;type 'exceptions.TypeError?'&gt;: wrong type" in ignored Exception ctypes.ArgumentError?: "argument 2: &lt;type 'exceptions.TypeError?'&gt;: wrong type" in ignored </code></pre> <p>I'm not using ctypes. The error could be in libraries I am importing: selenium, pyvisa/visa, or labjack/labjackpython. I tried importing some of those libraries locally but that didn't seem to change anything.</p> <p>Is there a way to hunt down the source of errors like this? A file name and line number would be great. Thanks</p>
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 which should show the library that causes the exception.</p>
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 starting up the app, redis or the worker, I set APP_SETTINGS:</p> <pre><code>export APP_SETTINGS="project.config.DevelopmentConfig" </code></pre> <p>However, when an item gets added to the queue, here's the stack trace:</p> <pre><code>17:00:00 *** Listening on default... 17:00:59 default: project.email.sendMailInBG(&lt;flask_mail.Message object at 0x7fc930e1c3d0&gt;) (aacf9546-5558-4db8-9232-5f36c25d521b) 17:01:00 KeyError: 'APP_SETTINGS' Traceback (most recent call last): File "/home/tony/pyp-launch/venv/local/lib/python2.7/site-packages/rq/worker.py", line 588, in perform_job rv = job.perform() File "/home/tony/pyp-launch/venv/local/lib/python2.7/site-packages/rq/job.py", line 498, in perform self._result = self.func(*self.args, **self.kwargs) File "/home/tony/pyp-launch/venv/local/lib/python2.7/site-packages/rq/job.py", line 206, in func return import_attribute(self.func_name) File "/home/tony/pyp-launch/venv/local/lib/python2.7/site-packages/rq/utils.py", line 150, in import_attribute module = importlib.import_module(module_name) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/home/tony/pyp-launch/project/__init__.py", line 24, in &lt;module&gt; app.config.from_object(os.environ['APP_SETTINGS']) File "/home/tony/pyp-launch/venv/lib/python2.7/UserDict.py", line 40, in __getitem__ raise KeyError(key) KeyError: 'APP_SETTINGS' Traceback (most recent call last): File "/home/tony/pyp-launch/venv/local/lib/python2.7/site-packages/rq/worker.py", line 588, in perform_job rv = job.perform() File "/home/tony/pyp-launch/venv/local/lib/python2.7/site-packages/rq/job.py", line 498, in perform self._result = self.func(*self.args, **self.kwargs) File "/home/tony/pyp-launch/venv/local/lib/python2.7/site-packages/rq/job.py", line 206, in func return import_attribute(self.func_name) File "/home/tony/pyp-launch/venv/local/lib/python2.7/site-packages/rq/utils.py", line 150, in import_attribute module = importlib.import_module(module_name) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/home/tony/pyp-launch/project/__init__.py", line 24, in &lt;module&gt; app.config.from_object(os.environ['APP_SETTINGS']) File "/home/tony/pyp-launch/venv/lib/python2.7/UserDict.py", line 40, in __getitem__ raise KeyError(key) KeyError: 'APP_SETTINGS' 17:01:00 Moving job to u'failed' queue 17:01:00 17:01:00 *** Listening on default... </code></pre> <p><strong>email.py</strong></p> <pre><code>from flask.ext.mail import Message from project import app, mail from redis import Redis from rq import use_connection, Queue q = Queue(connection=Redis()) def send_email(to, subject, template, emailable): if emailable==True: msg = Message( subject, recipients=[to], html=template, sender=app.config['MAIL_DEFAULT_SENDER'] ) q.enqueue(sendMailInBG, msg) else: print("no email sent, emailable set to: " + str(emailable)) def sendMailInBG(msgContent): with app.test_request_context(): mail.send(msgContent) </code></pre> <p><strong>worker.py</strong></p> <pre><code>import os import redis from rq import Worker, Queue, Connection listen = ['default'] redis_url = os.getenv('REDISTOGO_URL', 'redis://localhost:6379') conn = redis.from_url(redis_url) if __name__ == '__main__': with Connection(conn): worker = Worker(list(map(Queue, listen))) worker.work() </code></pre> <p>I'd really appreciate another set of eyes on this. I can't for the life of me figure out what's going on here.</p>
-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 = EmployeePersonal template_name = 'employeesControll/employees_studies_update_form.html' success_url = reverse('employee-details', kwargs={'pk': kwargs.get('pk')}) </code></pre> <p>My <em>url</em> is the following</p> <pre><code>url(r'^employees/detalles/(?P&lt;pk&gt;[0-9]+)/$', login_required(views.EmployeeDetails.as_view()), name='employee-details') </code></pre>
-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': self. kwargs['pk']}) </code></pre>
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 = EmployeePersonal template_name = 'employeesControll/employees_studies_update_form.html' success_url = reverse('employee-details', kwargs={'pk': kwargs.get('pk')}) </code></pre> <p>My <em>url</em> is the following</p> <pre><code>url(r'^employees/detalles/(?P&lt;pk&gt;[0-9]+)/$', login_required(views.EmployeeDetails.as_view()), name='employee-details') </code></pre>
-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</code> or <code>UpdateView</code> - they will use <code>get_absolute_url()</code> on the model object if available.</p> </blockquote> <p>You'll use <code>self.id</code> in the <code>get_absolute_url</code> method for the model objects primary key.</p> <hr> <p>Reference:</p> <p><a href="https://docs.djangoproject.com/en/1.10/topics/class-based-views/generic-editing/#model-forms" rel="nofollow">Model Forms</a></p>
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 getting this error:</p> <pre><code> UnboundLocalError: local variable 'v' referenced before assignment </code></pre> <p>all_R is a defaultdict where every value has keys that are pairs, and I'm interested in just one value from that pair:</p> <pre><code> {'1-0002': [('A-75G', 'dnaN'), ('I245T', 'recF'),... ], '1-0004': [('A-75G', 'dnaN'), ('L161', 'dnaN'),...]} </code></pre>
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 <code>(pairs[1] for k,v in all_R.iteritems() for pairs in v)</code></p> <p>That will create a generator with your desired properties. </p>
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("file2.csv") df3 = dd.merge(df1, df2) </code></pre> <p>Now, let's say I were to run this on my laptop, with 4 cores. How do I assign 4 threads to this task?</p> <p>It appears the correct way to do this is:</p> <pre><code>dask.set_options(get=dask.threaded.get) df3 = dd.merge(df1, df2).compute() </code></pre> <p>And this will use as many threads exist (i.e. as many cores with shared memory on your laptop exist, 4)? How do I set the number of threads?</p> <p>Let's say I am at a facility with 100 cores. How do I submit this in the same manner as one would submit jobs to the cluster with <code>qsub</code>? (Similar to running tasks on clusters via MPI?)</p> <pre><code>dask.set_options(get=dask.threaded.get) df3 = dd.merge(df1, df2).compute </code></pre>
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> method.</p> <h3>Distributed machine scheduling</h3> <p>You can use <a href="http://distributed.readthedocs.io/en/latest/" rel="nofollow">dask.distributed</a> to <a href="http://distributed.readthedocs.io/en/latest/setup.html" rel="nofollow">deploy dask workers across many nodes in a cluster</a>. One way to do this with <code>qsub</code> is to start a <code>dask-scheduler</code> locally:</p> <pre><code>$ dask-scheduler Scheduler started at 192.168.1.100:8786 </code></pre> <p>And then use <code>qsub</code> to launch many <code>dask-worker</code> processes, pointed at the reported address:</p> <pre><code>$ qsub dask-worker 192.168.1.100:8786 ... &lt;various options&gt; </code></pre> <p>As of yesterday there is an experimental package that can do this on any DRMAA-enabled system (which includes SGE/qsub-like systems): <a href="https://github.com/dask/dask-drmaa" rel="nofollow">https://github.com/dask/dask-drmaa</a></p> <p>After you have done this you can create a <code>dask.distributed.Client</code> object, which will take over as default scheduler</p> <pre><code>from dask.distributed import Client c = Client('192.168.1.100:8786') # now computations run by default on the cluster </code></pre> <h3>Multi-threaded performance</h3> <p>Note that as of Pandas version 0.19 the GIL still isn't released for <code>pd.merge</code>, so I wouldn't expect a huge speed boost from using multiple threads. If this is important to you then I recommend putting in a comment here: <a href="https://github.com/pandas-dev/pandas/issues/13745" rel="nofollow">https://github.com/pandas-dev/pandas/issues/13745</a></p>
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 to append that class name and keep adding +1 to <code>times_mentioned</code> for a specific class. </p> <p>This is what I have so far</p> <pre><code>class popular_courses(db.Model): id = db.Column(db.Integer,primary_key=True) name = db.Column(db.String(80), unique=True, default=None) times_mentioned =db.Column(db.String(80), default=None, unique=True) def __repr__(self): return '&lt;Popular Courses %r&gt;' % (self.name) @app.route('/add/&lt;coursename&gt;') def AddCourseName(coursename): addPopularCourse = popular_courses(name=coursename, times_mentioned=##DONT KNOW THE SYNTAX) </code></pre> <p>So like I'd want class name and add +1 every time the user visits /add URL. How would I do it? I don't know the syntax for it either.</p> <p>@app.route('/add/')</p> <pre><code>def AddCourseName(coursename): try: addPopularCourse = popular_courses(name=coursename, times_mentioned=1) db.session.add(addPopularCourse) db.session.commit() return "added! " + coursename + " to db" except exc.SQLAlchemyError: db.session.rollback() user = popular_courses.query.filter_by(name=coursename).first() user.name = coursename user.times_mentioned += 1 db.session.commit() </code></pre> <p>Is this the efficient approach?</p>
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==coursename).count‌​() &gt; 0: course = popular_courses.query.filter_by(name=coursename).first() course.name = coursename course.times_mentioned += 1 db.session.commit() return "increased by 1! " else: addPopularCourse = popular_courses(name=coursename, times_mentioned=1) db.session.add(addPopularCourse) db.session.commit() return "added! " + coursename + " to db" </code></pre>
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 hundreds of commands with different return values that I get dynamically, but this is one example what I can get back when I pass a command ID</p> <pre><code>def get_command_vars(commandID = None): if commandID == '0x4F': return [['mode', '16bits'], ['seconds', '8bits']] def issueMyCommand(commandID = None): commandParameters = get_command_vars(command=0x4F) </code></pre> <blockquote> <p>commandParameters tells me that the parameters for this command are mode and seconds, but they are strings </p> </blockquote> <pre><code>commandParm_1 = commandParameters[0][0] # 'mode' commandParm_2 = commandParameters[1][0] # 'seconds' &gt;get User Input from the gui to pass to issuetheCommand input1 = getinputEntry1() # this is the 'mode' value, e.g., 8 input2 = getinputEntry2() # this is the 'seconds' value, e.g., 14 </code></pre> <blockquote> <p>I have the values to pass from the user input but I don't know how to pass them to the function since I only have the variables as strings, i.e.'mode' and 'seconds'</p> </blockquote> <pre><code>c = issueTheCommand(mode = input1, seconds = input2) </code></pre> <blockquote> <p>this command format will change based on the parameter types from get_command_vars, so it could be 'count', 'datalength', 'milliseconds, 'delay', etc</p> </blockquote> <p>@sberry - actually the user input values are what will be passed with mode and seconds. the 16bits and 8 bits doesn't really come into play here. I'm trying to do this without changing the format that "issueTheCommand" function is expecting if possible. the way I issue it now looks like this: c = issueTheCommand(mode = 8, seconds = 14). i don't think it will take a dict?</p>
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></pre>
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 hundreds of commands with different return values that I get dynamically, but this is one example what I can get back when I pass a command ID</p> <pre><code>def get_command_vars(commandID = None): if commandID == '0x4F': return [['mode', '16bits'], ['seconds', '8bits']] def issueMyCommand(commandID = None): commandParameters = get_command_vars(command=0x4F) </code></pre> <blockquote> <p>commandParameters tells me that the parameters for this command are mode and seconds, but they are strings </p> </blockquote> <pre><code>commandParm_1 = commandParameters[0][0] # 'mode' commandParm_2 = commandParameters[1][0] # 'seconds' &gt;get User Input from the gui to pass to issuetheCommand input1 = getinputEntry1() # this is the 'mode' value, e.g., 8 input2 = getinputEntry2() # this is the 'seconds' value, e.g., 14 </code></pre> <blockquote> <p>I have the values to pass from the user input but I don't know how to pass them to the function since I only have the variables as strings, i.e.'mode' and 'seconds'</p> </blockquote> <pre><code>c = issueTheCommand(mode = input1, seconds = input2) </code></pre> <blockquote> <p>this command format will change based on the parameter types from get_command_vars, so it could be 'count', 'datalength', 'milliseconds, 'delay', etc</p> </blockquote> <p>@sberry - actually the user input values are what will be passed with mode and seconds. the 16bits and 8 bits doesn't really come into play here. I'm trying to do this without changing the format that "issueTheCommand" function is expecting if possible. the way I issue it now looks like this: c = issueTheCommand(mode = 8, seconds = 14). i don't think it will take a dict?</p>
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; a(**c) {'y': 2, 'x': 1} </code></pre>
0
2016-10-15T04:00:12Z
[ "python", "string", "variables", "parameters" ]