title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
python matplotlib how to get multiple axes handles
38,769,088
<p>My plot contains many subplots and I need a list of handles to treat each one of them. Right now I do the following</p> <pre><code>axes = [fig.add_subplot(2,3,1), fig.add_subplot(2,3,2), fig.add_subplot(2,3,3), fig.add_subplot(2,3,4), fig.add_subplot(2,3...
0
2016-08-04T13:43:13Z
38,769,154
<p>Simply use <a class='doc-link' href="http://stackoverflow.com/documentation/python/196/comprehensions/737/list-comprehensions#t=201608041346218089474">list comprehensions</a>:</p> <pre><code>axes = [fig.add_subplot(2,3,i+1) for i in range(6)] </code></pre> <p>Or a little generally:</p> <pre><code>x = 2 y = 3 axes...
2
2016-08-04T13:45:53Z
[ "python", "matplotlib" ]
python matplotlib how to get multiple axes handles
38,769,088
<p>My plot contains many subplots and I need a list of handles to treat each one of them. Right now I do the following</p> <pre><code>axes = [fig.add_subplot(2,3,1), fig.add_subplot(2,3,2), fig.add_subplot(2,3,3), fig.add_subplot(2,3,4), fig.add_subplot(2,3...
0
2016-08-04T13:43:13Z
38,769,334
<p>You can use:</p> <pre><code>f, ((ax1, ax2, ax3),(ax4, ax5, ax6)) = plt.subplots(2, 3) </code></pre> <p>or:</p> <pre><code>f, axarray = plt.subplots(2, 3) </code></pre>
3
2016-08-04T13:53:20Z
[ "python", "matplotlib" ]
Numpy ndarray object with string and floating point number types in it
38,769,120
<p>I have a file text with data in a following format:</p> <p>rubbish &amp; 3.97&amp; 3.83&amp; 3.95&amp; 3.83&amp; 3.82</p> <p>rubbish &amp; 4.92&amp; 4.81&amp; 4.88&amp; 4.81&amp; 4.81</p> <p>rubbish &amp; 5.90&amp; 5.66&amp; 5.88&amp; 5.66&amp; 5.66</p> <p>rubbish &amp;--- &amp; 6.05&amp; 6.14&amp; 6.05&amp; 6....
0
2016-08-04T13:44:13Z
38,769,316
<p>The problem isn't with <code>fun1</code>, it's with trying to insert elements of differing types into a numpy array. </p> <p>Consider the following:</p> <pre><code>&gt;&gt;&gt; a = numpy.array([1]) &gt;&gt;&gt; numpy.append(a,2) array([1, 2]) &gt;&gt;&gt; numpy.append(a,'b') array(['1', 'b'], dtype='&lt;U11') </...
1
2016-08-04T13:52:34Z
[ "python", "arrays", "numpy" ]
compare each row in two text file
38,769,140
<p>I hope i can have some help with this problem:</p> <p>I have two text file made up of about 10.000 rows (let's say File1 and File2) comng from a FEM analysis. The structure of the files is:</p> <p>File1</p> <pre><code> .... Element Facet Node CNORMF.Magnitude CNORMF.CNF1 ...
0
2016-08-04T13:45:29Z
38,769,638
<p>You are comparing each line of one file (with <code>m</code> lines) to each line of another file (with <code>n</code> lines). This leads to a time complexity <code>O(m*n)</code>. What this means is that two files, each having 10,000 lines, will produce 100,000,000 comparisons.</p> <p>You could speed up your code if...
1
2016-08-04T14:05:10Z
[ "python", "file", "text", "comparison", "abaqus" ]
Passing a list to HTML form Python
38,769,207
<p>I am trying to pass a list into an HTML form with Python. I am a noob and I am not really sure what I am doing so any advice would be appreciated.</p> <p>What I am trying to do is fill in all the blank text boxes and click radio buttons and drop down lists / menus using the list. This list will be the default value...
0
2016-08-04T13:48:03Z
38,769,449
<p>Part of the problem is that you're spinning this all up from the ground up. There are many templating libraries and tools offered in the greater Python community, you may want to look at those. Personally, I like Flask.</p> <p>If I <em>HAD</em> to solve this problem without recourse to an external library, I would ...
0
2016-08-04T13:57:57Z
[ "python", "html", "selenium", "cgi", "mechanize" ]
Passing a list to HTML form Python
38,769,207
<p>I am trying to pass a list into an HTML form with Python. I am a noob and I am not really sure what I am doing so any advice would be appreciated.</p> <p>What I am trying to do is fill in all the blank text boxes and click radio buttons and drop down lists / menus using the list. This list will be the default value...
0
2016-08-04T13:48:03Z
38,769,602
<p>I dont know a lot about Python but you did say you where a noob so I hope there is some value in this text, it gonna a quick and I hope easy to follow.</p> <p>Who cares what the server tech is? Get the data that you need on the client side and turn it into a json object so for instance if you need a name passed to ...
-1
2016-08-04T14:04:07Z
[ "python", "html", "selenium", "cgi", "mechanize" ]
Passing a list to HTML form Python
38,769,207
<p>I am trying to pass a list into an HTML form with Python. I am a noob and I am not really sure what I am doing so any advice would be appreciated.</p> <p>What I am trying to do is fill in all the blank text boxes and click radio buttons and drop down lists / menus using the list. This list will be the default value...
0
2016-08-04T13:48:03Z
38,772,084
<p>thanks to cwallenpoole I am making some progress. I am managing to pull some of the information from the settings list. However I do not seem to be able to affect the radio buttons or drop down lists. Here is my code now:</p> <pre><code>#!/usr/bin/python import config_settings import cgi import cgitb cgitb.enable(d...
0
2016-08-04T15:53:32Z
[ "python", "html", "selenium", "cgi", "mechanize" ]
change address of a website
38,769,274
<p>I want to have information about many persons. I have these informations on the website www.wats4u.com. . I have the firstname and the name of these persons in a document exel.</p> <p>For the moment I have the code :</p> <pre><code>import urllib page = urllib.urlopenbegin('https://www.wats4u.com/annuaire-alumni?...
0
2016-08-04T13:51:21Z
38,769,400
<p>Look into <a href="https://docs.python.org/2/library/stdtypes.html#str.format" rel="nofollow"><code>str.format</code></a>:</p> <pre><code>url = 'https://www.wats4u.com/annuaire-alumni?lastname={}&amp;firstname={}&amp;scholl=All&amp;class=All&amp;=rechercher' firstname = 'algan' lastname = 'michel' page = urllib.url...
1
2016-08-04T13:55:34Z
[ "python", "web" ]
Python: How to detect a particular number inside a long serial number
38,769,350
<p>I have been working on this project, a small Python and Tkinter project as I'm a beginner and I almost finished it if it weren't for this little issue I have with it that I detected after doing a few tests. The program should say whether a serial number that I entered in an input is a "devil number" or not depending...
1
2016-08-04T13:53:56Z
38,769,553
<p>If you mean that <code>666</code>, found anywhere in the number should be a match, then it's very simple:</p> <pre><code>if '666' in '1234666321': print("It's a devil's number") </code></pre> <p>However, you say that <code>666</code> must be a "lone" <code>666</code>, i.e. exactly three <code>6</code> side by ...
3
2016-08-04T14:02:24Z
[ "python", "tkinter", "project" ]
Python: How to detect a particular number inside a long serial number
38,769,350
<p>I have been working on this project, a small Python and Tkinter project as I'm a beginner and I almost finished it if it weren't for this little issue I have with it that I detected after doing a few tests. The program should say whether a serial number that I entered in an input is a "devil number" or not depending...
1
2016-08-04T13:53:56Z
38,769,806
<p>You should use a <a href="https://docs.python.org/3/library/re.html#re.search" rel="nofollow">regular expression</a> for this. Something like <code>(?:^|[^6])(666)(?:[^6]|$)</code> seems to work. This means "start of string <code>^</code> or <code>|</code> something that is not a 6 <code>[^6]</code>, then <code>666<...
3
2016-08-04T14:11:58Z
[ "python", "tkinter", "project" ]
Get a list from config.ini file
38,769,428
<p>In my config file I have something like that : </p> <pre><code>[Section_1] List=Column1,Column2,Column3,Column4 </code></pre> <p>Now, I would like to process it in my main file as normal lists :</p> <pre><code> config = configparser.ConfigParser() config.read("configTab.ini") for index in range(len(Lis...
1
2016-08-04T13:56:49Z
38,769,508
<p>Use <a href="https://docs.python.org/2/library/stdtypes.html#str.split" rel="nofollow"><code>str.split</code></a>:</p> <p><code>List = List.split(',')</code></p> <pre><code>string = 'a, b, c' print(string.split(',')) &gt;&gt; ['a', 'b', 'c'] </code></pre>
2
2016-08-04T14:00:19Z
[ "python", "configparser" ]
Python: Print specific value from a dictionary list that was read from a csv
38,769,628
<p>I want to know how to read a csv file into a dictionary and then print out a specific value from the dictionary with python. <a href="http://i.imgur.com/OcZ1tlK.jpg" rel="nofollow">CSV file example</a>. I'd like to grab the line that is selected and print that persons name out. I'm new at this and I've tried some lo...
-1
2016-08-04T14:04:46Z
38,769,878
<p>Do something like :</p> <pre><code>import csv l = [] with open('inputfile.csv') as f: reader = csv.DictReader(f) for row in reader: l.append(row) # If you need say for example the firstname for val in l: print (l['firstname']) </code></pre> <p>Although its still unclear without the code what ...
0
2016-08-04T14:14:46Z
[ "python", "csv", "dictionary" ]
efficient count distinct across columns of DataFrame, grouped by rows
38,769,675
<p>What is the fastest way (within the limits of sane pythonicity) to count distinct values, across columns of the same <code>dtype</code>, for each row in a <code>DataFrame</code>? </p> <p><strong>Details:</strong> I have a <code>DataFrame</code> of categorical outcomes by subject (in rows) by day (in columns), simil...
6
2016-08-04T14:06:50Z
38,770,078
<p><code>pandas.melt</code> with <code>DataFrame.groupby</code> and <code>groupby.SeriesGroupBy.nunique</code> seems to blow the other solutions away:</p> <pre><code>%timeit -n20 pd.melt(testDf, id_vars ='custId').groupby('custId').value.nunique() #20 loops, best of 3: 67.3 ms per loop </code></pre>
2
2016-08-04T14:22:36Z
[ "python", "performance", "pandas", "numpy", "distinct-values" ]
efficient count distinct across columns of DataFrame, grouped by rows
38,769,675
<p>What is the fastest way (within the limits of sane pythonicity) to count distinct values, across columns of the same <code>dtype</code>, for each row in a <code>DataFrame</code>? </p> <p><strong>Details:</strong> I have a <code>DataFrame</code> of categorical outcomes by subject (in rows) by day (in columns), simil...
6
2016-08-04T14:06:50Z
38,770,583
<p>You don't need <code>custId</code>. I'd <code>stack</code>, then <code>groupby</code></p> <pre><code>testDf.iloc[:, 1:].stack().groupby(level=0).nunique() </code></pre> <p><a href="http://i.stack.imgur.com/fBX5l.png" rel="nofollow"><img src="http://i.stack.imgur.com/fBX5l.png" alt="enter image description here"><...
2
2016-08-04T14:45:26Z
[ "python", "performance", "pandas", "numpy", "distinct-values" ]
efficient count distinct across columns of DataFrame, grouped by rows
38,769,675
<p>What is the fastest way (within the limits of sane pythonicity) to count distinct values, across columns of the same <code>dtype</code>, for each row in a <code>DataFrame</code>? </p> <p><strong>Details:</strong> I have a <code>DataFrame</code> of categorical outcomes by subject (in rows) by day (in columns), simil...
6
2016-08-04T14:06:50Z
38,772,004
<p>My understanding is that nunique is optimized for large series. Here, you have only 3 days. Comparing each column against the others seems to be faster:</p> <pre><code>testDf = genSampleData(100000,3, drinkIndex) days = testDf.columns[1:] %timeit testDf.iloc[:, 1:].stack().groupby(level=0).nunique() 10 loops, best...
3
2016-08-04T15:49:30Z
[ "python", "performance", "pandas", "numpy", "distinct-values" ]
How to solve "Insufficient Permission" for userUsageReport with Google API?
38,769,798
<p>I'm trying to write a Python script that will check if a user account has got two-step verification enabled.</p> <p>As a starting point, I'm using the quickstart script provided on <a href="https://developers.google.com/admin-sdk/reports/v1/quickstart/python" rel="nofollow">https://developers.google.com/admin-sdk/r...
0
2016-08-04T14:11:43Z
38,787,031
<p>I've solved this.</p> <p>userUsageReport requires the usage scope to be added, specifically:</p> <p><a href="https://www.googleapis.com/auth/admin.reports.usage.readonly" rel="nofollow">https://www.googleapis.com/auth/admin.reports.usage.readonly</a></p> <p>Since the quickstart only reference the audit scope:</p>...
0
2016-08-05T10:29:52Z
[ "python", "google-admin-sdk" ]
Assinging Values to a new column in DataFrame
38,769,859
<p>I am unable to understand how values are assinged to a new column of a DataFrame</p> <p>if my code is:</p> <pre><code>Frame3['Debt']=16.5 print Frame3 o/p is Year State POP Debt one 2000 Ohio 1.5 16.5 two 2001 Ohio 1.7 16.5 three 2002 Ohio 3.6 16.5 four 2001 Nevada 2.4 16.5 fiv...
-1
2016-08-04T14:14:02Z
38,769,930
<p>You need to write:</p> <pre><code>Frame5 = Frame3.loc[Frame3['Debt']== 16.5] </code></pre> <p>To subset your pandas DataFrame. Make sure that 'Debt' is a float.</p>
0
2016-08-04T14:16:45Z
[ "python", "pandas", "dataframe" ]
Scipy Non-central Chi-Squared Random Variable
38,769,935
<p>Consider a sum of <code>n</code> squared iid normal random variables <code>S = sum (Z^2(mu, sig^2))</code>. According to <a href="http://mathoverflow.net/questions/89779/sum-of-squares-of-normal-distributions">this question</a>, <code>S / sig^2</code> has a <a href="https://en.wikipedia.org/wiki/Noncentral_chi-squa...
3
2016-08-04T14:16:49Z
38,772,693
<p>The problem is in the second sentence of the question: <em>"<code>S / sig^2</code> has a noncentral chi-squared distribution with degrees of freedom = <code>n</code> and non-centrality parameter = <code>n*mu^2</code>."</em> That non-centrality parameter is not correct. It should be <code>n*(mu/sig)^2</code>.</p> ...
2
2016-08-04T16:24:02Z
[ "python", "numpy", "scipy" ]
How Do I Shorten Python Code By Getting Rid of Var=0
38,769,969
<p>I'm currently having a competition with my friends to create the shortest solution (in lines) to a python problem.</p> <p>I figure there must be a way to get rid of the <code>total=0</code> in this for loop</p> <pre><code>total=0 for x in word: total += x print total </code></pre> <p>(I am aware that I can pu...
-4
2016-08-04T14:18:08Z
38,770,004
<p>You can't in this context, but you don't even need that loop:</p> <pre><code>sum(list_of_ints) </code></pre>
5
2016-08-04T14:19:19Z
[ "python" ]
How Do I Shorten Python Code By Getting Rid of Var=0
38,769,969
<p>I'm currently having a competition with my friends to create the shortest solution (in lines) to a python problem.</p> <p>I figure there must be a way to get rid of the <code>total=0</code> in this for loop</p> <pre><code>total=0 for x in word: total += x print total </code></pre> <p>(I am aware that I can pu...
-4
2016-08-04T14:18:08Z
38,770,115
<p>Since you are only concerned about the number of lines, you could check if <code>total</code> has been declared already:</p> <pre><code>for x in word: total = x if 'total' not in locals() else total + x print total </code></pre>
0
2016-08-04T14:24:14Z
[ "python" ]
Speed up converting CSV to HDF5 in Pandas
38,770,024
<p>I'm looking for a way to speed up this process. I have it functioning, but it is going to take days to complete.<br> I have a data file for each day of a year. And, I want to combine them into a single HDF5 file with a node for each data label (data tag).<br> The data looks like this:</p> <pre><code>a,1468004920,...
1
2016-08-04T14:20:20Z
38,772,864
<p>I'd do it this way:</p> <pre><code>MI = pytz.timezone('US/Central') tmp_data=pd.read_csv('test1.txt',index_col=[1],names=['Tag','Timestamp','Value']) tmp_data.index=pd.to_datetime(tmp_data.index,unit='s') tmp_data.index.tz=MI hdf_key = 'my_key' store = pd.HDFStore('/path/to/file.h5') for loop which processes al...
0
2016-08-04T16:32:40Z
[ "python", "pandas" ]
Passing several arguments for rendering template
38,770,148
<p>First of all, let me excuse for my English - it's not my native language.</p> <p>I have following models:</p> <pre><code>class Student(models.Model): student_id = models.IntegerField(primary_key=True) student_name = models.CharField(max_length=255, default='John Doe') dob = models.DateField(max_length=...
0
2016-08-04T14:25:32Z
38,770,461
<p>You could get the number of students in a group like this:</p> <pre><code>group = ... # get a group n_students = Student_Group.objects.filter(group=group).count() </code></pre> <p>Then since every Student_Group object has <em>one</em> student, <code>n_students</code> will contain the number of student in the giv...
1
2016-08-04T14:40:15Z
[ "python", "django" ]
How to install scikit-learn for Python 3?
38,770,169
<p>I try to install scikit-learn for Python 3. I do it in the following way:</p> <pre><code>virtualenv model_env source model_env/bin/activate pip3 install sklearn </code></pre> <p>As a result I get the following error message:</p> <pre><code>Downloading/unpacking sklearn Cannot fetch index base URL https://pypi....
0
2016-08-04T14:26:32Z
38,770,234
<p>Try using</p> <pre><code>pip3 install scikit-learn </code></pre>
0
2016-08-04T14:29:41Z
[ "python", "scikit-learn", "python-3.4" ]
How to install scikit-learn for Python 3?
38,770,169
<p>I try to install scikit-learn for Python 3. I do it in the following way:</p> <pre><code>virtualenv model_env source model_env/bin/activate pip3 install sklearn </code></pre> <p>As a result I get the following error message:</p> <pre><code>Downloading/unpacking sklearn Cannot fetch index base URL https://pypi....
0
2016-08-04T14:26:32Z
38,770,605
<p>Maybe you should consider the use of <a href="https://www.continuum.io/downloads" rel="nofollow">Anaconda</a> which include both packages by default and make your life easy with tools to manage <a href="http://conda.pydata.org/docs/using/envs.html" rel="nofollow">enviroments</a> and <a href="http://conda.pydata.org/...
1
2016-08-04T14:46:25Z
[ "python", "scikit-learn", "python-3.4" ]
How to install scikit-learn for Python 3?
38,770,169
<p>I try to install scikit-learn for Python 3. I do it in the following way:</p> <pre><code>virtualenv model_env source model_env/bin/activate pip3 install sklearn </code></pre> <p>As a result I get the following error message:</p> <pre><code>Downloading/unpacking sklearn Cannot fetch index base URL https://pypi....
0
2016-08-04T14:26:32Z
38,779,064
<p>If you want the convenience of Anaconda packages but the flexibility and minimalism of <code>pip</code> package management, I suggest you try <a href="http://conda.pydata.org/miniconda.html" rel="nofollow">miniconda</a>.</p> <p>Once you install miniconda (remembering to <code>source ~/.bash_profile</code> or <code>...
0
2016-08-04T23:45:36Z
[ "python", "scikit-learn", "python-3.4" ]
How to install scikit-learn for Python 3?
38,770,169
<p>I try to install scikit-learn for Python 3. I do it in the following way:</p> <pre><code>virtualenv model_env source model_env/bin/activate pip3 install sklearn </code></pre> <p>As a result I get the following error message:</p> <pre><code>Downloading/unpacking sklearn Cannot fetch index base URL https://pypi....
0
2016-08-04T14:26:32Z
38,790,362
<p>Based on this <a href="http://stackoverflow.com/a/22446215/5781248">answer</a> for question <a href="http://stackoverflow.com/questions/15501133/python-pip-error-cannot-fetch-index-base-url-https-pypi-python-org-simple">Python pip error: “Cannot fetch index base URL https://pypi.python.org/simple/”</a> I would t...
0
2016-08-05T13:20:49Z
[ "python", "scikit-learn", "python-3.4" ]
Printing strings and variables on the same line
38,770,247
<p>I have a header array with three things in it. My program goes through all the combinations of headers and sees if they are concurrent or not concurrent.</p> <p>When I run the program I want it to print which two headers are concurrent and which are not concurrent. So basically when it prints, instead of it printin...
1
2016-08-04T14:30:28Z
38,770,329
<p>Best way to format strings in <em>Python</em> is like this:</p> <pre><code>"{} and {} are concurrent".format(header[p[0]],header[p[1]]) </code></pre> <p>It's also possible to use multiple placeholders <code>{}</code>.</p>
0
2016-08-04T14:33:40Z
[ "python", "string", "python-2.7", "variables", "printing" ]
Printing strings and variables on the same line
38,770,247
<p>I have a header array with three things in it. My program goes through all the combinations of headers and sees if they are concurrent or not concurrent.</p> <p>When I run the program I want it to print which two headers are concurrent and which are not concurrent. So basically when it prints, instead of it printin...
1
2016-08-04T14:30:28Z
38,770,613
<p>You want to combine the two lists into one:</p> <pre><code>for (h1, s1), (h2, s2) in combinations(zip(header, sequence), 2): if s1[start:stop] == s2[start:stop]: print h1, h2, "are concurrent" else: print h1, h2, "are not concurrent" </code></pre> <p>or to reduce duplicate code:</p> <pre><...
2
2016-08-04T14:46:37Z
[ "python", "string", "python-2.7", "variables", "printing" ]
Immutable Dictionary with key-object pairs Python
38,770,374
<p>I have a dictionary filled with key-object pairs. I want to make the dictionary immutable and I thought the best/easiest way is to cast it to a frozenset but <code>frozenset(dict)</code> and also <code>tuple(dict)</code> only stores the keys.</p> <p>Using <code>frozenset(dict.items())</code> I seem to get a frozens...
3
2016-08-04T14:35:57Z
38,770,548
<p>You could make a wrapper class that takes a dictionary and has a get item function but no set item. You'd need to add a few things for thread safety and hashing maybe but the basic class wouldn't be too difficult.</p>
0
2016-08-04T14:43:41Z
[ "python", "python-2.7", "dictionary", "frozenset" ]
Immutable Dictionary with key-object pairs Python
38,770,374
<p>I have a dictionary filled with key-object pairs. I want to make the dictionary immutable and I thought the best/easiest way is to cast it to a frozenset but <code>frozenset(dict)</code> and also <code>tuple(dict)</code> only stores the keys.</p> <p>Using <code>frozenset(dict.items())</code> I seem to get a frozens...
3
2016-08-04T14:35:57Z
38,770,619
<p>The simplest way I could think of to achieve what you want was to subclass the standard <code>dict</code> type and overwrite its <code>__setitem__</code> method:</p> <pre><code>class MyDict(dict): def __setitem__(self, key, value): raise NotImplementedError("This is a frozen dictionary") </code></pre> ...
0
2016-08-04T14:47:07Z
[ "python", "python-2.7", "dictionary", "frozenset" ]
Immutable Dictionary with key-object pairs Python
38,770,374
<p>I have a dictionary filled with key-object pairs. I want to make the dictionary immutable and I thought the best/easiest way is to cast it to a frozenset but <code>frozenset(dict)</code> and also <code>tuple(dict)</code> only stores the keys.</p> <p>Using <code>frozenset(dict.items())</code> I seem to get a frozens...
3
2016-08-04T14:35:57Z
38,770,783
<p>You can create an immutable view of a dictionary using <a href="https://docs.python.org/3/library/types.html#types.MappingProxyType" rel="nofollow"><code>types.MappingProxyType</code></a>:</p> <pre><code>from types import MappingProxyType d = { 'a': 1 } fd = MappingProxyType(d) fd['a'] #output: 1 fd['a'] = 2 #outp...
1
2016-08-04T14:54:16Z
[ "python", "python-2.7", "dictionary", "frozenset" ]
Immutable Dictionary with key-object pairs Python
38,770,374
<p>I have a dictionary filled with key-object pairs. I want to make the dictionary immutable and I thought the best/easiest way is to cast it to a frozenset but <code>frozenset(dict)</code> and also <code>tuple(dict)</code> only stores the keys.</p> <p>Using <code>frozenset(dict.items())</code> I seem to get a frozens...
3
2016-08-04T14:35:57Z
38,770,978
<p>Since you mention <code>tuple(dict)</code> in your original post, probably the simplest solution to achieve what you want might simply be:</p> <pre><code>tuple(dict.items()) </code></pre>
0
2016-08-04T15:02:51Z
[ "python", "python-2.7", "dictionary", "frozenset" ]
Immutable Dictionary with key-object pairs Python
38,770,374
<p>I have a dictionary filled with key-object pairs. I want to make the dictionary immutable and I thought the best/easiest way is to cast it to a frozenset but <code>frozenset(dict)</code> and also <code>tuple(dict)</code> only stores the keys.</p> <p>Using <code>frozenset(dict.items())</code> I seem to get a frozens...
3
2016-08-04T14:35:57Z
38,771,111
<p>You need a <code>dict</code> that is capable of freezing? You can simply make one:</p> <pre><code>class FrozenDict(dict): def __init__(self, *args, **kwargs): self._frozen = False dict.__init__(self, *args, **kwargs) def freeze(self): self._frozen = True def __setitem__(self, key...
0
2016-08-04T15:08:29Z
[ "python", "python-2.7", "dictionary", "frozenset" ]
python program raising exceptions
38,770,470
<p>Im working on a finger exercise from Guttag Intro to computer science and programming using python, and Im working on the following finger exercise:</p> <p>Finger Exercise: Implement a function that satisfies the specification def findAnEven(l): """Assumes l is a list of integers Returns the first even number in l ...
-2
2016-08-04T14:40:32Z
38,770,739
<p>The issue with your code is the usage of <code>exit()</code>. Generally <code>return</code> will exit for you. To fix the code, just remove it:</p> <pre><code>def isEven(l): for i in l: if i % 2 == 0: return i raise ValueError("No even numbers in list!") ...
1
2016-08-04T14:52:02Z
[ "python", "exception", "raise" ]
Replace sequence of words in string with string python
38,770,484
<p>I couldn't find anything that could solve this (<code>replace()</code> method doesn't work).</p> <p>I have a sentence like:</p> <pre><code>sentence_noSlots = "Albania compared to other CountriesThe Internet users of Albania is similar to that of Poland , Portugal , Russia , Macedonia , Saudi Arabia , Argentina , G...
0
2016-08-04T14:41:04Z
38,770,661
<p><code>string.replace()</code> is not in-place. Strings are immutable in python.</p> <p>From <a href="https://docs.python.org/2/library/string.html" rel="nofollow">python docs</a>:</p> <blockquote> <p>string.replace(s, old, new[, maxreplace]) Return a copy of string s with all occurrences of substring old repla...
1
2016-08-04T14:48:55Z
[ "python", "string", "replace", "find", "findall" ]
Replace sequence of words in string with string python
38,770,484
<p>I couldn't find anything that could solve this (<code>replace()</code> method doesn't work).</p> <p>I have a sentence like:</p> <pre><code>sentence_noSlots = "Albania compared to other CountriesThe Internet users of Albania is similar to that of Poland , Portugal , Russia , Macedonia , Saudi Arabia , Argentina , G...
0
2016-08-04T14:41:04Z
38,770,773
<p>I assume you meant:</p> <pre><code>extracted_country = "Saudi Arabia" extracted_value = "58.5" </code></pre> <p>Then, the .replace method works as expected. Be careful though, it is NOT a modifier: it returns a NEW string with the modification. "sentence_noSlots" will remain the same.</p> <p>So by chaining both ....
1
2016-08-04T14:53:33Z
[ "python", "string", "replace", "find", "findall" ]
Python 3 csv.writer prints "bytes" with prefix and quotes
38,770,522
<p>In Python 2 this code does what I'd expect:</p> <pre><code>import csv import sys writer = csv.writer(sys.stdout) writer.writerow([u'hello', b'world']) </code></pre> <p>It prints:</p> <pre><code>hello,world </code></pre> <p>But in Python 3, <code>bytes</code> are printed with a prefix and quotes:</p> <pre><code...
1
2016-08-04T14:42:28Z
38,773,355
<p>I don't think there's any way of avoiding having to explictly convert the byte strings into unicode strings with the <code>csv</code> module in Python 3. In Python 2, they're implicitly converted to ASCII. </p> <p>To make this easier you could effectively subclass <code>csv.writer</code> (or wrap) objects as shown ...
0
2016-08-04T17:00:32Z
[ "python", "python-3.x", "csv", "python-unicode" ]
Python 3 csv.writer prints "bytes" with prefix and quotes
38,770,522
<p>In Python 2 this code does what I'd expect:</p> <pre><code>import csv import sys writer = csv.writer(sys.stdout) writer.writerow([u'hello', b'world']) </code></pre> <p>It prints:</p> <pre><code>hello,world </code></pre> <p>But in Python 3, <code>bytes</code> are printed with a prefix and quotes:</p> <pre><code...
1
2016-08-04T14:42:28Z
38,773,645
<p><code>csv</code> writes text files and expects Unicode (text) strings in Python 3.</p> <p><code>csv</code> writes binary files and expects byte strings in Python 2, but allowed implicit encoding of Unicode strings to byte strings using the default <code>ascii</code> codec. Python 3 does not allow implicit conversi...
0
2016-08-04T17:16:22Z
[ "python", "python-3.x", "csv", "python-unicode" ]
Synchronizing code between jupyter/iPython notebook script and class methods
38,770,604
<p>I'm trying to figure out the best way to keep code in an Jupyter/iPython notebook and the same code inside of a class method in sync. Here's the use case:</p> <p>I wrote a long script that uses pandas inside a notebook, and have multiple cells which made the development easy, because I could check intermediate res...
1
2016-08-04T14:46:24Z
38,838,030
<p>I have used your same development workflow and recognize the value of being able to step through code using the jupyter notebook. I've developed several packages by first hashing out the details and then eventually moving the polished product in to separate .py files. I do not think there is a simple solution to the...
1
2016-08-08T20:32:02Z
[ "python", "pandas", "ipython-notebook", "jupyter-notebook" ]
Finding patterns in list
38,770,606
<p>I am currently searching for a way to find patterns in a list of integers, but the method I am going to use would be applicable to strings and other lists with different elements of course. Now let me explain what I am looking for.</p> <p>I want to find the longest repeating pattern in a list of integers. For examp...
16
2016-08-04T14:46:29Z
38,772,020
<h1>The Code</h1> <p>Ignoring the "no overlapping" requirement, here's the code I used:</p> <pre><code>def pattern(seq): storage = {} for length in range(1,len(seq)/2+1): valid_strings = {} for start in range(0,len(seq)-length+1): valid_strings[s...
3
2016-08-04T15:50:05Z
[ "python", "algorithm", "performance", "pattern-matching" ]
Sharing a ctypes numpy array without lock when using multiprocessing
38,770,681
<p>I have a large array (~500k rows x 9 columns) which I would like to share when running a number of parallel processes using Python's <code>multiprocessing</code> module. I am using <a href="http://stackoverflow.com/questions/5549190/is-shared-readonly-data-copied-to-different-processes-for-python-multiprocessing/555...
0
2016-08-04T14:49:33Z
38,824,970
<p>Found the answer <a href="http://stackoverflow.com/a/11715314/1414831">here</a> thanks to <a href="http://stackoverflow.com/users/772649/hyry">HYRY</a></p> <p>Stating <code>lock=True</code> returns a wrapped object:</p> <pre><code>multiprocessing.sharedctypes.SynchronizedArray </code></pre> <p>When <code>lock=Fal...
0
2016-08-08T08:56:16Z
[ "python", "numpy", "multiprocessing" ]
python isdigit() returning unexpected result
38,770,753
<p>I'm making a basic BMI calculation program for a class assignment using TKinter for the GUI, and ran into a problem when trying to validate the user's input. I'm trying to only allow numerical input and to deactivate the 'calculate' button and send an error message when the user enters anything that's not a number. ...
0
2016-08-04T14:52:39Z
38,770,837
<p>You need to use <a href="http://www.tutorialspoint.com/python/string_isdigit.htm" rel="nofollow"><code>isdigit</code></a> on strings.</p> <pre><code>val = '23' val.isdigit() # True val = '4' val.isdigit() # True val = 'abc' val.isdigit() # False </code></pre> <p>If you're not sure what the type of the input is,...
-1
2016-08-04T14:57:01Z
[ "python", "tkinter" ]
python isdigit() returning unexpected result
38,770,753
<p>I'm making a basic BMI calculation program for a class assignment using TKinter for the GUI, and ran into a problem when trying to validate the user's input. I'm trying to only allow numerical input and to deactivate the 'calculate' button and send an error message when the user enters anything that's not a number. ...
0
2016-08-04T14:52:39Z
38,770,883
<p><code>isdigit</code> is a string method. Are you expecting a string, an int, or a float?</p> <p>You can add some typechecking code like this, so that your program validates regardless of whether the value is a numerical type or a string type.</p> <pre><code>def val(value): if type(value) in (int, float): ...
-1
2016-08-04T14:59:02Z
[ "python", "tkinter" ]
python isdigit() returning unexpected result
38,770,753
<p>I'm making a basic BMI calculation program for a class assignment using TKinter for the GUI, and ran into a problem when trying to validate the user's input. I'm trying to only allow numerical input and to deactivate the 'calculate' button and send an error message when the user enters anything that's not a number. ...
0
2016-08-04T14:52:39Z
38,771,034
<p>The first thing you should do to debug this is to print out <code>value</code> inside of <code>val</code>, to see if your assumptions are correct. Validating your assumptions is always the first step in debugging.</p> <p>What you'll find is that your function is being called before the digit typed by the user is ac...
0
2016-08-04T15:04:56Z
[ "python", "tkinter" ]
Django - Adding multiple children to a model
38,770,760
<p>I have a <code>Test</code> class that will contain an unknown number of <code>WriteData</code> and <code>VerifyData</code> objects:</p> <pre><code>class Test(models.Model): objective = models.ForeignKey(Objective) test_at = models.CharField(max_length=NAME_MAX_LENGTH, unique=True) description = models.C...
0
2016-08-04T14:52:57Z
38,771,264
<p>In you script you have a method <code>add_verify_data</code> (line 148):</p> <pre><code>def add_verify_data(test, v_var, rel_op, v_val, v_tol): vd = WriteData.objects.get_or_create( test=test, verify_variable=v_var, relational_operator=rel_op, verify_value=v_val, verify_t...
1
2016-08-04T15:16:00Z
[ "python", "django", "database", "django-models" ]
legend is missing when I used add_subplot function
38,770,771
<p>I plan to graph a data with tow subplot. In the first subplot, it is including all stock price, moving average(window = 5),moving average( window = 8) and moving average( window = 13)</p> <p>In the second subplot, it is just including RSI.</p> <p>I initially obtain a serious of data that is the stock price (using ...
0
2016-08-04T14:53:33Z
38,770,936
<p>To get the legends to work, change these two lines</p> <pre><code>ax1.plot(df) ax2.plot(stock_rsi) </code></pre> <p>to these:</p> <pre><code>ax1.plot(df, label="df") ax2.plot(stock_rsi, label="stock_rsi") </code></pre> <p>The reason why is because Matplotlib's artist requires labels to draw legends.</p>
0
2016-08-04T15:00:59Z
[ "python", "pandas" ]
Create class object instance named from string?
38,770,845
<p>I can't find the answer anywhere.</p> <p>I have a class called "vrf".</p> <p>I have an input file.</p> <p>As Python iterates through the lines of this input file, every time it sees the word vrf, I want to create an object named after the next word.</p> <p>So if it reading the line "ip vrf TESTER", I would like ...
1
2016-08-04T14:57:11Z
38,770,946
<p>Generally speaking, dynamically created variable names are a bad idea. Instead, you should create a dictionary where the name is the key and the instance is the value</p> <p>In your case it would look something like this:</p> <pre><code>objects = {} ... object_name = line.split()[2] objects[object_name] = vrf() </...
2
2016-08-04T15:01:29Z
[ "python", "object", "dynamic" ]
Create class object instance named from string?
38,770,845
<p>I can't find the answer anywhere.</p> <p>I have a class called "vrf".</p> <p>I have an input file.</p> <p>As Python iterates through the lines of this input file, every time it sees the word vrf, I want to create an object named after the next word.</p> <p>So if it reading the line "ip vrf TESTER", I would like ...
1
2016-08-04T14:57:11Z
38,770,955
<p>Why don't you just use a dictionary?</p> <pre><code>object = {} object[line.split()[2]] = vrf() </code></pre>
1
2016-08-04T15:01:46Z
[ "python", "object", "dynamic" ]
Create class object instance named from string?
38,770,845
<p>I can't find the answer anywhere.</p> <p>I have a class called "vrf".</p> <p>I have an input file.</p> <p>As Python iterates through the lines of this input file, every time it sees the word vrf, I want to create an object named after the next word.</p> <p>So if it reading the line "ip vrf TESTER", I would like ...
1
2016-08-04T14:57:11Z
38,771,062
<p>The <code>globals()</code> dictionary can be edited to do this:</p> <pre><code>&gt;&gt;&gt; globals()['TEST'] = vrf() &gt;&gt;&gt; type(TEST) # &lt;class 'vrf'&gt; </code></pre>
0
2016-08-04T15:06:16Z
[ "python", "object", "dynamic" ]
Create class object instance named from string?
38,770,845
<p>I can't find the answer anywhere.</p> <p>I have a class called "vrf".</p> <p>I have an input file.</p> <p>As Python iterates through the lines of this input file, every time it sees the word vrf, I want to create an object named after the next word.</p> <p>So if it reading the line "ip vrf TESTER", I would like ...
1
2016-08-04T14:57:11Z
38,771,068
<p>What you're trying to do is not a great idea, instead use a <strong>dictionary</strong>, or if your object has an instance variable that stores name information such as <code>name</code>, bind the data there.</p> <pre><code>objs = {} objs[line.split()[2]] = vrf() </code></pre> <p>or (<em>if available</em>)</p> <p...
1
2016-08-04T15:06:33Z
[ "python", "object", "dynamic" ]
Remove some elements from an Array in Python
38,770,911
<p>i have an other question, i have this array in Python :</p> <pre><code>import numpy as np A = np.zeros((5)); A[0] = 2; A[1] = 3; A[2] = 7; A[3] = 1; A[4] = 8; </code></pre> <p>And what I want to do is to delete <code>A[i] for i from 2 to 4</code> that is to say i am looking for a command like this :</p> <p><code...
2
2016-08-04T15:00:10Z
38,771,148
<p>If what you want is deleting the positions from numpy array you can use:</p> <pre><code>np.delete(A, slice(2,5)) # note that the interval is inclusive, exclusive [2, 5) </code></pre>
1
2016-08-04T15:10:09Z
[ "python", "python-2.7", "python-3.x" ]
Remove some elements from an Array in Python
38,770,911
<p>i have an other question, i have this array in Python :</p> <pre><code>import numpy as np A = np.zeros((5)); A[0] = 2; A[1] = 3; A[2] = 7; A[3] = 1; A[4] = 8; </code></pre> <p>And what I want to do is to delete <code>A[i] for i from 2 to 4</code> that is to say i am looking for a command like this :</p> <p><code...
2
2016-08-04T15:00:10Z
38,771,159
<p>What you need to use is actually, <code>numpy.delete</code>, but you need to pass the proper second argument, e.g.:</p> <pre><code>np.delete(A, slice(2, 4)) </code></pre>
0
2016-08-04T15:10:31Z
[ "python", "python-2.7", "python-3.x" ]
How to create separate login for admin and user in django?
38,771,004
<p>How to create separate login for admin and user in django using django built in authentication system that user can't access admin panel and vice versa?If admin login it will redirect the admin page and if user login it will redirect the home page.</p>
-3
2016-08-04T15:03:35Z
38,771,192
<p>Only user who are active and are having staff or superadmin status can login in django admin panel <a href="http://prntscr.com/c1kvpx" rel="nofollow">http://prntscr.com/c1kvpx</a></p> <p>To enable a non admin user login it is highly recommended that you create a new login page. </p> <p>Use something like this in y...
1
2016-08-04T15:12:21Z
[ "python", "django" ]
change a variable in a for loop from 0 to 2, and back again to 0
38,771,083
<p>Hi I am looking for a smart way to get a for loop in Python in which one variable, say k, has to shift from 0 to 2 and than back to 0 up to the end of the loop. Something like </p> <pre><code>k = 0 for j in range(15): fancycode k = k + 1 </code></pre> <p>In which for each loop k has the following values</p...
0
2016-08-04T15:07:12Z
38,771,309
<p>Simply using modulo! (%)</p> <pre><code>for j in range(15): fancycode k = j % 3 print(k) </code></pre>
0
2016-08-04T15:17:43Z
[ "python" ]
change a variable in a for loop from 0 to 2, and back again to 0
38,771,083
<p>Hi I am looking for a smart way to get a for loop in Python in which one variable, say k, has to shift from 0 to 2 and than back to 0 up to the end of the loop. Something like </p> <pre><code>k = 0 for j in range(15): fancycode k = k + 1 </code></pre> <p>In which for each loop k has the following values</p...
0
2016-08-04T15:07:12Z
38,771,391
<p>using list comprehension you can:</p> <pre><code>for j, k in ((j, j % 3) for j in range(15)): print('j: {0}, k: {1}'.format(j, k)) </code></pre> <p>will print:</p> <pre><code>j: 0, k: 0 j: 1, k: 1 j: 2, k: 2 j: 3, k: 0 j: 4, k: 1 j: 5, k: 2 j: 6, k: 0 j: 7, k: 1 j: 8, k: 2 j: 9, k: 0 j: 10, k: 1 j: 11, k: 2 j...
0
2016-08-04T15:21:13Z
[ "python" ]
change a variable in a for loop from 0 to 2, and back again to 0
38,771,083
<p>Hi I am looking for a smart way to get a for loop in Python in which one variable, say k, has to shift from 0 to 2 and than back to 0 up to the end of the loop. Something like </p> <pre><code>k = 0 for j in range(15): fancycode k = k + 1 </code></pre> <p>In which for each loop k has the following values</p...
0
2016-08-04T15:07:12Z
38,771,405
<p>The right way to do it is to use <a href="https://docs.python.org/3/library/itertools.html?highlight=chain#itertools.cycle" rel="nofollow">itertools.cycle()</a> For example:</p> <pre><code>import itertools my_cycle = itertools.cycle(range(3)) for j in range(15): k = my_cycle.next() </code></pre> <p>valid in Pyt...
1
2016-08-04T15:21:56Z
[ "python" ]
change a variable in a for loop from 0 to 2, and back again to 0
38,771,083
<p>Hi I am looking for a smart way to get a for loop in Python in which one variable, say k, has to shift from 0 to 2 and than back to 0 up to the end of the loop. Something like </p> <pre><code>k = 0 for j in range(15): fancycode k = k + 1 </code></pre> <p>In which for each loop k has the following values</p...
0
2016-08-04T15:07:12Z
38,772,170
<pre><code>from itertools import cycle, islice for index, value in enumerate(islice(cycle([0, 2]), 15)): print('loop{} k = {}'.format(index, value)) </code></pre>
1
2016-08-04T15:57:36Z
[ "python" ]
How to encode strings with mixed character sets for Excel in Python
38,771,085
<p>I'm trying to encode some nested lists of data in python in order to save the file as a csv and have others be able to access and use the data in Excel.</p> <p>My data is supplied in <code>UTF8</code>. As part of converting this into an Excel-friendly format, I typically decode from <code>UTF8</code> and encode usi...
0
2016-08-04T15:07:15Z
38,829,478
<p>Solved by ignoring Windows codecs and instead keeping UTF8, and inserting a BOM. I believe my original question had no solution using Windows codecs.</p> <p><a href="http://stackoverflow.com/questions/6002256/is-it-possible-to-force-excel-recognize-utf-8-csv-files-automatically">Is it possible to force Excel recogn...
0
2016-08-08T12:39:13Z
[ "python", "excel", "csv", "utf-8" ]
Psycopg2 shows error
38,771,089
<p>From my understanding psycopg2 comes installed with the Python 2.7. When I run the following module it returns an error.</p> <pre><code>import psycopg2 import sys conn = none Traceback (most recent call last): File "C:/Users/aqureshi/Desktop/Programming/psycopg2.py", line 1, in&lt;module&gt; import psycopg2 File ...
0
2016-08-04T15:07:21Z
38,771,166
<p>The "none" is a <a href="https://docs.python.org/2/library/constants.html" rel="nofollow">built in constant</a> which needs to be capitalised:</p> <pre><code>import psycopg2 import sys conn = None </code></pre> <p>The error occurs because the Python interpreter thinks you are trying to reference a variable named ...
0
2016-08-04T15:10:49Z
[ "python", "psycopg2" ]
Why, when raised to the level of the array and divide it to another array of numbers is obtained, rather than an array?
38,771,091
<p>Why, in the Matlab in the construction of the power of the array and divide it into another array (with the same number of values) obtained just a number, not an array? That line of code:</p> <pre><code>cvDelta = sdDelta.^2/delta; </code></pre> <p>How to recreate this code in Python? In Python, when doing this lin...
0
2016-08-04T15:07:29Z
38,771,441
<p>This should make it</p> <p><code>[sdDelta[i]**2/delta[i] for i in range(len(delta))]</code></p> <p>Or more readable for me </p> <p><code>[x**2/y for x,y in zip(sdDelta, delta)]</code></p>
0
2016-08-04T15:24:01Z
[ "python", "arrays", "matlab" ]
Why, when raised to the level of the array and divide it to another array of numbers is obtained, rather than an array?
38,771,091
<p>Why, in the Matlab in the construction of the power of the array and divide it into another array (with the same number of values) obtained just a number, not an array? That line of code:</p> <pre><code>cvDelta = sdDelta.^2/delta; </code></pre> <p>How to recreate this code in Python? In Python, when doing this lin...
0
2016-08-04T15:07:29Z
38,771,972
<p>For a matlab like experience you should consider using numpy. Following code would do the trick</p> <pre><code>import numpy as np # Define sdDelta and Delta sdDelta = np.array(sdDelta) Delta = np.array(Delta) cvDelta = sdDelta ** 2 / delta </code></pre>
1
2016-08-04T15:48:21Z
[ "python", "arrays", "matlab" ]
python - Can't seem to call a parent class's method from the child
38,771,149
<p>Here is my code:</p> <pre><code>from mutagen.easyid3 import EasyID3 from mutagen import File class MusicFile: """A class representing a particular music file. Children that are intended to be instantiated must initialize fields for the getters that exist in this class. """ def __init__(self, ...
1
2016-08-04T15:10:10Z
38,771,461
<p>All of your instance methods must have self as the first parameter. What's happening here is that in <code>parseBitrate()</code> you renamed <code>self</code> to <code>br</code>. You need <code>parseBitrate(self, br)</code> in order to accept a bitrate. You need to add <code>self</code> to the argument list in other...
2
2016-08-04T15:24:44Z
[ "python", "python-3.x", "inheritance" ]
python regex - no match in script, although it should
38,771,244
<p>I am programming a parser for an old dictionary and I'm trying to find a pattern like re.findall("{.*}", string) in a string. A control print after the check proves, that only a few strings match, although all strings contain a pattern like {...}. Even copying the string and matching it interactively in the idle sh...
1
2016-08-04T15:14:46Z
38,771,711
<p>Try this:</p> <pre><code>re = {0: "{.test1}",1: "{.test1}",2: "{.test1}",3: "{.test1}"} for value in re.itervalues(): if "{" in value: value = value.replace("{"," ") print value </code></pre> <p>or if you want to remove both "{}”</p> <pre><code>for value in re.itervalues(): if "{" in val...
0
2016-08-04T15:34:59Z
[ "python", "regex" ]
python regex - no match in script, although it should
38,771,244
<p>I am programming a parser for an old dictionary and I'm trying to find a pattern like re.findall("{.*}", string) in a string. A control print after the check proves, that only a few strings match, although all strings contain a pattern like {...}. Even copying the string and matching it interactively in the idle sh...
1
2016-08-04T15:14:46Z
38,773,696
<p>Try this</p> <pre><code>data=re.findall(r"\{([^\}]*)}",aParse,re.I|re.S) </code></pre> <p><a href="https://repl.it/Cj8y" rel="nofollow">DEMO</a></p>
0
2016-08-04T17:19:12Z
[ "python", "regex" ]
python regex - no match in script, although it should
38,771,244
<p>I am programming a parser for an old dictionary and I'm trying to find a pattern like re.findall("{.*}", string) in a string. A control print after the check proves, that only a few strings match, although all strings contain a pattern like {...}. Even copying the string and matching it interactively in the idle sh...
1
2016-08-04T15:14:46Z
38,803,481
<p>So, in a really simplified scenario, a lexical entry looks like that: </p> <blockquote> <blockquote> <p>"headword" {meta, meaning} context [reference for context].</p> </blockquote> </blockquote> <p>So, I was chunking (split()) the entry at [...] with a regex. that works fine so far. then, after separating...
0
2016-08-06T10:56:31Z
[ "python", "regex" ]
Creating a 2D array from Nested Dictionaries
38,771,317
<p>I am a student working with python dictionaries for the first time and I'm getting stuck on resorting them in to matrix arrays.</p> <p>I have a nested ordered dictionary describing the temperature and humidity week by week.</p> <pre><code>weather = OrderedDict([(92, OrderedDict([('Mon', 79), ('Tues', 85), ...
3
2016-08-04T15:18:04Z
38,772,857
<p>If you want a 2D array you need to be concatenating your ranges with x and y rather than appending. The reason you're not getting the output you want is x.append(list) inserts the list as an element of x--this means you have</p> <pre><code>[[0, 1, 2, 3], [0, 1, 2, 3],...] </code></pre> <p>when it seems you want</...
0
2016-08-04T16:32:09Z
[ "python", "arrays", "dictionary", "multidimensional-array", "matplotlib" ]
Creating a 2D array from Nested Dictionaries
38,771,317
<p>I am a student working with python dictionaries for the first time and I'm getting stuck on resorting them in to matrix arrays.</p> <p>I have a nested ordered dictionary describing the temperature and humidity week by week.</p> <pre><code>weather = OrderedDict([(92, OrderedDict([('Mon', 79), ('Tues', 85), ...
3
2016-08-04T15:18:04Z
38,773,066
<p>You need to loop through the nested dictionaries appending values to a list. You also should store the day number so as to have something to plot temperature against. The colour for humidity should also be stored for each day. You then need to define the axis label to display the days as strings. The code to do this...
2
2016-08-04T16:44:45Z
[ "python", "arrays", "dictionary", "multidimensional-array", "matplotlib" ]
Creating a 2D array from Nested Dictionaries
38,771,317
<p>I am a student working with python dictionaries for the first time and I'm getting stuck on resorting them in to matrix arrays.</p> <p>I have a nested ordered dictionary describing the temperature and humidity week by week.</p> <pre><code>weather = OrderedDict([(92, OrderedDict([('Mon', 79), ('Tues', 85), ...
3
2016-08-04T15:18:04Z
38,789,673
<p>If it is only the plot you want, this may help</p> <pre><code>from collections import OrderedDict import matplotlib.pyplot as plt weather = OrderedDict([(40, OrderedDict([('Mon', 79), ('Tues', 85), ('Weds', 87), ('Thurs', 83)])), (90, OrderedDict([('Mon', 65), ('Tues', 71), ('Weds', 74), ('Th...
1
2016-08-05T12:49:59Z
[ "python", "arrays", "dictionary", "multidimensional-array", "matplotlib" ]
sklearn - predict top 3-4 labels in multi-label classifications from text documents
38,771,478
<p>I currently have a classifier <code>MultinomialNB()</code> set up using <code>CountVectorizer</code> for feature extraction from text documents, and whilst this works quite well, I want to use the same methodology to predict the top 3-4 labels, not just the top one.</p> <p>The main reason is that there are c.90 lab...
1
2016-08-04T15:25:26Z
38,772,610
<p>Once you have done your predictions, you can get the probability of each labels with:</p> <pre><code>labels_probability = pipeline.predict_proba(test_text) </code></pre> <p>You will get the probability for each label. see <a href="http://scikit-learn.org/stable/modules/generated/sklearn.pipeline.Pipeline.html#skle...
1
2016-08-04T16:19:13Z
[ "python", "scikit-learn", "classification", "text-classification", "multilabel-classification" ]
Pyinstaller with Python 3 doesn't run as it should
38,771,521
<p>I made a commandline python program that uses urllib and queue libraries. I use a menu to give the user a more pleasant experience, but somehow it loops over and over again when I deploy a single-file app using pyinstaller.</p> <p>I did notice that when I run 'python myapp.py' I get the same problem. I wrote the sc...
0
2016-08-04T15:27:14Z
38,772,932
<p>I think this is a problem related to the fact that in Python 2.7 <code>raw_input()</code>should be used for input, rather than in Python 3 where <code>input()</code> should be used. My next guess would be there is something wrong with your tabulation, and your bottom break is never occurring. Please consider posting...
0
2016-08-04T16:36:32Z
[ "python", "python-2.7", "python-3.x", "pyinstaller" ]
Fatal error in launcher: Unable to create process using '"' (even though there are no spaces!)
38,771,604
<p>I am using Python 3.5 and I'm trying to install some modules with pip, but I've had a bunch of difficulties. When I first typed pip install pandas into the Command Prompt, I got this error message:</p> <pre><code>'pip' is not recognized as an internal or external command </code></pre> <p>I went to (<a href="http:/...
0
2016-08-04T15:30:36Z
40,131,224
<p>Just try</p> <pre><code>python -m pip install XXX </code></pre> <p>It worked for me :) </p>
1
2016-10-19T12:18:48Z
[ "python", "python-3.x", "path", "pip" ]
How to specify an RRule taking into account daylight savings time?
38,771,638
<p>I'm trying to use <a href="http://labix.org/python-dateutil#head-470fa22b2db72000d7abe698a5783a46b0731b57" rel="nofollow">python-dateutil</a> to create a rrule to schedule an event to run every day at exactly 6PM EST.</p> <p>The current rrule I'm using is simply:</p> <pre><code>byhour:23; </code></pre> <p>this re...
0
2016-08-04T15:31:48Z
38,785,846
<p>You should not use BYHOUR for this.</p> <p>All you need is an RRULE:FREQ=DAILY <em>but</em> your DTSTART needs to be in local time with timezone id, not in UTC, ie something like:</p> <pre><code>DTSTART;TZID=America/New_York:20160805T180000 RRULE:FREQ=DAILY </code></pre>
2
2016-08-05T09:28:00Z
[ "python", "icalendar", "rrule" ]
check what field value changed in django model
38,771,803
<p>I parse data from a restful API call using django-rest-framework ModelSerializer. Here is the code: </p> <pre><code> url = "API URL HERE" r = requests.get(url) json = r.json() serializer = myModelSerializer(data=json, many=True) if serializer.is_valid(): serializer.save() </code></pre> ...
0
2016-08-04T15:39:33Z
38,779,483
<p>First, you could add a column to your <code>MyModel</code>:</p> <pre><code>updated = models.DateTimeField(auto_now=True) </code></pre> <p>This will update whenever an instance is changed. If you filter on this field in your queryset, you can determine what rows changed and if there are new rows.</p> <p>Finding ou...
1
2016-08-05T00:40:44Z
[ "python", "django", "django-rest-framework" ]
DocumentDB in Docker - "The authorization token is not valid at the current time."
38,771,809
<p>I'm running a Python Tornado application in Docker, and part of the API involves connecting to DocumentDB for storage:</p> <pre><code>client = document_client.DocumentClient(config.uri, {'masterKey': config.key}) db = next((data for data in client.ReadDatabases() if data['id'] == config.db)) coll = next((docs for d...
0
2016-08-04T15:39:43Z
38,777,438
<p>This can be due to your machine time drift(as compared to the server) that keeps on increasing until the difference is one hour.</p> <p>In the exception message, you can see the lag between token start/end time and the current server time.</p>
0
2016-08-04T21:08:36Z
[ "python", "azure", "docker", "tornado", "azure-documentdb" ]
DocumentDB in Docker - "The authorization token is not valid at the current time."
38,771,809
<p>I'm running a Python Tornado application in Docker, and part of the API involves connecting to DocumentDB for storage:</p> <pre><code>client = document_client.DocumentClient(config.uri, {'masterKey': config.key}) db = next((data for data in client.ReadDatabases() if data['id'] == config.db)) coll = next((docs for d...
0
2016-08-04T15:39:43Z
38,790,986
<p>It sounds like the auth tokens expire. So you'll need to generate another one.The error message says "Please create another token and retry".</p> <p>Maybe you're creating the token when you create the container? You could try removing the container to force it to create a new one.</p>
0
2016-08-05T13:53:04Z
[ "python", "azure", "docker", "tornado", "azure-documentdb" ]
DocumentDB in Docker - "The authorization token is not valid at the current time."
38,771,809
<p>I'm running a Python Tornado application in Docker, and part of the API involves connecting to DocumentDB for storage:</p> <pre><code>client = document_client.DocumentClient(config.uri, {'masterKey': config.key}) db = next((data for data in client.ReadDatabases() if data['id'] == config.db)) coll = next((docs for d...
0
2016-08-04T15:39:43Z
38,852,637
<p>According to the <a href="https://msdn.microsoft.com/en-us/library/azure/dn783364.aspx" rel="nofollow">HTTP Status Codes for DocumentDB</a> and your description, the status code <code>403</code> of the exception information means <strong><code>The authorization token expired.</code></strong></p> <p>So the solution ...
0
2016-08-09T13:48:58Z
[ "python", "azure", "docker", "tornado", "azure-documentdb" ]
Django REST Framework - Set request in serializer test?
38,771,852
<p>I built a web app where the back-end is implemented using the Django REST Framework. Now I'm writing unit tests and I have come across a problem in testing my serializer methods. Here is one example of a serializer method I'm struggling with: </p> <pre><code> def get_can_edit(self, obj): request = self.con...
1
2016-08-04T15:41:40Z
38,772,421
<p>You need to <strong>pass <code>context</code> argument</strong> to add <code>request1</code> to serializer's <code>context</code> while instantiating the serializer in your test.</p> <p>From DRF docs on <a href="http://www.django-rest-framework.org/api-guide/serializers/#including-extra-context" rel="nofollow">incl...
2
2016-08-04T16:09:20Z
[ "python", "django", "django-rest-framework" ]
How to ensure only patternProperties that match a particular pattern
38,771,938
<p>I'm using python module validictory to validate dicts / yaml configs.</p> <p>Given the following schema I want to match any count of keys that match "^[0-9x]{3}$" and validate the value with another pattern.</p> <pre><code>SCHEMA = { "type": "object", "patternProperties": { "^[0-9x]{3}$": { ...
0
2016-08-04T15:46:47Z
38,774,035
<p>I can't reproduce your issue. This code works as expected for me (Python 3.5.1, validictory 1.0.2), unless I'm misunderstanding your question?</p> <pre><code>import validictory should_work = { '5xx': 'someValidValue', 'x9x': 'someValidValue' } should_not_work = { '5xx': 'someValidValue', 'foobar':...
0
2016-08-04T17:41:09Z
[ "python" ]
Vectorized date parsing in a pandas series?
38,771,946
<p>I have a <code>pandas.core.series.Series</code> that looks like this:</p> <pre><code>import pandas as pd s = pd.Series(["1/1/1900 8:00:00 AM", "1/1/1900 8:15:00 PM", "1/1/1900 9:02:11 PM"]) </code></pre> <p>I'm trying to just parse out the time and AM/PM indicator, to get something like this: <code>8:00:00 AM</cod...
1
2016-08-04T15:47:13Z
38,772,043
<p>IIUC you can make an additional vectorised <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.join.html" rel="nofollow"><code>str.join</code></a> call on the splitted strings:</p> <pre><code>In [141]: s = pd.Series(["1/1/1900 8:00:00 AM", "1/1/1900 8:15:00 PM", "1/1/1900 9:02:11 PM"]) ...
1
2016-08-04T15:50:43Z
[ "python", "pandas", "text" ]
How do I convert an RGB picture into graysacle using simplecv?
38,771,983
<p>So working with windows, python 2.7 and simplecv I am making a live video with my webcam and want simplecv to give me a grayscale version of the video. Is there any simple way to achieve that? I found the command </p> <pre><code>grayscale() </code></pre> <p>on the opencv page, which should do exactly that but whe...
0
2016-08-04T15:48:44Z
38,778,751
<p>In simple cv theres a function called toGray() for example this may or may not work. SO plz dont down vote me I dont have any rep. :( </p> <pre><code>import SimpleCV as sv img = img.jpg sv.img.jpg.toGray() return gimg.jpg </code></pre>
0
2016-08-04T23:09:31Z
[ "python", "windows", "python-2.7", "opencv", "simplecv" ]
Adding nested dictionaries in Python from yield
38,772,135
<p>If I do something like this:</p> <pre><code>x1={'Count': 11, 'Name': 'Andrew'} x2={'Count': 14, 'Name': 'Matt'} x3={'Count': 17, 'Name': 'Devin'} x4={'Count': 20, 'Name': 'Andrew'} x1 vars=[x1,x2,x3,x4] for i in vars: my_dict[i[group_by_column]]=i my_dict </code></pre> <p>Then I get:</p> <pre><code>defaultdi...
-2
2016-08-04T15:56:02Z
38,772,282
<p>A couple of issues. First, cast_record_stream is a function, I assume, so your first line should be</p> <pre><code>for line in cast_record_stream(): </code></pre> <p>Dictionaries can't have duplicate keys. If your iterator returns two Geoffs, the latter will always overwrite the former. If you expect to have dupli...
-1
2016-08-04T16:03:26Z
[ "python", "dictionary", "nested" ]
Adding nested dictionaries in Python from yield
38,772,135
<p>If I do something like this:</p> <pre><code>x1={'Count': 11, 'Name': 'Andrew'} x2={'Count': 14, 'Name': 'Matt'} x3={'Count': 17, 'Name': 'Devin'} x4={'Count': 20, 'Name': 'Andrew'} x1 vars=[x1,x2,x3,x4] for i in vars: my_dict[i[group_by_column]]=i my_dict </code></pre> <p>Then I get:</p> <pre><code>defaultdi...
-2
2016-08-04T15:56:02Z
38,772,618
<p>I can't reproduce your problem. Here is a full reproduction, except that it works perfectly. This shows that the ideas you described in your OP are correct, and you have some other bug in the real code.</p> <pre><code>cast_list = [ {'Count': 11, 'Name': 'Andrew'}, {'Count': 14, 'Name': 'Matt'}, {'Count'...
0
2016-08-04T16:19:33Z
[ "python", "dictionary", "nested" ]
Python Snake Game Boundries not working
38,772,204
<p>I'm new to python and I'm trying following along with a tutorial that uses PyGame to create a snake like game. For some reason my boundaries are not working. It may be something simple but I can't see any reason why it wouldn't work. I don't get any errors, the snake just goes past the boundaries and the game doesn'...
0
2016-08-04T15:59:25Z
38,772,369
<p>In your exit condition, you're using the equality comparison, not the assignment operator:</p> <pre><code> if lead_x &gt;= display_width or lead_x &lt; 0 or lead_y &gt;= display_height or lead_y &lt; 0: gameOver == True #boundaries </code></pre> <p>in the above, </p> <pre><code>gameOver == True </code>...
2
2016-08-04T16:07:16Z
[ "python", "python-3.x", "pygame" ]
Prometheus to track requests in auto-scalled servers
38,772,233
<p>I am trying to use <a href="https://prometheus.io/docs/introduction/overview/" rel="nofollow">Prometheus</a> to track the number of requests to my server over time. Since my servers will be auto-scalled horizontally using Google Compute Engine, I can only push my metric to the remote push gateway. My servers will be...
2
2016-08-04T16:01:00Z
38,774,790
<blockquote> <p>Since my servers will be auto-scalled horizontally using Google Compute Engine, I can only push my metric to the remote push gateway. My servers will be deleted and re-created at any given time.</p> </blockquote> <p>That's not quite true. You can use service discovery to automatically discover your n...
1
2016-08-04T18:25:37Z
[ "python", "django", "google-compute-engine", "autoscaling", "prometheus" ]
Add UUID's to pandas DF
38,772,246
<p>Say I have a pandas DataFrame like so:</p> <pre><code>df = pd.DataFrame({'Name': ['John Doe', 'Jane Smith', 'John Doe', 'Jane Smith','Jack Dawson','John Doe']}) df: Name 0 John Doe 1 Jane Smith 2 John Doe 3 Jane Smith 4 Jack Dawson 5 John Doe </code></pre> <p>And I want ...
0
2016-08-04T16:01:33Z
38,772,816
<p>How about this</p> <pre><code>names = df['Name'].unique() for name in names: df.loc[df['Name'] == name, 'UUID'] = uuid.uuid4() </code></pre> <p>could shorten it to</p> <pre><code>for name in df['Name'].unique(): df.loc[df['Name'] == name, 'UUID'] = uuid.uuid4() </code></pre>
0
2016-08-04T16:30:16Z
[ "python", "pandas", "uuid" ]
problems with display after XML parsing
38,772,257
<p>I am parsing an XML document that has a following structure:</p> <pre><code>&lt;Distlist&gt; &lt;DistDoc&gt; &lt;Metadata&gt;&lt;/Metadata&gt; &lt;ArchiveDoc&gt; &lt;Article&gt; &lt;Para&gt;aaaaaa&lt;/Para&gt; &lt;Para&gt;bbbbbb&lt;/Para&gt; &lt;Para&gt;cccccc&lt;/P...
0
2016-08-04T16:02:15Z
38,772,494
<p>Iterate over <code>article</code> nodes and join the texts of <code>para</code> nodes:</p> <pre><code>for article in root.xpath(".//Article"): texts = article.xpath(".//Para/text()") print("\n".join(texts)) </code></pre>
1
2016-08-04T16:12:51Z
[ "python", "xml", "python-3.x", "parsing", "lxml" ]
Python 3 using matplotlib to display pie chart with percentages , TypeError
38,772,363
<p>I am making a simple pie chart with matplotlib with only 2 segments. When I add in a variable 'fracs' at the start of the pie command I get an error regarding the "explode" argument. Here is my code :</p> <pre><code>import matplotlib.pyplot as plt dataFile = open("data.txt") #open the file with the data bigData = ...
0
2016-08-04T16:07:03Z
38,772,597
<p>According to the matplotlib documentation, the <code>pie()</code> function takes one argument and then keyword arguments.</p> <pre><code>matplotlib.pyplot.pie(x, explode=None, labels=None, colors=None, autopct=None, pctdistance=0.6, shadow=False, labeldistance=1.1, startangle=None, radius=None, counterclock=True...
1
2016-08-04T16:18:28Z
[ "python", "matplotlib", "charts" ]
Dask worker persistent variables
38,772,455
<p>Is there a way with dask to have a variable that can be retrieved from one task to another. I mean a variable that I could lock in the worker and then retrieve in the same worker when i execute another task.</p>
2
2016-08-04T16:10:47Z
38,772,791
<p>The workers themselves are just Python processes, so you could do tricks with <code>globals()</code>. </p> <p>However, it is probably cleaner to emit values and pass these between tasks. Dask retains the right to rerun functions and run them on different machines, so depending on global state or worker-specific s...
1
2016-08-04T16:29:05Z
[ "python", "dask" ]
Trying to add numbers from a file subtrack them and put them into another file
38,772,480
<pre><code>file = open("byteS-F_FS_U.toff","r") f = file.readline() s = file.readline() file.close() f = int(f) s = int(s) u = s - f file = open("bytesS-F_FS_U","w") file.write(float(u) + '\n') file.close() </code></pre> <p>This is what its says when I run the code :</p> <pre class="lang-none prettyprint-override"><c...
-1
2016-08-04T16:12:15Z
38,773,605
<p>First, you need to put full path of the file you're trying to open!</p> <p>With that first thing fixed, I created a loop program which opens the file every 10 seconds and writes the result to the other file. Exceptions are handled so if another process is writing in the file while being opened/read it does not cras...
0
2016-08-04T17:13:59Z
[ "python", "file" ]
Trying to add numbers from a file subtrack them and put them into another file
38,772,480
<pre><code>file = open("byteS-F_FS_U.toff","r") f = file.readline() s = file.readline() file.close() f = int(f) s = int(s) u = s - f file = open("bytesS-F_FS_U","w") file.write(float(u) + '\n') file.close() </code></pre> <p>This is what its says when I run the code :</p> <pre class="lang-none prettyprint-override"><c...
-1
2016-08-04T16:12:15Z
38,776,065
<p>You cannot do float + string, then you should do smth like:</p> <pre><code>"{0}\n".format(float(u)) </code></pre>
0
2016-08-04T19:42:15Z
[ "python", "file" ]
ImportError: No module named context_processors
38,772,498
<p>I am running the command in my django project:-</p> <pre><code>$python manage.py runserver </code></pre> <p>then I am getting the error like:-</p> <pre><code>from django.core.context_processors import csrf ImportError: No module named context_processors </code></pre> <p>here is results of </p> <pre><code>$ pip ...
1
2016-08-04T16:12:59Z
38,772,814
<p>The <code>csrf</code> module is moved from <code>django.core.context_processors</code> to <code>django.views.decorators</code> in the latest release. You can refer it <a href="https://docs.djangoproject.com/ja/1.9/ref/csrf/" rel="nofollow">here</a></p>
4
2016-08-04T16:30:10Z
[ "python", "django" ]
Evaluation function inside numpy indexing array with PIL images
38,772,590
<p>I'm working on image segmentation using PIL where I'm using a nested iteration to index the image, but it runs very slow. <code></p> <pre><code>def evalPixel((r,g,b), sess): pixel = [float(r)/255, float(g)/255, float(b)/255] test = sess.run(y, feed_dict={x: [pixel]}) return test[0][0] ... ... # sess =...
0
2016-08-04T16:18:02Z
38,772,859
<p>Try using the following:</p> <pre><code>im = np.array(rgb) im = [[evalPixel(x,sess) &lt; 0.6 for x in row] for row in im] </code></pre> <p>By using constructors to generate rows and columns, it's possible to avoid accidentally applying a function with a single argument (in this case, a tuple) to an entire row or c...
0
2016-08-04T16:32:13Z
[ "python", "numpy", "python-imaging-library" ]
Evaluation function inside numpy indexing array with PIL images
38,772,590
<p>I'm working on image segmentation using PIL where I'm using a nested iteration to index the image, but it runs very slow. <code></p> <pre><code>def evalPixel((r,g,b), sess): pixel = [float(r)/255, float(g)/255, float(b)/255] test = sess.run(y, feed_dict={x: [pixel]}) return test[0][0] ... ... # sess =...
0
2016-08-04T16:18:02Z
38,798,484
<p>Your function <code>evalPixel</code> takes as first argument a tuple, but your numpy array does not contain (and cannot contain) tuples. You have to rewrite that function to be able to work with numpy arrays.</p> <p>I tried to make a working example for you, but the code you're sharing contains a lot of unknown var...
0
2016-08-05T22:19:47Z
[ "python", "numpy", "python-imaging-library" ]
rebinning a list of numbers in python
38,772,640
<p>I've a question about rebinning a list of numbers, with a desired bin-width. It's basically what a frequency histogram does, but I don't want the plot, just the bin number and the number of occurrences for each bin.</p> <p>So far I've already written some code that does what I want, but it's not very efficient. Giv...
0
2016-08-04T16:20:45Z
38,773,098
<p>Numpy has a method called <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.histogram.html" rel="nofollow">np.histogram</a> which does the work for you. It also scales pretty well.</p>
0
2016-08-04T16:46:13Z
[ "python", "bin", "dynamic-rebinding" ]
rebinning a list of numbers in python
38,772,640
<p>I've a question about rebinning a list of numbers, with a desired bin-width. It's basically what a frequency histogram does, but I don't want the plot, just the bin number and the number of occurrences for each bin.</p> <p>So far I've already written some code that does what I want, but it's not very efficient. Giv...
0
2016-08-04T16:20:45Z
38,773,485
<p>If you use <code>a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]</code>, your solution is:</p> <blockquote> <p>[[ 0. 3.]<br> [ 3. 3.]<br> [ 6. 3.]]</p> </blockquote> <p>How you interpret this? The intervals are 0..2, 3..5, 6..8? I think you are missing something.</p> <p>Using <a href="http://docs.scipy.org/doc/numpy/...
1
2016-08-04T17:07:48Z
[ "python", "bin", "dynamic-rebinding" ]
Scrapy Images Downloading
38,772,662
<p>My spider runs without displaying any errors but the images are not stored in the folder here are my scrapy files:</p> <p><strong>Spider.py:</strong></p> <pre><code>import scrapy import re import os import urlparse from scrapy.spiders import CrawlSpider, Rule from scrapy.linkextractors import LinkExtractor from sc...
0
2016-08-04T16:22:24Z
38,773,029
<p>Since you don't know what to put in the pipelines I assume you can use the default pipeline for images provided by scrapy so in the <code>settings.py</code> file you can just declare it like</p> <pre><code>ITEM_PIPELINES = { 'scrapy.pipelines.images.ImagesPipeline':1 } </code></pre> <p>Also, your images path is wr...
2
2016-08-04T16:42:41Z
[ "python", "image", "scrapy" ]
Scrapy Images Downloading
38,772,662
<p>My spider runs without displaying any errors but the images are not stored in the folder here are my scrapy files:</p> <p><strong>Spider.py:</strong></p> <pre><code>import scrapy import re import os import urlparse from scrapy.spiders import CrawlSpider, Rule from scrapy.linkextractors import LinkExtractor from sc...
0
2016-08-04T16:22:24Z
38,810,007
<p>My Working end result:</p> <p><strong>spider.py</strong>:</p> <pre><code>import scrapy import re import urlparse from scrapy.spiders import CrawlSpider, Rule from scrapy.linkextractors import LinkExtractor from scrapy.loader.processors import Join, MapCompose, TakeFirst from scrapy.pipelines.images import ImagesPi...
1
2016-08-07T01:07:18Z
[ "python", "image", "scrapy" ]
Python: Can this be done in a single list comprehension statement
38,772,834
<p>What I am trying to do is extracting zeroth element in a list and first element in another list of the given 2 dimensional list.</p> <pre><code>baseball = [[180, 78.4], [215, 102.7], [210, 98.5], [188, 75.2]] x = [ a[0] for a in baseball ] y = [ a[1] for a in baseball ] pr...
2
2016-08-04T16:31:06Z
38,772,981
<p>Assuming it's rectangular (ie. the length of the inner lists is consistent), you can implement the following:</p> <pre><code>def transpose(matrix): return [[matrix[j][i] for j in range(len(matrix))] for i in range(len(matrix[0]))] </code></pre> <p>Then, your problem is just a call to transpose (<code>x, y = tr...
2
2016-08-04T16:39:47Z
[ "python", "list-comprehension" ]
Python: Can this be done in a single list comprehension statement
38,772,834
<p>What I am trying to do is extracting zeroth element in a list and first element in another list of the given 2 dimensional list.</p> <pre><code>baseball = [[180, 78.4], [215, 102.7], [210, 98.5], [188, 75.2]] x = [ a[0] for a in baseball ] y = [ a[1] for a in baseball ] pr...
2
2016-08-04T16:31:06Z
38,773,046
<p>If you don't mind tuples:</p> <pre><code>baseball = [[180, 78.4], [215, 102.7], [210, 98.5], [188, 75.2]] x,y = zip(*baseball) </code></pre> <p>If you really want lists:</p> <pre><code>x,y = map(list,zip(*baseball)) </code></pre> <p>If you had more than two elements in each...
2
2016-08-04T16:43:58Z
[ "python", "list-comprehension" ]
Python Logging module formatter
38,772,838
<p>Having a hard time understanding the formatter options. specifically the string replacements. If I have a really long python file name, how do I get it to cut it off to keep everything even?</p> <pre><code>formatter = logging.Formatter('%(asctime)s %(name)-15s %(threadName)-10s %(levelname)-8s %(message)s') </cod...
0
2016-08-04T16:31:17Z
38,773,117
<p>Just tested it:</p> <pre><code>formatter = logging.Formatter('%(asctime)s %(name)-15.5s %(threadName)-10s %(levelname)-8s %(message)s') </code></pre> <p>Truncates the loggers's name to 5 chars. How to combine that with padding is another question.</p>
1
2016-08-04T16:47:26Z
[ "python", "logging", "formatter" ]