title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
importing issues between modules
39,970,364
<pre><code>|--------FlaskApp |----------------FlaskApp |----------------__init__.py |----------------view.py |----------------models.py |----------------db_create.py |-----------------------static |-----------------------templates |-----------------------venv |-----------------------__init__.py |----------------flaskap...
-1
2016-10-11T04:07:58Z
39,988,340
<p>got this after using the above answer</p> <pre>RuntimeError: Working outside of application context. This typically means that you attempted to use functionality that needed to interface with the current application object in a way. To solve this set up an application context with app.app_context(). See the docum...
0
2016-10-11T23:34:04Z
[ "python", "flask", "flask-sqlalchemy", "python-3.5" ]
Finding a coordinate of matched object from template matching
39,970,445
<p>I'm a newbie to computer vision and openCV, just for the heads up. So I used this code from <a href="http://docs.opencv.org/3.1.0/d4/dc6/tutorial_py_template_matching.html" rel="nofollow">http://docs.opencv.org/3.1.0/d4/dc6/tutorial_py_template_matching.html</a></p> <p>Below is the code:</p> <pre><code>import cv2 ...
0
2016-10-11T04:19:09Z
39,971,154
<p>This piece of code:</p> <pre><code>for pt in zip(*loc[::-1]): cv2.rectangle(image, pt, (pt[0] + w, pt[1] + h), (0,0,255), 2) </code></pre> <p>draws red rectangle at every position where template probably is located. So at every step point <code>pt</code> (from <code>loc</code> list) contains coordinates of the...
0
2016-10-11T05:49:26Z
[ "python", "osx", "python-2.7", "opencv", "opencv3.0" ]
What to do if a query result is too big
39,970,487
<p>I'm using mysql connector of python3 to query from a mysql database. I have so many data that if I collect the recent 7 days' data, the size of the query will be over 10GB and therefore forced my python script to be killed. I think usually we can stream the result however I don't find a way to stream the query resul...
-1
2016-10-11T04:26:42Z
39,970,671
<p>Don't fetch the result set in one go. You can do one of the following or the combination of these:</p> <ol> <li>Use <code>LIMIT, OFFSET</code> to generate multiple files using <code>SELECT into</code></li> <li>Use Date/Hour Functions to generate multiple files using <code>SELECT into</code></li> </ol> <p><code>cat...
0
2016-10-11T04:50:12Z
[ "python", "mysql", "mysql-connector" ]
What to do if a query result is too big
39,970,487
<p>I'm using mysql connector of python3 to query from a mysql database. I have so many data that if I collect the recent 7 days' data, the size of the query will be over 10GB and therefore forced my python script to be killed. I think usually we can stream the result however I don't find a way to stream the query resul...
-1
2016-10-11T04:26:42Z
40,029,516
<p>@Anthony Kong's comment is correct. To solve this issue, we can do <code>fetchmany</code> function from <a href="https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-fetchmany.html" rel="nofollow">https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-fetchmany.html<...
0
2016-10-13T19:37:25Z
[ "python", "mysql", "mysql-connector" ]
Connect to Database on local host with sqlite3 in python
39,970,495
<p>I have a database that I am running on my local machine which I can access through Microsoft SQL Server Manager Studio. I connect to this server "JIMS-LAPTOP\SQLEXPRESS" and then I can run queries through the manager. However I need to be able to connect to this database and work with it through python. When I try ...
0
2016-10-11T04:27:08Z
39,971,478
<p>You can't use sqlite3 to connect to SQL server, only to Sqlite databases. You need to use a driver that can talk to MS SQL, like <code>pyodbc</code>.</p>
1
2016-10-11T06:22:11Z
[ "python", "sql", "sql-server", "database", "sqlite3" ]
Python: Plot a sparse matrix
39,970,515
<p>I have a sparse matrix X, shape (6000, 300). I'd like something like a scatterplot which has a dot where the X(i, j) != 0, and blank space otherwise. I don't know how many nonzero entries there are in each row of X. X[0] has 15 nonzero entries, X[1] has 3, etc. The maximum number of nonzero entries in a row is 16.</...
0
2016-10-11T04:29:47Z
39,971,118
<p>It seems to me heatmap is the best candidate for this type of plot. imshow() will return u a colored matrix with color scale legend. </p> <p>I don't get ur stretched ellipses problem, shouldnt it be a colored squred for each data point? </p> <p>u can try log color scale if it is sparse. also plot the 12 classes se...
0
2016-10-11T05:44:36Z
[ "python", "matplotlib" ]
Python: Plot a sparse matrix
39,970,515
<p>I have a sparse matrix X, shape (6000, 300). I'd like something like a scatterplot which has a dot where the X(i, j) != 0, and blank space otherwise. I don't know how many nonzero entries there are in each row of X. X[0] has 15 nonzero entries, X[1] has 3, etc. The maximum number of nonzero entries in a row is 16.</...
0
2016-10-11T04:29:47Z
39,979,586
<p>You can use <code>nonzero()</code> to find the non zero elements and use <code>scatter()</code> plot the points:</p> <pre><code>import pylab as pl import numpy as np a = np.random.rand(6000, 300) a[a &lt; 0.9999] = 0 r, c = np.nonzero(a) pl.scatter(r, c, c=a[r, c]) </code></pre>
0
2016-10-11T14:27:12Z
[ "python", "matplotlib" ]
Python: Plot a sparse matrix
39,970,515
<p>I have a sparse matrix X, shape (6000, 300). I'd like something like a scatterplot which has a dot where the X(i, j) != 0, and blank space otherwise. I don't know how many nonzero entries there are in each row of X. X[0] has 15 nonzero entries, X[1] has 3, etc. The maximum number of nonzero entries in a row is 16.</...
0
2016-10-11T04:29:47Z
40,127,976
<p><code>plt.matshow</code> also turned out to be a feasible solution. I could also plot a heatmap with colorbars and all that.</p>
0
2016-10-19T09:55:31Z
[ "python", "matplotlib" ]
How to encode two Pandas dataframes according to the same dummy vectors?
39,970,517
<p>I'm trying to encode categorical values to dummy vectors. pandas.get_dummies does a perfect job, but the dummy vectors depend on the values present in the Dataframe. How to encode a second Dataframe according to the same dummy vectors as the first Dataframe?</p> <pre><code> import pandas as pd df=pd.DataFrame({'c...
0
2016-10-11T04:29:50Z
39,973,405
<p>A always use <a href="https://github.com/wdm0006/categorical_encoding" rel="nofollow">categorical_encoding</a> because it has a great choice of encoders. It also works with Pandas very nicely, is pip installable and is written inline with the sklearn API.</p> <p>If you wish to encode just the first column, like in ...
0
2016-10-11T08:38:35Z
[ "python", "pandas", "machine-learning" ]
How to encode two Pandas dataframes according to the same dummy vectors?
39,970,517
<p>I'm trying to encode categorical values to dummy vectors. pandas.get_dummies does a perfect job, but the dummy vectors depend on the values present in the Dataframe. How to encode a second Dataframe according to the same dummy vectors as the first Dataframe?</p> <pre><code> import pandas as pd df=pd.DataFrame({'c...
0
2016-10-11T04:29:50Z
39,979,704
<p>I had the same problem before. This is what I did which is not necessary the best way to do this. But this works for me.</p> <pre><code>df=pd.DataFrame({'cat1':['A','N'],'cat2':['C','S']}) df['cat1'] = df['cat1'].astype('category', categories=['A','N','K','P']) # then run the get_dummies b=pd.get_dummies(df['cat1'...
1
2016-10-11T14:31:57Z
[ "python", "pandas", "machine-learning" ]
Plot a graph in python using common values in dictionary
39,970,537
<p>How can I visually represent the common keys when a value is selected. I am creating a form where the user will select a value, say <code>'john'</code>. I want to plot the common keys'a', 'b' and 'c'. Suggestions on how to approach this problem will be very helpful.</p> <pre><code>d = { 'a': ['john', 'doe', 'jane'...
1
2016-10-11T04:33:07Z
39,971,329
<p>You can create a data frame from the dictionary:</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt plt.style.use('ggplot') df = pd.DataFrame({ 'a': ['john', 'doe', 'jane'], 'b': ['james', 'danny', 'john'], 'c':['john', 'scott', 'jane'], }) </code></pre> <p>Then you can simply plot <code>john</c...
1
2016-10-11T06:09:28Z
[ "python", "pandas", "dictionary", "matplotlib", "plot" ]
Plot a graph in python using common values in dictionary
39,970,537
<p>How can I visually represent the common keys when a value is selected. I am creating a form where the user will select a value, say <code>'john'</code>. I want to plot the common keys'a', 'b' and 'c'. Suggestions on how to approach this problem will be very helpful.</p> <pre><code>d = { 'a': ['john', 'doe', 'jane'...
1
2016-10-11T04:33:07Z
39,971,446
<p>Solution with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.plot.bar.html" rel="nofollow"><code>Series.plot.bar</code></a>:</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt df = pd.DataFrame({ 'a': ['john', 'doe', 'jane'], 'b': ['james', 'danny', 'john'], 'c':['j...
2
2016-10-11T06:18:51Z
[ "python", "pandas", "dictionary", "matplotlib", "plot" ]
How to divide list of lists by another list of lists in Python?
39,970,595
<p>I have <code>q = [[7,2,3],[4,5,6]]</code> and <code>r=[[6,1,2],[3,4,5]]</code>. I need to divide q by the corresponding elements in r. (i.e. <code>[[7/6,2/1,3/2],[4/3,5/4,6/5]]</code>)</p> <p>Output needed B = [[1.16,2,1.5],[1.33,1.25,1.2]]</p> <p>Code:</p> <p><code>B= [[float(j)/float(i) for j in q] for i in r]<...
1
2016-10-11T04:39:54Z
39,970,627
<p>Use <a href="https://docs.python.org/3/library/functions.html#zip"><em>zip</em></a> for bring together the sublists pairwise and then use it again to bring together the corresponding numerators and denominators:</p> <pre><code>&gt;&gt;&gt; q = [[7,2,3],[4,5,6]] &gt;&gt;&gt; r = [[6,1,2],[3,4,5]] &gt;&gt;&gt; [[n/d ...
8
2016-10-11T04:43:17Z
[ "python", "algorithm", "list", "floating-point", "division" ]
How to divide list of lists by another list of lists in Python?
39,970,595
<p>I have <code>q = [[7,2,3],[4,5,6]]</code> and <code>r=[[6,1,2],[3,4,5]]</code>. I need to divide q by the corresponding elements in r. (i.e. <code>[[7/6,2/1,3/2],[4/3,5/4,6/5]]</code>)</p> <p>Output needed B = [[1.16,2,1.5],[1.33,1.25,1.2]]</p> <p>Code:</p> <p><code>B= [[float(j)/float(i) for j in q] for i in r]<...
1
2016-10-11T04:39:54Z
39,970,678
<p>You can do:</p> <pre><code>&gt;&gt;&gt; out=[] &gt;&gt;&gt; for s1, s2 in zip(q, r): ... inner=[] ... for n, d in zip(s1, s2): ... inner.append(float(n)/d) ... out.append(inner) ... &gt;&gt;&gt; out [[1.1666666666666667, 2.0, 1.5], [1.3333333333333333, 1.25, 1.2]] </code></pre> <p>Or, use numpy:</p...
2
2016-10-11T04:51:01Z
[ "python", "algorithm", "list", "floating-point", "division" ]
gaierror: [Errno 8] nodename nor servname provided, or not known (with macOS Sierra)
39,970,606
<p>socket.gethostbyname(socket.gethostname()) worked well on OS X El Capitan. However, it's not working now after the Mac updated to macOS Sierra.</p> <p>Thanks!</p> <pre><code>import socket socket.gethostbyname(socket.gethostname()) Traceback (most recent call last): File "&lt;pyshell#26&gt;", line 1, in &lt;modu...
0
2016-10-11T04:41:45Z
40,079,851
<p>Same problem tome. I change the code to:</p> <pre><code>import socket socket.gethostbyname("") </code></pre> <p>And it works now.</p>
0
2016-10-17T06:33:17Z
[ "python", "sockets" ]
Python Get Mouse position in a cron script
39,970,611
<p>I am using python3 and I am able to get the mouse position using the following codes in Centos 7:</p> <pre><code>from Xlib import display data = display.Display().screen().root.query_pointer()._data data["root_x"], data["root_y"] </code></pre> <p>However, when I run the script using crontab, it shows the following...
0
2016-10-11T04:42:05Z
39,970,961
<p>It is because the environment variable <code>DISPLAY</code> is not set properly during execution of your python script. Try adding the following line to the beginning of your python script, for example:</p> <pre><code>import os os.environ['DISPLAY'] = ':0.0' # the value should match your setting </code></pre>
0
2016-10-11T05:23:53Z
[ "python", "cron" ]
created CSV file from html page input in python to D3 graph with flask
39,970,664
<p>I have a flask application that I am building. On one page a computation is performed and a csv file is created. This page then links to another page that uses d3 and reads the csv file to display a graph. When I do this, the graph does not display. Is it possible to go from python csv to d3 graph with flask?</p> <...
-1
2016-10-11T04:49:02Z
39,972,774
<p>The csv needed to be placed in the static folder. Not the templates folder.</p>
0
2016-10-11T07:59:53Z
[ "python", "csv", "d3.js", "file-io", "flask" ]
Identifying closest value in a column for each filter using Pandas
39,970,703
<p>I have a data frame with categories and values. I need to find the value in each category closest to a value. I think I'm close but I can't really get the right output when applying the results of argsort to the original dataframe.</p> <p>For example, if the input was defined in the code below the output should h...
3
2016-10-11T04:53:29Z
39,970,834
<p>You can create a column of absolute differences:</p> <pre><code>df['dif'] = (df['values'] - 2).abs() df Out: category values dif 0 a 1 1 1 b 2 0 2 b 3 1 3 b 4 2 4 c 5 3 5 a 4 2 6 b 3 1 7 c ...
3
2016-10-11T05:08:46Z
[ "python", "pandas", "group-by", "boolean", "closest" ]
Identifying closest value in a column for each filter using Pandas
39,970,703
<p>I have a data frame with categories and values. I need to find the value in each category closest to a value. I think I'm close but I can't really get the right output when applying the results of argsort to the original dataframe.</p> <p>For example, if the input was defined in the code below the output should h...
3
2016-10-11T04:53:29Z
39,970,921
<p>Solution with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.DataFrameGroupBy.idxmin.html" rel="nofollow"><code>DataFrameGroupBy.idxmin</code></a> - get indexes of minimal values per group and then assign boolean mask by <a href="http://pandas.pydata.org/pandas-docs/stable/generat...
2
2016-10-11T05:19:42Z
[ "python", "pandas", "group-by", "boolean", "closest" ]
How to get appname from model in django
39,970,853
<p>I have this code</p> <pre><code>class Option(models.Model): option_text = models.CharField(max_length=400) option_num = models.IntegerField() # add field to hold image or a image url in future class Meta: app_label = 'myapp' </code></pre> <p>if i have <code>Options</code> model in my view i wan...
0
2016-10-11T05:10:43Z
39,970,897
<pre><code>from django.contrib.contenttypes.models import ContentType ct = ContentType.objects.get_for_model(option_instance) print(ct.app_label) </code></pre> <p>or</p> <pre><code>option_instance._meta.app_label </code></pre>
3
2016-10-11T05:16:50Z
[ "python", "django" ]
How to get appname from model in django
39,970,853
<p>I have this code</p> <pre><code>class Option(models.Model): option_text = models.CharField(max_length=400) option_num = models.IntegerField() # add field to hold image or a image url in future class Meta: app_label = 'myapp' </code></pre> <p>if i have <code>Options</code> model in my view i wan...
0
2016-10-11T05:10:43Z
39,971,408
<p>If you have an instance of your object, you can quite easily get the app_label from _meta</p> <pre><code>o = Option.objects.all()[0] print o._meta.app_label </code></pre> <p>There is a host of other usefull information in there. In the shell type help(a._meta) to see them all</p>
2
2016-10-11T06:16:00Z
[ "python", "django" ]
Filtering a list. Get elements of list only with a certain distance between items?
39,970,857
<p>I need to get only those elements that are to some extent distant from each other. For example, I have a list of integers:</p> <pre><code>data = [-2000, 1000, 2000, 3500, 3800, 4500, 4600, 5000, 6000] </code></pre> <p>Let's assume I want to retrieve only those elements that have have a distance of at least <strong...
3
2016-10-11T05:11:15Z
39,970,930
<p>Sorting the data and then comparing to the previous would do it:</p> <pre><code>data = [-2000, 1000, 2000, 3500, 3800, 4500, 4600, 5000, 6000] lst = [min(data)] # the min of data goes in solution list for i in sorted(data[1:]): if i-lst[-1] &gt; 999: # comparing with last element lst.append(i) ...
6
2016-10-11T05:20:10Z
[ "python", "list", "python-3.x", "distance" ]
Pygame, move a square on the screen, but can not erase the previous movements
39,970,906
<p>This is my first post in StackOverflow, hope you guys can help a newbie programmer. It's Pygame Python simple ask.</p> <p>I am trying to move a square on the screen, but can not erase the previous movements.</p> <pre><code>import pygame pygame.init() screen = pygame.display.set_mode((400,300)) pygame.display.set_...
0
2016-10-11T05:17:35Z
39,970,939
<p>You have to draw over the previous image. Easiest is to fill the screen with a background color in the beginning of the game loop, like so:</p> <pre><code>screen.fill((0, 0, 0)) </code></pre>
4
2016-10-11T05:21:29Z
[ "python", "pygame", "move", "rect" ]
Pygame, move a square on the screen, but can not erase the previous movements
39,970,906
<p>This is my first post in StackOverflow, hope you guys can help a newbie programmer. It's Pygame Python simple ask.</p> <p>I am trying to move a square on the screen, but can not erase the previous movements.</p> <pre><code>import pygame pygame.init() screen = pygame.display.set_mode((400,300)) pygame.display.set_...
0
2016-10-11T05:17:35Z
39,977,174
<p>You also can draw everything from a previous surface, before the square was in place, then draw the square on it always in a different place. Then draw the new surface to screen each time.</p> <p>But not really good strategy, it can be slow and/or induce flickering.</p> <p>For instance:</p> <pre><code># Draw anyt...
0
2016-10-11T12:23:32Z
[ "python", "pygame", "move", "rect" ]
Pygame, move a square on the screen, but can not erase the previous movements
39,970,906
<p>This is my first post in StackOverflow, hope you guys can help a newbie programmer. It's Pygame Python simple ask.</p> <p>I am trying to move a square on the screen, but can not erase the previous movements.</p> <pre><code>import pygame pygame.init() screen = pygame.display.set_mode((400,300)) pygame.display.set_...
0
2016-10-11T05:17:35Z
40,012,752
<p>I am also a newbie and I am doing something similar and I hope this helps </p> <pre><code>import pygame clock=pygame.time.Clock() #the frames per second BIF in pygame pygame.init() FPS=30 display_width=800 display_height=600 white=(255,255,255) black=(0,0,0) block_size=10 gameExit=False lead_x = display_width / 2 ...
0
2016-10-13T05:11:31Z
[ "python", "pygame", "move", "rect" ]
Where in my code are duplicates being deleted?
39,970,958
<p>An important part of my output is being able to identify the length of the <code>finalList</code> but somewhere in my code, duplicates are being deleted and I can't figure out where</p> <pre><code>from itertools import chain, permutations allPos = [] first_list = ['a','b','c'] match_list = [['a','b','c'], ['a','b',...
0
2016-10-11T05:23:36Z
39,971,399
<p>You can try with this. Change <code>iterable</code> using permutations.</p> <pre><code>from itertools import chain, permutations ... ... for i in range(1,30): # change iterable for phrase in permutations([j for ele in match_list for j in ele], i): ... for i in set(allPos): if len(i) == len(allPos[-1]):...
0
2016-10-11T06:14:58Z
[ "python", "permutation" ]
Make an object that behaves like a slice
39,971,030
<p>How can we make a class represent itself as a slice when appropriate?</p> <p>This didn't work:</p> <pre><code>class MyThing(object): def __init__(self, start, stop, otherstuff): self.start = start self.stop = stop self.otherstuff = otherstuff def __index__(self): return slic...
6
2016-10-11T05:33:03Z
39,971,122
<p>A slice can't be in your return type as the method just doesn't support this. You can read more about the <code>__index__</code> <a href="https://www.python.org/dev/peps/pep-0357/" rel="nofollow">special method here</a>. I could only come up with a workaround that directly calls the function in your class:</p> <pre...
-2
2016-10-11T05:45:34Z
[ "python", "slice" ]
Make an object that behaves like a slice
39,971,030
<p>How can we make a class represent itself as a slice when appropriate?</p> <p>This didn't work:</p> <pre><code>class MyThing(object): def __init__(self, start, stop, otherstuff): self.start = start self.stop = stop self.otherstuff = otherstuff def __index__(self): return slic...
6
2016-10-11T05:33:03Z
39,971,377
<p>TLDR: It's impossible to make custom classes replace <code>slice</code> for builtins types such as <code>list</code> and <code>tuple</code>.</p> <hr> <p>The <code>__index__</code> method exists purely to provide an <em>index</em>, which is by definition an integer in python (see <a href="https://docs.python.org/3....
5
2016-10-11T06:13:02Z
[ "python", "slice" ]
Make an object that behaves like a slice
39,971,030
<p>How can we make a class represent itself as a slice when appropriate?</p> <p>This didn't work:</p> <pre><code>class MyThing(object): def __init__(self, start, stop, otherstuff): self.start = start self.stop = stop self.otherstuff = otherstuff def __index__(self): return slic...
6
2016-10-11T05:33:03Z
39,987,094
<blockquote> <blockquote> <h1>I'M SORRY FOR THE DARK MAGIC</h1> </blockquote> </blockquote> <p>Using <a href="http://clarete.li/forbiddenfruit/" rel="nofollow">Forbiddenfruit</a> and python python's builtin <code>new</code> method I was able to do this:</p> <pre><code>from forbiddenfruit import curse class ...
3
2016-10-11T21:31:27Z
[ "python", "slice" ]
Python Type Error: 'List' object is not callable
39,971,037
<p>I'm getting this error with this small code content of Python27. Can anyone help me with this? Thanks in advance.</p> <blockquote> <p>Run Time Error Traceback (most recent call last): File "5eb4481881d51d6ece1c375c80f5e509.py", line 57, in print len(arr) TypeError: 'list' object is not callable</p> </b...
0
2016-10-11T05:33:49Z
39,971,064
<p>That is what happens when you define a variable that is also a built-in function name.<br> Change the variable <code>len</code> to something else.</p>
1
2016-10-11T05:37:23Z
[ "python", "list" ]
Python Type Error: 'List' object is not callable
39,971,037
<p>I'm getting this error with this small code content of Python27. Can anyone help me with this? Thanks in advance.</p> <blockquote> <p>Run Time Error Traceback (most recent call last): File "5eb4481881d51d6ece1c375c80f5e509.py", line 57, in print len(arr) TypeError: 'list' object is not callable</p> </b...
0
2016-10-11T05:33:49Z
39,971,067
<p>You have created a list named <code>len</code> as you can see here from the fact that you're able to index it:</p> <pre><code>len[i] = input() </code></pre> <p>So naturally, <code>len</code> is no longer a function that gets the length of a list, leading to the error you receive.</p> <p>Solution: name your <code>...
5
2016-10-11T05:37:38Z
[ "python", "list" ]
Python Django not running
39,971,084
<p>Firstly I installed Django using pip in my "CentOS" operating system. After that I performed these steps using terminal.</p> <pre><code>django-admin startproject mysite </code></pre> <p>a folder mysite is created with :</p> <pre><code>manage.py and another subfolder mysite </code></pre> <p>Then simply I just use...
-1
2016-10-11T05:40:28Z
39,973,895
<p>This right here:</p> <pre><code>'/home/username/Desktop/prog/django/mysite/webapp/urls.pyc'&gt;' does not appear to have any patterns in it. </code></pre> <p>Check <code>urls.py</code></p> <p>I can't tell you exactly what to check without seeing the file, but here is a sample <code>urls.py</code>:</p> <pre><code...
0
2016-10-11T09:08:43Z
[ "python", "django" ]
How to enable "View State" option for ExecuteScript processor in NiFi UI?
39,971,249
<p>I am using NiFi <strong>ExecuteScript</strong> with python. In the python script I add/modify state of the processor</p> <pre><code>stateManager = context.getStateManager() stateManager.setState(newmap, Scope.LOCAL) </code></pre> <p>Is there anyway I can view/clear the processor state in NiFi web ui? </p> <p>Some...
0
2016-10-11T06:01:59Z
39,977,840
<p>Most processors that store state have an annotation on them @Stateful which indicates to the framework that they store state, and is used to enabled features such as the "View State". </p> <p>Since ExecuteScript doesn't store state itself it doesn't currently have this annotation, but since scripts can access the s...
2
2016-10-11T13:00:13Z
[ "python", "state", "apache-nifi" ]
Prompt for Name without any Variables
39,971,304
<p>How would go about writing this program without any variables? It's super simple exercise from the book "57 Programming Exercises" but other than using importing sys and using the command line argv I don't see how to go about it. I think the intent is for it not to use sys.argv. Thank you.</p> <pre><code>inp = raw_...
0
2016-10-11T06:07:27Z
39,971,333
<p>This will do the trick:</p> <pre><code> print "Hello, {} nice to meet you!".format(raw_input("What is your name? ")) </code></pre> <p><a href="https://docs.python.org/2/library/string.html#format-string-syntax" rel="nofollow">format</a> is just a way of inserting arguments in a string, similar to</p> <pre><code>p...
5
2016-10-11T06:10:01Z
[ "python" ]
selenium fails to iterate on elements
39,971,323
<p>Im trying to translate user comments from tripadvisor.<br> My code :- </p> <p>1.]Selects only portuguese comments( from language dropdown), </p> <p>2.]Then expands each of the comments, </p> <p>3.]Then saves all these expanded comments in a list</p> <p>4.]Then translates them into english &amp; prints on screen<...
1
2016-10-11T06:08:56Z
39,974,090
<p>I have changed your code and now it's working.</p> <pre><code>from selenium import webdriver from selenium.webdriver.common.by import By import time from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC driver = webdriver.Chrome("./chromedriver.exe...
1
2016-10-11T09:20:38Z
[ "python", "selenium", "web-scraping" ]
How do I implement the Triplet Loss in Keras?
39,971,597
<p>I'm trying to implement Google's Facenet paper:</p> <p><img src="http://i.stack.imgur.com/RT3TZ.png" alt="enter image description here"></p> <p>First of all, is it possible to implement this paper using the Sequential API of Keras or should I go for the Graph API? </p> <p>In either case, could you please tell me ...
1
2016-10-11T06:33:36Z
40,004,986
<p><a href="https://github.com/fchollet/keras/issues/369" rel="nofollow">This issue</a> explains how to create a custom objective (loss) in Keras:</p> <pre><code>def dummy_objective(y_true, y_pred): return 0.5 # your implem of tripletLoss here model.compile(loss=dummy_objective, optimizer='adadelta') </code></pr...
1
2016-10-12T17:39:06Z
[ "python", "keras" ]
Lambda function Python3 no change in output
39,971,604
<pre><code>def salary_sort(thing): def importantparts(thing): for i in range(1, len(thing)): a=thing[i].split(':') output = (a[1],a[0],a[8]) sortedlist = sorted(output, key = lambda item: item[2], reverse=True) print(sortedlist) return importantparts(thing...
0
2016-10-11T06:34:37Z
39,972,159
<p>The problem is that you sort <strong>individual</strong> elements (meaning <code>['Putie', 'Arthur', '126000']</code>), based on the salary value, and not the whole array.</p> <p>Also, since you want to sort the salaries, you have to cast them to <code>int</code>, otherwise alphabetical sort is going to be used.</p...
0
2016-10-11T07:17:00Z
[ "python", "sorting", "lambda" ]
Lambda function Python3 no change in output
39,971,604
<pre><code>def salary_sort(thing): def importantparts(thing): for i in range(1, len(thing)): a=thing[i].split(':') output = (a[1],a[0],a[8]) sortedlist = sorted(output, key = lambda item: item[2], reverse=True) print(sortedlist) return importantparts(thing...
0
2016-10-11T06:34:37Z
39,972,163
<p>There are a number of issues with your code, but the key one is that you are sorting <em>each row</em> as you create it, rather than the list of lists.</p> <p>Also:</p> <ul> <li><p><code>importantparts()</code> doesn't return anything (so <code>salarysort()</code> returns None). </p></li> <li><p>You need to cast ...
2
2016-10-11T07:17:15Z
[ "python", "sorting", "lambda" ]
Lambda function Python3 no change in output
39,971,604
<pre><code>def salary_sort(thing): def importantparts(thing): for i in range(1, len(thing)): a=thing[i].split(':') output = (a[1],a[0],a[8]) sortedlist = sorted(output, key = lambda item: item[2], reverse=True) print(sortedlist) return importantparts(thing...
0
2016-10-11T06:34:37Z
39,972,253
<p>You main problem is that you reset the <code>output</code> sequence with each new <em>line</em> instead of first accumulating the data and then sorting. Another problem is that your external function declared an inner one and called it, but the inner one did not return anything. Finally, if you sort strings without ...
1
2016-10-11T07:24:23Z
[ "python", "sorting", "lambda" ]
How to show yticks on the plot/graph (not on y-axis). Show yticks near points
39,971,625
<p>I have a plot with a simple line. For the moment, I set <strong>yticks</strong> as invisible. <a href="http://i.stack.imgur.com/EaW9w.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/EaW9w.jpg" alt="enter image description here"></a></p> <p>Here is the code for the graph:</p> <pre><code>import matplotlib.pyp...
2
2016-10-11T06:35:49Z
39,995,065
<p>You can use <code>plt.text()</code> to annotate text onto an axis. By iterating over your x,y points you can place a label at each marker. For example: </p> <pre><code>import matplotlib.pyplot as plt x = [1, 2, 3, 4, 5] y = [1, 1.5, 2, 2.5, 3] fig, ax = plt.subplots(figsize=(15,10)) plt.plot(x, y, 'ko-') plt.xlab...
2
2016-10-12T09:25:24Z
[ "python", "matplotlib", "linechart" ]
Import mssql spatial fields into geopandas/shapely geometry
39,971,629
<p>I cannot seem to be able to directly import mssql spatial fields into geopandas. I can import normal mssql tables into pandas with Pymssql without problems, but I cannot figure out a way to import the spatial fields into shapely geometry. I know that the OGR driver for mssql should be able to handle it, but I'm not ...
0
2016-10-11T06:36:05Z
39,973,045
<p>I figured it out by properly querying the sql database table and converting the wkt string to shapely geometry via the loads function in shapely.wkt.</p> <p>I'm no programmer, so bear that in mind with the organization of the function. The function can import mssql tables with or without GIS geometry.</p> <pre><co...
0
2016-10-11T08:16:33Z
[ "python", "sql-server", "shapely", "geopandas" ]
Scrapy not able to get image url and also not able to download images
39,971,674
<p>I have tried every search result in google and stack overflow solution but i am not able to get the solution. I am creating a scrapy to extract images please find the code below</p> <p>My items.py </p> <pre><code>class MyntraItem(scrapy.Item): product_urls=scrapy.Field() files=scrapy.Field() image_urls...
0
2016-10-11T06:39:47Z
39,973,380
<p>By default, <code>FilesPipeline</code> expects file URLs to be available from the value of <a href="https://docs.scrapy.org/en/latest/topics/media-pipeline.html#usage-example" rel="nofollow">an item's <code>"file_urls"</code> key</a>.</p> <blockquote> <p>(...) if a spider returns a dict with the URLs key (<code>"...
0
2016-10-11T08:37:28Z
[ "python", "image", "scrapy", "pipeline" ]
Scrapy not able to get image url and also not able to download images
39,971,674
<p>I have tried every search result in google and stack overflow solution but i am not able to get the solution. I am creating a scrapy to extract images please find the code below</p> <p>My items.py </p> <pre><code>class MyntraItem(scrapy.Item): product_urls=scrapy.Field() files=scrapy.Field() image_urls...
0
2016-10-11T06:39:47Z
39,985,109
<p>Use <strong>ImagesPipeline</strong> instead, and extract the images using <strong>regex</strong>.</p> <p>In My first.py</p> <pre><code>item['files']= re.findall('front":\{"path":"(.+?)"', response.body) </code></pre> <p>In settings.py</p> <pre><code>IMAGES_STORE = '/home/swapnil/Desktop/AI/myntra/' ITEM_PIPELIN...
0
2016-10-11T19:24:46Z
[ "python", "image", "scrapy", "pipeline" ]
How to count the number of times a word appears in each row of a csv file, in python
39,971,779
<p>I have a csv document in which each row contains a string of words. For each row, I want to know how many times each words appears in that row, how would I go about this?</p> <p>Thanks</p>
-3
2016-10-11T06:49:12Z
39,971,953
<p>Move the row to a list, make it unique and count every object in list,</p> <p>For converting to list <a href="http://stackoverflow.com/questions/7844118/how-to-convert-comma-delimited-string-to-list-in-python">Check this</a></p> <p>if result is more than one, print it.</p> <p>Considered this as list <code>['a','b...
0
2016-10-11T07:01:59Z
[ "python", "csv" ]
How to count the number of times a word appears in each row of a csv file, in python
39,971,779
<p>I have a csv document in which each row contains a string of words. For each row, I want to know how many times each words appears in that row, how would I go about this?</p> <p>Thanks</p>
-3
2016-10-11T06:49:12Z
39,971,991
<p>Use <code>collections.Counter</code>:</p> <pre><code>from collections import Counter z = ['a', 'b', 'c', 'd', 'a'] u = Counter(z) print(u['a']) # 2 print(u['b']) # 1 </code></pre>
0
2016-10-11T07:05:10Z
[ "python", "csv" ]
ImportError: No module named cv2. But running apt-get command shows that python-opencv is already installed
39,971,846
<p>Even though I tried out the solutions given for the same type of questions concerning the same error, nothing worked. When I try to run the script it gives this import error. But surprisingly when I try </p> <blockquote> <p>apt-get install python-opencv </p> </blockquote> <p>I get this message:</p> <blockquote>...
0
2016-10-11T06:53:59Z
39,973,217
<p>Most likely the library python-opencv is not installed in the default directory. That is why your interpreter cannot find it.</p> <p>When dealing with python projects it's recommended to use virtualenv. It will allow you to create separate python environments and not mess them up. Then install pip and use it to ins...
0
2016-10-11T08:27:25Z
[ "python", "opencv", "importerror" ]
What are variable annotations in Python 3.6?
39,971,929
<p>Python 3.6 is about to be released. <a href="https://www.python.org/dev/peps/pep-0494/">PEP 494 -- Python 3.6 Release Schedule</a> mentions the end of December, so I went through <a href="https://docs.python.org/3.6/whatsnew/3.6.html">What's New in Python 3.6</a> to see they mention the <em>variable annotations</em>...
15
2016-10-11T07:00:15Z
39,972,031
<p>Everything between <code>:</code> and the <code>=</code> is a type hint, so <code>primes</code> is indeed defined as <code>List[int]</code>, and initially set to an empty list (and <code>stats</code> is an empty dictionary initially, defined as <code>Dict[str, int]</code>).</p> <p><code>List[int]</code> and <code>D...
15
2016-10-11T07:08:33Z
[ "python", "python-3.x", "annotations", "type-hinting", "python-3.6" ]
What are variable annotations in Python 3.6?
39,971,929
<p>Python 3.6 is about to be released. <a href="https://www.python.org/dev/peps/pep-0494/">PEP 494 -- Python 3.6 Release Schedule</a> mentions the end of December, so I went through <a href="https://docs.python.org/3.6/whatsnew/3.6.html">What's New in Python 3.6</a> to see they mention the <em>variable annotations</em>...
15
2016-10-11T07:00:15Z
39,973,133
<p>Indeed, variable annotations are just the next step from <code># type</code> comments as they where defined in <code>PEP 484</code>; the rationale behind this change is highlighted in the <a href="https://www.python.org/dev/peps/pep-0526/#rationale">respective PEP section</a>. So, instead of hinting the type with:</...
11
2016-10-11T08:21:24Z
[ "python", "python-3.x", "annotations", "type-hinting", "python-3.6" ]
Subdomain Django Settings Conflict
39,972,134
<p>I have a site with a set of sub-domains. When I visit one of those sub-domains including the actual domain, it <strong>sometimes</strong> shows an Internal Server Error on the browser and when I check the apache error.log it tells that it throws an <strong>ImportError</strong> :</p> <pre><code> [Tue Oct 11 06:47...
0
2016-10-11T07:15:34Z
39,975,023
<p>Don't use:</p> <pre><code>os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings") </code></pre> <p>use:</p> <pre><code>os.environ["DJANGO_SETTINGS_MODULE"] = "project.settings" </code></pre> <p>Similarly for the other <code>wsgi.py</code> file.</p> <p>This is mentioned in the Django documentation fo...
1
2016-10-11T10:12:40Z
[ "python", "django", "apache", "digital-ocean", "ubuntu-16.04" ]
How to update pandas when python is installed as part of ArcGIS10.4, or another solution
39,972,261
<p>I recently installed ArcGIS10.4 and now when I run python 2.7 programs using Idle (for purposes unrelated to ArcGIS) it uses the version of python attached to ArcGIS.</p> <p>One of the programs I wrote needs an updated version of the pandas module. When I try to update the pandas module in this verion of python (by...
0
2016-10-11T07:25:02Z
39,972,738
<p>I reinstalled python again directly from python.org and then installed pandas which seems to work. </p> <p>I guess this might stop the ArcMap version of python working properly but since I'm not using python with ArcMap at the moment it's not a big problem.</p>
0
2016-10-11T07:57:09Z
[ "python", "pandas", "upgrade", "arcmap" ]
pydal requires pymongo version >= 3.0, found '2.2.1'
39,972,326
<p><strong>Web2py Error:</strong> </p> <pre><code> &lt;type 'exceptions.RuntimeError'&gt; Failure to connect, tried 5 times: Traceback (most recent call last): File "/Applications/web2py.app/Contents/Resources/gluon/packages/dal/pydal/base.py", line 446, in __init__ File "/Applications/web2py.app/Contents/Reso...
0
2016-10-11T07:29:51Z
39,980,493
<p>It looks like you are running the OSX binary version of web2py, which comes with its own Python 2 interpreter (currently, web2py runs under Python 2 only), so it will ignore your system's Python installation (and web2py wouldn't run under your Python 3 installation anyway). The web2py binary version does not come wi...
0
2016-10-11T15:06:33Z
[ "python", "web2py", "pydal" ]
Extracting DBN last hidden layer, Theano, Python
39,972,433
<p>I am new to Theano and I have been searching for this question about 2 months. I am using the code provided in this site: <a href="http://deeplearning.net/tutorial/DBN.html" rel="nofollow">http://deeplearning.net/tutorial/DBN.html</a></p> <p>I have a 4 layer Deep Belief Network, actually with 2 hidden layers. As f...
0
2016-10-11T07:37:39Z
39,973,007
<p>DBM is constructed in layer wise of multiple RBM. quick review to the code in the provided link you should look to the appended layer in the DBM and print the output result of this layer when you are providing the input in these following models. </p> <pre><code> sigmoid_layer = HiddenLayer(rng=numpy_rng, ...
0
2016-10-11T08:14:21Z
[ "python", "theano" ]
ImportError: No module named 'bs4' in django only
39,972,580
<p>The same question has been asked a number of times but I couldn't find the solution.</p> <p>After I install a package using pip, I am able to import it in python console or python file and it works as expected. The same package when I try to include in django, it gives <code>import error</code>. Do I need to modify...
-2
2016-10-11T07:46:34Z
39,972,703
<p>You don't show either the code of your site or the command you ran (and the URL you entered, if any) to trigger this issue. There's almost certainly some difference between the Python environment on the command line and that operating in Django.</p> <p>Are you using virtual environments? If so, dependencies should ...
2
2016-10-11T07:54:37Z
[ "python", "django" ]
ElasticSearch indexing with 450K documents - performance
39,972,655
<p>We have ElasticSearch (1.5) on AWS (t2.micro, 2 instances with 10GB SSD storage each) and a MySQL with ~450K fairly big/complex entities. </p> <p>I'm using python to read from MySql, serialize to JSON and PUT to ElasticSearch. There are 10 threads working simultaneously, each PUTing bulk of 1000 documents at the ti...
0
2016-10-11T07:51:09Z
40,002,481
<p>I suspect EC2 is your bottleneck. Based on <a href="http://stackoverflow.com/questions/28984106/whats-is-cpu-credit-balance-in-ec2">the way burstable instances are allocated CPU</a>, a <code>t2.micro</code> accrues 6 cpu credits an hour. </p> <p>So in your first hour up, your Elasticsearch nodes will be able to r...
1
2016-10-12T15:25:42Z
[ "python", "mysql", "amazon-web-services", "elasticsearch" ]
Quick method to make 2 dimensional sparse arrays from a master data array
39,972,729
<p>I will simplify my problem with an example of what I would like done (the actual data I am working with is massive).</p> <p>The solution to my problem would be simple if there was a 3 dimensional sparse array object that could be fed the x,y,z coordinates along with the data to be stored. Note that I will have memo...
1
2016-10-11T07:56:37Z
39,973,056
<p>Here's an alternative approach -</p> <pre><code>out_shp = (10,10) # (1536, 32768) for your actual case out_dic = {} for i in np.unique(arr[:,0]): RCD = arr[arr[:,0] == i,1:] out_dic[i] = coo_matrix((RCD[:,2],(RCD[:,0],RCD[:,1])), shape=out_shp) </code></pre> <p>Sample input, output -</p> <pre><code>In [8...
0
2016-10-11T08:17:07Z
[ "python", "numpy", "indexing", "sparse-matrix" ]
Python xlsxwriter: How do I write a formula that references a different sheet
39,972,739
<p>I'm trying to add a excel file that includes a formula referencing a different sheet.</p> <p>In this example, I try to copy the word "world" from sheet 2 to sheet 1.</p> <pre><code>import xlsxwriter workbook = xlsxwriter.Workbook('hello.xlsx') sheet1 = workbook.add_worksheet(name='Sheet 1') sheet2 = workbook.add_...
1
2016-10-11T07:57:14Z
39,973,378
<p>The formula needs to be in the US Excel syntax, like the following (note <code>!</code> not <code>.</code>):</p> <pre><code>sheet1.write_formula('D3', "='Sheet 2'!C3") </code></pre> <p>See the <a href="https://xlsxwriter.readthedocs.io/working_with_formulas.html" rel="nofollow">Working with Formulas</a> section of...
1
2016-10-11T08:37:23Z
[ "python", "python-3.x", "excel-formula", "openoffice-calc", "xlsxwriter" ]
How to average over the output values of a function
39,972,751
<p>I am relatively new to python so I apologize for any unconventionality in my code. I have a function which returns some values. I want to repeat this function n times and get the average over the output values for the n iterations (possibly without defining a new function). How can this be done? For example:</p> ...
-1
2016-10-11T07:58:29Z
39,972,819
<p>Is that how you want it, you need to assign the return value to a variable to access it later:</p> <pre><code>for i in range(n): v_min2 = flip_coin(coins) print v_min2 </code></pre> <p>If you want average of everytime you call the function, you can simply do:</p> <pre><code>average_list = [] for i in range(10...
1
2016-10-11T08:02:15Z
[ "python", "iteration", "average" ]
How to average over the output values of a function
39,972,751
<p>I am relatively new to python so I apologize for any unconventionality in my code. I have a function which returns some values. I want to repeat this function n times and get the average over the output values for the n iterations (possibly without defining a new function). How can this be done? For example:</p> ...
-1
2016-10-11T07:58:29Z
39,973,058
<p>You are not assigning function call result. First collect all function calls so we can calculate average on them</p> <pre><code>v_min_list = [flip_coin(coins) for i in range(n)] </code></pre> <p>then we can find average with this answer <a href="http://stackoverflow.com/questions/9039961/finding-the-average-of-a-l...
0
2016-10-11T08:17:12Z
[ "python", "iteration", "average" ]
Why is my function looping python
39,972,771
<p>Weird issue I know that a function is being called twice some how but I dont know where or why its happening.</p> <p>Heres my code:</p> <pre><code> 8 def getAccessSecretName(): 9 access_key = raw_input("Enter Access Key: ") 10 secret_key = raw_input("Enter Secret Key: ") 11 yourName = ...
-2
2016-10-11T07:59:41Z
39,987,910
<p>What I thought was a problem in the loop was a issue with how I thought variables in python get passed to other functions.</p> <p>looks like doing this </p> <pre><code>71: access_key, secret_key, yourName = getAccessSecretName() </code></pre> <p>Doesnt mean make ^ variable values available from the function of ge...
0
2016-10-11T22:45:15Z
[ "python", "loops" ]
Python: Compare elements in two list by pair
39,972,828
<p>I am so sorry for asking so silly question. So I have got two lists(columns) for instance:</p> <pre><code>In: a= [0.0,1.0,2.0,3.0,4.0] b= [1.0,2.0,3.0,5.0,6.0] zp = list(zip(a,b)) #And I zipped it for better view. for i in zp: print (i) Out: (0.0, 1.0) (1.0, 2.0) (2.0, 3.0) (3.0, 5.0) (4.0, 6.0) </code></pre> ...
0
2016-10-11T08:02:39Z
39,972,887
<p>The initial zip for better view is not completely necessary. </p> <p>You could simply <code>zip</code> a slice of <code>a</code> starting from index 1 with <code>b</code>, and then compare the items using a <code>for</code> loop:</p> <pre><code>a = [0.0,1.0,2.0,3.0,4.0] b = [1.0,2.0,3.0,5.0,6.0] for i, j in zip(a...
4
2016-10-11T08:07:10Z
[ "python", "list", "compare" ]
Python: Compare elements in two list by pair
39,972,828
<p>I am so sorry for asking so silly question. So I have got two lists(columns) for instance:</p> <pre><code>In: a= [0.0,1.0,2.0,3.0,4.0] b= [1.0,2.0,3.0,5.0,6.0] zp = list(zip(a,b)) #And I zipped it for better view. for i in zp: print (i) Out: (0.0, 1.0) (1.0, 2.0) (2.0, 3.0) (3.0, 5.0) (4.0, 6.0) </code></pre> ...
0
2016-10-11T08:02:39Z
39,973,145
<p>index variant without zip and enumerate</p> <pre><code>a = [0.0,1.0,2.0,3.0,4.0] b = [1.0,2.0,3.0,5.0,6.0] for i in a: if a.index(i) and i != b[a.index(i)-1]: print "{0} &gt; {1}".format(i, b[a.index(i)-1]) </code></pre>
1
2016-10-11T08:21:56Z
[ "python", "list", "compare" ]
Python Pandas: Inconsistent behaviour of boolean indexing on a Series using the len() method
39,972,874
<p>I have a Series of strings and I need to apply boolean indexing using <code>len()</code> on it.</p> <p>In one case it works, in another case it does not:</p> <p>The working case is a <code>groupby</code> on a dataframe, followed by a <code>unique()</code> on the resulting Series and a <code>apply(str)</code> to ch...
1
2016-10-11T08:06:12Z
39,972,902
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.len.html" rel="nofollow"><code>str.len</code></a>, because need length of each value of <code>Series</code>:</p> <pre><code>ss = pd.Series(['a','b','cc','dd','eeee','ff','ggg']) print (ss.str.len()) 0 1 1 1 2 ...
2
2016-10-11T08:07:45Z
[ "python", "python-2.7", "pandas" ]
Using Scherrer equation for calculating the grain size
39,973,073
<p>I'm trying to calculate the grain size by Scherrer equation but I have stuck in FWHM. </p> <pre><code>import numpy as np #import math k = 0.94 wave_length = 1.5406e-10 data = np.genfromtxt("G3.txt") indice = np.argmax(data[:,1]) peak = (data[indice, :]) #D = (k*wave_length) / (beta*cos((math.radian(theta)) </cod...
0
2016-10-11T08:18:07Z
39,977,103
<p>Here is a working example, assuming you have a normal distribution. I run this in a Jupyter console, so in case you don't, you have to skip the "magic line" (<code>%matplotlib notebook</code>) and add <code>plt.show()</code> at the very end.</p> <pre><code>%matplotlib notebook import matplotlib.pyplot as plt from s...
3
2016-10-11T12:19:21Z
[ "python", "numpy", "physics" ]
Using Scherrer equation for calculating the grain size
39,973,073
<p>I'm trying to calculate the grain size by Scherrer equation but I have stuck in FWHM. </p> <pre><code>import numpy as np #import math k = 0.94 wave_length = 1.5406e-10 data = np.genfromtxt("G3.txt") indice = np.argmax(data[:,1]) peak = (data[indice, :]) #D = (k*wave_length) / (beta*cos((math.radian(theta)) </cod...
0
2016-10-11T08:18:07Z
40,049,528
<p>I'm sorry for sharing this as an answer but comments does not provide me upload a picture to clarify the problem. So I've illustrated the problem with an image below (BTW, I can't edit or delete my comments which I wrote reluctantly). I got this graph when I run your code <a href="https://i.stack.imgur.com/wyIVm.png...
0
2016-10-14T18:08:36Z
[ "python", "numpy", "physics" ]
Using Scherrer equation for calculating the grain size
39,973,073
<p>I'm trying to calculate the grain size by Scherrer equation but I have stuck in FWHM. </p> <pre><code>import numpy as np #import math k = 0.94 wave_length = 1.5406e-10 data = np.genfromtxt("G3.txt") indice = np.argmax(data[:,1]) peak = (data[indice, :]) #D = (k*wave_length) / (beta*cos((math.radian(theta)) </cod...
0
2016-10-11T08:18:07Z
40,065,417
<p>I don't know how to solve this problem in python (at least for this moment). So I made it in Matlab. </p> <pre><code> clear all clc A = dlmread('YOUR DATAS'); %Firstly add to path plot(A(:,1),A(:,2)) %Plotting the graph hold on min_peak = input('Just write a value that is higher than ...
0
2016-10-15T23:53:06Z
[ "python", "numpy", "physics" ]
How to show warning using Python tornado
39,973,273
<p>Is there a way to show a warning to the user and just continue with the called function?</p> <p>All I can find in tornado is the HTTPError. Is there anything like this to show a warning?</p> <p>Current snippet:</p> <pre><code>if warning_bool: warning_text = "Warning! You can still continue though..." rais...
0
2016-10-11T08:31:22Z
39,986,329
<p>If you want to continue with your processing you will not want to raise an error. That has a number of effects depending on your setup. Typically raising an error will set the status to something other than 200, which probably isn't what you want. It will generally trip whatever exception logging you have (in our ca...
1
2016-10-11T20:38:39Z
[ "python", "tornado" ]
Complicated python regex
39,973,353
<p>I have multiple lines like this:</p> <pre><code>EWSR1{ENST00000397938}:r.1_1364_FLI1{ENST00000429175}:r.1046_3051 EML4{ENST00000318522}:r.1_929_EML4{ENST00000318522}:r.903+188_903+220_ALK{ENST00000389048}:r.4080_6220 FUS{ENST00000254108}:r.1_(608)_FUS{ENST00000254108}:r.(819)_937_DDIT3{ENST00000547303}:r.76_872 TCF...
2
2016-10-11T08:36:08Z
39,973,649
<p>First split on <code>(?&lt;=\d|\)|\?)_(?=[a-z])</code> and you'll end up with the <em>records</em> separated, like this:</p> <pre><code>EWSR1{ENST00000397938}:r.1_1364 FLI1{ENST00000429175}:r.1046_3051 EML4{ENST00000318522}:r.1_929 EML4{ENST00000318522}:r.903+188_903+220 ALK{ENST00000389048}:r.4080_6220 FUS{ENST000...
3
2016-10-11T08:55:33Z
[ "python", "regex", "python-3.x" ]
Complicated python regex
39,973,353
<p>I have multiple lines like this:</p> <pre><code>EWSR1{ENST00000397938}:r.1_1364_FLI1{ENST00000429175}:r.1046_3051 EML4{ENST00000318522}:r.1_929_EML4{ENST00000318522}:r.903+188_903+220_ALK{ENST00000389048}:r.4080_6220 FUS{ENST00000254108}:r.1_(608)_FUS{ENST00000254108}:r.(819)_937_DDIT3{ENST00000547303}:r.76_872 TCF...
2
2016-10-11T08:36:08Z
39,974,363
<p>Here is a one regex solution, that might not be so elegant, but working:</p> <pre><code>((?&lt;![^_])ins\d+)_|([a-zA-Z]+[0-9]*)\{([^{}]*)\}:r\.([-()?+\d]+)?(?:_([-()?+\d]+))? </code></pre> <p>See the <a href="https://regex101.com/r/21roQD/4" rel="nofollow">regex demo</a></p> <p><em>Details</em>:</p> <ul> <li><co...
3
2016-10-11T09:35:24Z
[ "python", "regex", "python-3.x" ]
Complicated python regex
39,973,353
<p>I have multiple lines like this:</p> <pre><code>EWSR1{ENST00000397938}:r.1_1364_FLI1{ENST00000429175}:r.1046_3051 EML4{ENST00000318522}:r.1_929_EML4{ENST00000318522}:r.903+188_903+220_ALK{ENST00000389048}:r.4080_6220 FUS{ENST00000254108}:r.1_(608)_FUS{ENST00000254108}:r.(819)_937_DDIT3{ENST00000547303}:r.76_872 TCF...
2
2016-10-11T08:36:08Z
39,989,152
<p>First split with "_(?=[a-zA-Z]".Then split whith "[}{:._r]"</p> <pre><code>import re with open('file.txt') as f: for l in f: print "\n".join(map(lambda x:" ".join(re.split(r'[}{:._r]',x)),re.split(r'_(?=[a-zA-Z])',l.strip('\n'))))+'\n' </code></pre>
1
2016-10-12T01:27:11Z
[ "python", "regex", "python-3.x" ]
How to pass a list of lists through a for loop in Python?
39,973,360
<p>I have a list of lists :</p> <pre><code>sample = [['TTTT', 'CCCZ'], ['ATTA', 'CZZC']] count = [[4,3],[4,2]] correctionfactor = [[1.33, 1.5],[1.33,2]] </code></pre> <p>I calculate frequency of each character (pi), square it and then sum (and then I calculate het = 1 - sum). </p> <pre><code>The desired output [[1,...
4
2016-10-11T08:36:43Z
39,974,974
<p>I'm not completely clear on how you want to handle the 'Z' items in your data, but this code replicates the output for the sample data in <a href="https://eval.in/658468" rel="nofollow">https://eval.in/658468</a></p> <pre><code>from __future__ import division bases = set('ACGT') #sample = [['TTTT', 'CCCZ'], ['ATTA...
3
2016-10-11T10:10:30Z
[ "python", "list", "for-loop", "division" ]
Prime numbers in a given range using Sieve of Eratosthenes
39,973,477
<p>I am trying to print prime numbers less than 'n'.The code is below:</p> <pre><code>def prime_numbers(n): A=[1 for i in range(n+1)] for i in range(2,int(sqrt(n))): if A[i]==1: for j in range(i*2,n,i): A[j]=0 for i in range(n): if A[i]: print(i) </co...
0
2016-10-11T08:43:34Z
39,973,525
<p>The end point in a <code>range()</code> is not included. Since <code>sqrt(10)</code> is <code>3.1623</code>, your <code>range()</code> loops to 2 and no further, and the multiples of 3 are not removed from your list. Your code works for 100, because it doesn't matter if you test for multiples 10 (those are already c...
2
2016-10-11T08:46:53Z
[ "python", "python-3.x", "primes" ]
python: how to get list length in list generator expression?
39,973,542
<p>Maybe like this (just a pseudocode) </p> <pre><code>li = [1,2,3,4,5,6] a = [d for d in li if self.length&lt;3] print a [1,2] </code></pre> <p>What is a pythonic way to do that thing? </p>
-1
2016-10-11T08:48:53Z
39,973,729
<p>You can use <code>itertools.count()</code> to keep track of how many elements you have used:</p> <pre><code>from itertools import count li = [1,2,3,4,5,6] c = count(1) # initialize to 1 a = [d for d in li if next(c) &lt; 3] # everytime you add an element print (a) # in the comprehe...
3
2016-10-11T08:59:35Z
[ "python" ]
Python IDLE/Terminal return back after error
39,973,597
<p>When reading a book or just coding on terminal/IDLE it's common to make typo, forgot brace or comma etc. After I got error and all what I wrote before is lost. Then I have to write down code again.. Is there any way/option to return back all what write before and just edit mistake and continue to code?</p>
1
2016-10-11T08:52:02Z
39,973,715
<p>In Idle (at least my version, Python 2.7.10 on windows), you can simply copy paste your code. In the python interpreter, you can't afaik, however you can use the up/down arrow keys to recall lines you previously "submitted" (i.e. typed and pressed enter).</p>
0
2016-10-11T08:58:46Z
[ "python", "terminal", "edit", "python-idle", "undo" ]
Python IDLE/Terminal return back after error
39,973,597
<p>When reading a book or just coding on terminal/IDLE it's common to make typo, forgot brace or comma etc. After I got error and all what I wrote before is lost. Then I have to write down code again.. Is there any way/option to return back all what write before and just edit mistake and continue to code?</p>
1
2016-10-11T08:52:02Z
39,974,277
<p>If I understood correctly, IDLE is a GUI (graphical user interface - a visual representation of a program rather just through text) made to have a bit more features for programming in Python. You can use IDLE interactively, like in Terminal (a.k.a command line), or use it to write your script rather than in a separa...
0
2016-10-11T09:31:27Z
[ "python", "terminal", "edit", "python-idle", "undo" ]
Python IDLE/Terminal return back after error
39,973,597
<p>When reading a book or just coding on terminal/IDLE it's common to make typo, forgot brace or comma etc. After I got error and all what I wrote before is lost. Then I have to write down code again.. Is there any way/option to return back all what write before and just edit mistake and continue to code?</p>
1
2016-10-11T08:52:02Z
39,990,408
<p>IDLE's Shell window is statement rather that line oriented. One can edit any line of a statement before submitting it for execution. After executing, one may recall any statement by either a) placing the cursor anywhere on the statement and hitting Enter, or b) using the history-next and history-prev actions. On ...
0
2016-10-12T04:12:57Z
[ "python", "terminal", "edit", "python-idle", "undo" ]
Python socket programming and LED interfacing
39,973,653
<p>I'm trying to write socket programming in python. Whenever client sends message to server, LED should start blinking. I'm running server program on Raspberry pi and client on PC.</p> <p>Here is the code of server which is running on my Pi.</p> <pre><code>#!/usr/bin/python # This is server.py file impor...
2
2016-10-11T08:55:40Z
39,974,480
<p>Try this on your PC or Raspberry and then edit accordingly:</p> <pre><code>#!/usr/bin/python # This is server.py file import socket # Import socket module def led_blink(msg): print "got msg", msg # Debug msg s = socket.socket() # Create a socket object host = ...
1
2016-10-11T09:42:20Z
[ "python", "raspberry-pi2" ]
Python socket programming and LED interfacing
39,973,653
<p>I'm trying to write socket programming in python. Whenever client sends message to server, LED should start blinking. I'm running server program on Raspberry pi and client on PC.</p> <p>Here is the code of server which is running on my Pi.</p> <pre><code>#!/usr/bin/python # This is server.py file impor...
2
2016-10-11T08:55:40Z
39,974,543
<p>You are comparing a string <code>"10"</code> with a number <code>10</code>. Change your server code to : </p> <pre><code>msg1 = "10" </code></pre>
0
2016-10-11T09:45:31Z
[ "python", "raspberry-pi2" ]
Name Error: name 'QFileDialog' is not defined
39,973,665
<p>I am working on coursework for computer science and can't work out why the piece of code isn't working. I am trying to connect a button that I've created in PyQt4 so that when it is pressed it shows a directory dialogue:</p> <pre><code>self.Browse_Button_1 = QtGui.QToolButton(self.tab) self.Browse_Button_1.setG...
1
2016-10-11T08:56:25Z
39,974,332
<p><code>QFileDialog</code> is in the <a href="http://doc.qt.io/qt-4.8/qfiledialog.html" rel="nofollow">QtGui module</a>, so you need to append that to beginning of your line, e.g.:</p> <pre><code>file = str(QtGui.QFileDialog.getExistingDirectory(self, "Select Directory")) </code></pre> <p>Alternatively, if you want ...
1
2016-10-11T09:34:00Z
[ "python", "pyqt", "qfiledialog" ]
How do I run two indefinite loops simultaneously, while also changing variables within them?
39,973,911
<p>I'm trying to write a script in Python that records a stream of an IP camera in realtime. It only keeps about a minute worth of recording, constantly overwriting the same files. Whenever an external sensor is triggered I want a variable to be set (event variable) which merges the recording with an extra 30 seconds i...
1
2016-10-11T09:09:35Z
39,975,189
<p>Two processes won't share data, so each process will contain a copy of those global variables, which won't work for you.</p> <p>The best bet is either threading or co-routines(gevent). I"m assuming your logic is -> record 30 seconds, check if event triggered, if so, record another 30 seconds and merge. i.e. I"m ass...
0
2016-10-11T10:22:07Z
[ "python", "multithreading", "ffmpeg" ]
argparse: let the same required argument be positional OR optional
39,974,093
<p>I would like to have a required command line argument passed as a positional argument or an optional argument. For example, I would like the same action be performed from any of the following invocations:</p> <pre><code>prog 10 prog -10 prog -n 10 prog --num 10 </code></pre> <p>Is this possible with argparse?</p>
1
2016-10-11T09:20:55Z
39,982,371
<p>With a mutually exclusive group I can create a reasonable approximation:</p> <p>In an interactive session:</p> <pre><code>In [10]: parser=argparse.ArgumentParser() In [11]: grp=parser.add_mutually_exclusive_group(required=True) In [12]: a=grp.add_argument('pos',nargs='?',type=int,default=0) In [13]: b=grp.add_argu...
0
2016-10-11T16:41:27Z
[ "python", "argparse" ]
Commas in BeautifulSoup csv
39,974,116
<p>I'm trying to output some web scraped information to a csv. When I print it to the screen it comes out as I expect but when I output to a csv it has commas between every character. I'm being dumb, but what am I missing?</p> <p>Here's my relevant python code:</p> <pre><code>list_of_rows = [] for hotel in hotels:...
1
2016-10-11T09:22:09Z
39,974,571
<p>You should supply the data as a nested list, where each sublist represents a single row. </p> <pre><code>data_mod = [[item] for item in list_of_rows] with open("./hotels.csv", "wb") as outfile: writer = csv.writer(outfile) for row in data_mod: writer.writerow(row) # With writerows() being equivale...
0
2016-10-11T09:46:50Z
[ "python", "csv", "beautifulsoup" ]
py-elasticsearch stop printing errors
39,974,132
<p>I am using a py-elasticsearch to query elasticsearch:</p> <pre><code>try: res = es.get(index='unique_names', doc_type='name', id=token, ignore=['404']) except elasticsearch.exceptions.NotFoundError: continue </code></pre> <p>As you can see I use an exception for if the index does not exist, however the errors...
0
2016-10-11T09:23:09Z
39,974,337
<p>The reason this gets printed out is because of <a href="https://github.com/elastic/elasticsearch-py/blob/d4efb81b0695f3d9f64784a35891b732823a9c32/elasticsearch/connection/base.py#L64-L67" rel="nofollow">these lines</a> in the <code>base.py</code> code.</p> <p>Basically, you're ignoring 404 status codes, so the requ...
1
2016-10-11T09:34:18Z
[ "python", "python-3.x", "elasticsearch", "pyelasticsearch" ]
Fetching data from Microsoft Access database using SELECT QUERY WITH WHERE CLAUSE in python
39,974,214
<pre><code>from tkinter import * lg = Tk() lg.state('zoomed') def view(): cus = accno.get() dis = [cus] print(dis) import pypyodbc con=pypyodbc.win_connect_mdb("D:\\customer_details.mdb") cur = con.cursor() q = "select * from cus_details where cus_id = '" + cus + "' " cur.execute(q,dis) re...
0
2016-10-11T09:27:29Z
39,975,075
<p>SQL injection is a serious issue and can ultimately destroy your database. The classic to remember is <a href="https://xkcd.com/327/" rel="nofollow">Bobby Tables</a>. For this reason, it's important to build your queries properly to prevent this; that requires some mechanism to "escape" an input so that it cannot be...
2
2016-10-11T10:15:13Z
[ "python", "ms-access", "select" ]
Tornado how to return error exception?
39,974,225
<p>I want to run a method I know this method doesn't work and I want to get the error returned by the method. </p> <p>This is my code : </p> <pre><code>def is_connect(s): print("ok connection") print(s) ioloop.stop() try: current_job_ready = 0 print("ok1") beanstalk = beanstalkt.Client(hos...
1
2016-10-11T09:28:00Z
39,980,565
<p>Here's where reading the code helps. In beanstalkt 0.6's <code>connect</code>, it creates an IOStream to connect to the server:</p> <p><a href="https://github.com/nephics/beanstalkt/blob/v0.6.0/beanstalkt/beanstalkt.py#L108" rel="nofollow">https://github.com/nephics/beanstalkt/blob/v0.6.0/beanstalkt/beanstalkt.py#L...
1
2016-10-11T15:09:40Z
[ "python", "exception", "tornado", "beanstalk" ]
How to determine which process is using a port in Linux
39,974,335
<p>I'm currently running RethinkDB on its default port, because if I point my browser to <code>localhost:8080</code> I see the RethinkDB web interface:</p> <p><a href="http://i.stack.imgur.com/vtGXl.png" rel="nofollow"><img src="http://i.stack.imgur.com/vtGXl.png" alt="enter image description here"></a></p> <p>I'd li...
0
2016-10-11T09:34:16Z
39,974,485
<pre><code>1. lsof -i:8080 2. kill $(lsof -t -i:8080) or 2 . kill -9 $(lsof -t -i:8080) </code></pre>
1
2016-10-11T09:42:33Z
[ "python", "linux", "rethinkdb" ]
How to determine which process is using a port in Linux
39,974,335
<p>I'm currently running RethinkDB on its default port, because if I point my browser to <code>localhost:8080</code> I see the RethinkDB web interface:</p> <p><a href="http://i.stack.imgur.com/vtGXl.png" rel="nofollow"><img src="http://i.stack.imgur.com/vtGXl.png" alt="enter image description here"></a></p> <p>I'd li...
0
2016-10-11T09:34:16Z
39,974,560
<p>Following <a href="http://stackoverflow.com/users/3929826/klaus-d">Klaus D.</a>'s comment, I determined the process using <code>netstat -nlp</code>:</p> <pre><code>kurt@kurt-ThinkPad:~$ netstat -nlp | grep 8080 (Not all processes could be identified, non-owned process info will not be shown, you would have to be r...
0
2016-10-11T09:46:22Z
[ "python", "linux", "rethinkdb" ]
sympy solve linear equations XOR, NOT
39,974,427
<p>I have 60 equations with 70 variables. all of them are in one list:</p> <p>(x0,x1,...,x239) are sympy symbols</p> <pre><code>list_a = [Xor(Not(x40), Not(x86)), Xor(x41, Not(x87)), ...] </code></pre> <p>and my question is, if it is possible somehow transform this equations to matrix or solved them. I think, that i...
1
2016-10-11T09:39:16Z
39,981,657
<p>A solution to a system of logic expressions is the same as checking SAT for the conjunction (And) of the expressions.</p> <pre><code>In [3]: list_a = [Xor(Not(x40), Not(x86)), Xor(x41, Not(x87))] In [4]: list_a Out[4]: [¬x₄₀ ⊻ ¬x₈₆, x₄₁ ⊻ ¬x₈₇] In [5]: satisfiable(And(*list_a)) Out[5]: {x87...
0
2016-10-11T16:00:25Z
[ "python", "sympy", "equation", "algebra" ]
Python: get the most maximum values from dictionary
39,974,474
<p>I have a dictionary </p> <pre><code>{u'__': 2, u'\u0441\u0442\u0440\u0430\u043d\u0438\u0446\u0430': 1, u'\u041f\u043e\u0447\u0435\u043c\u0443': 1, u'\u041d\u0430\u043c': 1, u'\u043e\u0434\u0438\u043d': 1, u'\u0441\u043e\u0432\u0435\u0442\u0430\u043c\u0438': 1, u'\u041f\u0440\u043e\u0438\u0437\u043d\u0435\u0441\u044...
2
2016-10-11T09:42:06Z
39,974,530
<p><code>max()</code> can only ever return a single value. Use a Counter:</p> <pre><code>from collections import Counter counter = Counter(yourdictionary) print(counter.most_common(10)) </code></pre>
5
2016-10-11T09:44:59Z
[ "python", "dictionary", "encoding" ]
Reducing file size of scatter plot
39,974,576
<p>I am currently trying to reduce the file size of a scatter plot. My code looks like:</p> <pre><code>plt.scatter(a1,b1) plt.savefig('test.ps') </code></pre> <p>where a1,b1 are arrays of size 400,000 or so, and it gives a file size of 7.8MB.</p> <p>I have tried adding </p> <pre><code>plt.rcParams['path.simplify'] ...
1
2016-10-11T09:47:03Z
39,974,868
<p>One approach is to use <code>plot</code> instead of <code>scatter</code> (you can still produce scatter plots using <code>plot</code> by using the <code>'o'</code> argument), and use the <code>rasterized</code> keyword argument, like so:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt a1,b1 = np...
1
2016-10-11T10:04:34Z
[ "python", "matplotlib" ]
Reducing file size of scatter plot
39,974,576
<p>I am currently trying to reduce the file size of a scatter plot. My code looks like:</p> <pre><code>plt.scatter(a1,b1) plt.savefig('test.ps') </code></pre> <p>where a1,b1 are arrays of size 400,000 or so, and it gives a file size of 7.8MB.</p> <p>I have tried adding </p> <pre><code>plt.rcParams['path.simplify'] ...
1
2016-10-11T09:47:03Z
39,974,916
<p>I would think that this is due to the PostScript format, and nothing that can be changed. Let's do the math:</p> <p>7.8MB is something like 7.8 * 1024 * 1024 = 8,178,892.8. Assuming that you have 400,000 points in your scatter plot, that means that your file would assign something like 20 bytes to each point in you...
0
2016-10-11T10:07:13Z
[ "python", "matplotlib" ]
Reducing file size of scatter plot
39,974,576
<p>I am currently trying to reduce the file size of a scatter plot. My code looks like:</p> <pre><code>plt.scatter(a1,b1) plt.savefig('test.ps') </code></pre> <p>where a1,b1 are arrays of size 400,000 or so, and it gives a file size of 7.8MB.</p> <p>I have tried adding </p> <pre><code>plt.rcParams['path.simplify'] ...
1
2016-10-11T09:47:03Z
39,977,232
<p>You could consider using e.g. <code>hexbin</code> -- I particularly like this when you have a dense collection of points, since it better indicates where your data is concentrated. For example:</p> <pre><code>import numpy as np import matplotlib.pylab as pl x = np.random.normal(size=40000) y = np.random.normal(siz...
0
2016-10-11T12:26:49Z
[ "python", "matplotlib" ]
Search all files in a folder
39,974,584
<p>I want to search "word" in many files in a folder. </p> <p>I have already : </p> <pre><code>route=os.listdir("/home/new") for file in route: </code></pre> <p>This does not work : </p> <pre><code> f = open ('' , 'r') for line in f : </code></pre> <p>I tried this :</p> <pre><code>for file in route: f = ope...
-1
2016-10-11T09:47:23Z
39,974,785
<pre><code>for file in filelist: f = open(file,"r") data = f.read() rows = data.split("\n") count = 0 full_data = [] for row in rows: split_row = row.split(",") full_data.append(split_row) for each in full_data: if re.search("word", each) is not None: ...
0
2016-10-11T10:00:25Z
[ "python", "os.system" ]
Search all files in a folder
39,974,584
<p>I want to search "word" in many files in a folder. </p> <p>I have already : </p> <pre><code>route=os.listdir("/home/new") for file in route: </code></pre> <p>This does not work : </p> <pre><code> f = open ('' , 'r') for line in f : </code></pre> <p>I tried this :</p> <pre><code>for file in route: f = ope...
-1
2016-10-11T09:47:23Z
39,974,869
<p>You already have it down mostly:</p> <pre><code>for file in route: f = open(file, 'r') for line in f: if word in line: print(file) break </code></pre>
-1
2016-10-11T10:04:38Z
[ "python", "os.system" ]
Search all files in a folder
39,974,584
<p>I want to search "word" in many files in a folder. </p> <p>I have already : </p> <pre><code>route=os.listdir("/home/new") for file in route: </code></pre> <p>This does not work : </p> <pre><code> f = open ('' , 'r') for line in f : </code></pre> <p>I tried this :</p> <pre><code>for file in route: f = ope...
-1
2016-10-11T09:47:23Z
40,055,530
<p><a href="https://docs.python.org/3/library/os.html#os.listdir" rel="nofollow"><code>os.listdir</code> only returns the file names</a>, not the qualified paths. So to make this work, your <code>open</code> needs to be opening the qualified path (constructed with <code>os.path.join("/home/new", file)</code>), not just...
0
2016-10-15T05:55:43Z
[ "python", "os.system" ]
Search all files in a folder
39,974,584
<p>I want to search "word" in many files in a folder. </p> <p>I have already : </p> <pre><code>route=os.listdir("/home/new") for file in route: </code></pre> <p>This does not work : </p> <pre><code> f = open ('' , 'r') for line in f : </code></pre> <p>I tried this :</p> <pre><code>for file in route: f = ope...
-1
2016-10-11T09:47:23Z
40,055,558
<p>How about something along these lines?</p> <pre><code>import os folderpath = "/.../.../foldertosearch" word = 'giraffe' for(path, dirs, files) in os.walk(folderpath, topdown=True): for filename in files: filepath = os.path.join(path, filename) with open(filepath, 'r') as currentfile: ...
0
2016-10-15T06:00:09Z
[ "python", "os.system" ]
replicate iferror and vlookup in a pandas join
39,974,673
<p>I want to join two dataframes:</p> <pre><code>df1 = pd.DataFrame({'Banner': {0: 'banner1', 1: 'banner2', 2: 'banner3'}, 'Campaign': {0: 'campaign1', 1: 'campaign2', 2: '12345'}, 'Country ': {0: 'de', 1: 'it', 2: 'de'}, 'Date': {0: '1/1/2016', 1: '2/1/2016'...
2
2016-10-11T09:52:59Z
39,975,266
<p>You can use double <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.merge.html" rel="nofollow"><code>merge</code></a> by 3 and 2 keys and then fill not match values by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.combine_first.html" rel="nofollow"><code>combine_fi...
0
2016-10-11T10:26:31Z
[ "python", "pandas", "join", "merge" ]
Automatically play video on Mac
39,974,758
<p>I've the following code in my webpage (Python/Django framework) to enable a video to play in the background.</p> <p><strong>HTML</strong></p> <pre><code>&lt;div class="video-container"&gt; &lt;div class="video-container-bg"&gt; &lt;video playsinline autoplay muted loop poster="{{page.image.url}}" id="b...
0
2016-10-11T09:58:39Z
39,995,436
<p>I've solved this by saving the mp4 files in a lossless state. It now seems to work. I have no idea why</p>
0
2016-10-12T09:42:58Z
[ "python", "css", "django", "osx", "html5-video" ]
Using python's multiprocessing on slurm
39,974,874
<p>I am trying to run some parallel code on slurm, where the different processes do not need to communicate. Naively I used python's slurm package. However, it seems that I am only using the cpu's on one node.</p> <p>For example, if I have 4 nodes with 5 cpu's each, I will only run 5 processes at the same time. How ca...
0
2016-10-11T10:04:55Z
39,975,214
<p>Your current code will run 10 times on 5 processor, on a SINGLE node where you start it. It has nothing to do with SLURM now. </p> <p>You will have to <code>SBATCH</code> the script to SLURM.</p> <p>If you want to run this script on 5 cores with SLURM modify the script like this:</p> <pre><code>#!/usr/bin/python3...
1
2016-10-11T10:23:29Z
[ "python", "multiprocessing", "slurm" ]
python sample large array using smaller array
39,974,913
<p>Let's say I have two arrays: SMALL_ARRAY and LARGE_ARRAY The LARGE_ARRAY contains values that are similar in value (not necessarily the same) I would like to get a subarray of the LARGE_ARRAY that:</p> <p>= Has same size as SMALL_ARRAY</p> <p>= Has similar values (similar distribution) as SMALL_ARRAY</p> <p>let's...
-1
2016-10-11T10:06:45Z
39,975,173
<p>Based on <a href="http://stackoverflow.com/a/8914682/3627387">http://stackoverflow.com/a/8914682/3627387</a></p> <pre><code>LARGE_ARRAY = [100,1.8,32,4.1,5,55,34,2.9,1.1,99] SMALL_ARRAY = [1,2,3,4] similar = [] for i in SMALL_ARRAY: diff_list = [(abs(i - x), x) for x in LARGE_ARRAY] diff_list.sort() si...
0
2016-10-11T10:20:48Z
[ "python", "arrays" ]
python sample large array using smaller array
39,974,913
<p>Let's say I have two arrays: SMALL_ARRAY and LARGE_ARRAY The LARGE_ARRAY contains values that are similar in value (not necessarily the same) I would like to get a subarray of the LARGE_ARRAY that:</p> <p>= Has same size as SMALL_ARRAY</p> <p>= Has similar values (similar distribution) as SMALL_ARRAY</p> <p>let's...
-1
2016-10-11T10:06:45Z
39,975,257
<p><code>numpy.random.choice</code> is your friend if you want to subsample uniformly at random:</p> <pre><code>import numpy as np # 'initialise' small so we know its shape # obviously you can skip that step if you already know the shape m, n = 5, 10 small = np.zeros((m, n)) # get a sample from a large array large =...
0
2016-10-11T10:26:11Z
[ "python", "arrays" ]