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
How to get the Incorrectly clustered instances after ClusterEvaluation through the latest weka-python-wrapper 0.3.8?
39,818,194
<p>I'm learning the Clustering of Weka and trying to get the "Incorrectly clustered instances" after 'ClusterEvaluation' with the python-weka-wrapper 0.3.8 (python 2.7).</p> <p>Currently, I have the class attribute in the input arff file, build the data model successfully, and can get the output of num of clusters &am...
0
2016-10-02T14:50:28Z
39,821,203
<p>If your <code>Instances</code> object for testing has a class attribute set when you perform cluster evaluation using the <code>ClusterEvaluation</code> class, you can use the <code>classes_to_clusters</code> property to obtain the mapping that has been collected while evaluating the clusterer. The equivalent Java m...
0
2016-10-02T20:10:21Z
[ "python", "weka" ]
how to .writerow() to only 1 row in csv file ?
39,818,202
<p>guys currently in my code it changes the 3rd row but for all rows , I want it to only change the row with the entered GTIN by the user.</p> <p>current code :</p> <pre><code>file=open("stock.csv") stockfile= csv.reader(file) for line in stockfile: if GTIN in line: currentstock= line[2] targetsto...
0
2016-10-02T14:51:16Z
39,818,534
<p>use the <code>csv</code> module: <a href="https://docs.python.org/3/library/csv.html" rel="nofollow">https://docs.python.org/3/library/csv.html</a></p> <p>It has a <code>csv.reader()</code> and <code>csv.writer()</code>. Read the file into memory, iterate over it doing calcs/replacements, then write each row to a ...
1
2016-10-02T15:27:26Z
[ "python", "file", "python-3.x", "csv" ]
how to .writerow() to only 1 row in csv file ?
39,818,202
<p>guys currently in my code it changes the 3rd row but for all rows , I want it to only change the row with the entered GTIN by the user.</p> <p>current code :</p> <pre><code>file=open("stock.csv") stockfile= csv.reader(file) for line in stockfile: if GTIN in line: currentstock= line[2] targetsto...
0
2016-10-02T14:51:16Z
39,820,470
<p>I answered one of your other questions before you were using csvreader but it looks like it got deleted. But the principle is the same. As I stated in one of the comments, I don't think you should keep reopening/rereading <code>stock.txt</code>. Just read it line by line then write line by line to an output file:</p...
0
2016-10-02T18:51:44Z
[ "python", "file", "python-3.x", "csv" ]
How to save multiple output in multiple file where each file has a different title coming from an object in python?
39,818,241
<p>I'm scraping rss feed from a web site (<a href="http://www.gfrvitale.altervista.org/index.php/autismo-in?format=feed&amp;type=rss" rel="nofollow">http://www.gfrvitale.altervista.org/index.php/autismo-in?format=feed&amp;type=rss</a>). I have wrote down a script to extract and purifie the text from every of the feed....
0
2016-10-02T14:54:58Z
39,818,526
<p>You need to put the comma after <code>%tit</code></p> <p>should be:</p> <pre><code>#save each file with it's proper title with codecs.open("testo_%s" %tit, "w", encoding="utf-8") as f: f.write(s) f.close() </code></pre> <p>However, if your file name has invalid characters it will return an error (i.e <c...
0
2016-10-02T15:26:58Z
[ "python", "rss", "feed" ]
How to save multiple output in multiple file where each file has a different title coming from an object in python?
39,818,241
<p>I'm scraping rss feed from a web site (<a href="http://www.gfrvitale.altervista.org/index.php/autismo-in?format=feed&amp;type=rss" rel="nofollow">http://www.gfrvitale.altervista.org/index.php/autismo-in?format=feed&amp;type=rss</a>). I have wrote down a script to extract and purifie the text from every of the feed....
0
2016-10-02T14:54:58Z
39,820,854
<p>First off, you misplaced the comma, it should be after the <code>%tit</code> not before.</p> <p>Secondly, you don't need to close the file because the <code>with</code> statement that you use, does it automatically for you. And where did the codecs came from? I don't see it anywhere else.... anyway, the correct <co...
0
2016-10-02T19:34:03Z
[ "python", "rss", "feed" ]
How to make indexing work with ItemLoader's add_xpath method
39,818,248
<p>I'm trying to rewrite this piece of code to use <code>ItemLoader</code> class:</p> <pre><code>import scrapy from ..items import Book class BasicSpider(scrapy.Spider): ... def parse(self, response): item = Book() # notice I only grab the first book among many there are on the page ...
0
2016-10-02T14:55:43Z
39,819,264
<p>A problem with your code is that Xpath uses one-based indexing. Another problem is that the index bracket should be inside the string you pass to the add_xpath method.</p> <p>So the correct code would look like this:</p> <pre><code>l.add_xpath('title', '(//*[@class="link linkWithHash detailsLink"]/@title)[1]') </c...
0
2016-10-02T16:43:13Z
[ "python", "xpath", "scrapy" ]
Why don't string variables update when they are changed
39,818,267
<p>Say we have some code like so :</p> <pre><code>placehold = "6" string1 = "this is string one and %s" % placehold print string1 placehold = "7" print string1 </code></pre> <p>When run, both of the print statements return as if placehold were ALWAYS 6. However, just before the second statement ran, placehold was c...
0
2016-10-02T14:58:07Z
39,818,297
<p><code>string1</code> will use whatever value of <code>placehold</code> existed at the time <code>string1</code> was declared. In your example, that value happens to be <code>"6"</code>. To get <code>string1</code> to "return with 7" you would need to reassign it (<code>string1 = "this is string one and %s" % placeho...
1
2016-10-02T15:01:36Z
[ "python", "string" ]
Why don't string variables update when they are changed
39,818,267
<p>Say we have some code like so :</p> <pre><code>placehold = "6" string1 = "this is string one and %s" % placehold print string1 placehold = "7" print string1 </code></pre> <p>When run, both of the print statements return as if placehold were ALWAYS 6. However, just before the second statement ran, placehold was c...
0
2016-10-02T14:58:07Z
39,818,302
<p>Because you have already assigned a value to that variable once you execute the statement.</p> <p>It sounds like you'd rather need a function such as:</p> <pre><code>def f(placehold): return "this is string one and %s" % placehold </code></pre> <p>Now you can <code>print(f("7"))</code> to achieve the desired ...
4
2016-10-02T15:02:44Z
[ "python", "string" ]
Why don't string variables update when they are changed
39,818,267
<p>Say we have some code like so :</p> <pre><code>placehold = "6" string1 = "this is string one and %s" % placehold print string1 placehold = "7" print string1 </code></pre> <p>When run, both of the print statements return as if placehold were ALWAYS 6. However, just before the second statement ran, placehold was c...
0
2016-10-02T14:58:07Z
39,818,365
<p>When you do:</p> <pre><code>string1 = "this is string one and %s" % placehold </code></pre> <p>You are creating a string <code>string1</code> with <code>%s</code> replaced by the value of <code>placehold</code> On later changing the value of <code>placehold</code> it won't have any impact on <code>string1</code> a...
3
2016-10-02T15:08:29Z
[ "python", "string" ]
Why don't string variables update when they are changed
39,818,267
<p>Say we have some code like so :</p> <pre><code>placehold = "6" string1 = "this is string one and %s" % placehold print string1 placehold = "7" print string1 </code></pre> <p>When run, both of the print statements return as if placehold were ALWAYS 6. However, just before the second statement ran, placehold was c...
0
2016-10-02T14:58:07Z
39,818,453
<p>Strings are immutable and can't be changed, but what you're trying to do doesn't work with mutable objects either, so mutability (or lack of it) is something of a red herring here.</p> <p>The real reason is that Python does not work like Excel. Objects do not remember all the operations that have been performed on ...
2
2016-10-02T15:18:34Z
[ "python", "string" ]
/bin/sh: 1: python: not found while running docker container
39,818,273
<p>This is my docker file</p> <pre><code>FROM ubuntu:14.04 ADD ./file.py ./ CMD python file.py </code></pre> <p>I am building using below command: </p> <pre><code>docker build -t myimage . </code></pre> <p>And running using this: </p> <pre><code>docker run myimage </code></pre> <p>And then getting below error a...
0
2016-10-02T14:59:10Z
39,818,905
<p>Use <a href="https://hub.docker.com/_/python" rel="nofollow">official Python Docker image</a>:</p> <pre><code>FROM python:3.5 COPY ./file.py ./ CMD python file.py </code></pre>
1
2016-10-02T16:04:07Z
[ "python", "docker" ]
Python Numpy : operands could not be broadcast together with shapes when producting matrix
39,818,358
<pre><code>import numpy as np def grams(A): (m,n) = A.shape Q = A R = np.zeros((n,n)) for i in range(0,n-1): R[i,i] = np.linalg.norm(Q[:,i]) Q[:,i] =Q[:,i]/R[i,i] R[i,i+1:n] = np.transpose(Q[:,i])*Q[:,i+1:n] Q[:,i+1:n] = Q[:,i+1:n+1]-Q[:,i]*R[i,i+1:n] R[n,n] = np.lina...
0
2016-10-02T15:08:07Z
39,818,677
<p>Asterisk <code>*</code> performs <strong>elementwise multiplication</strong> in <code>numpy</code>. Your code reads:</p> <pre><code>R[i,i+1:n] = np.transpose(Q[:,i])*Q[:,i+1:n] </code></pre> <p><code>np.transpose(Q[:,i])</code> has dimensions <code>(3, 1)</code> and <code>Q[:,i+1:n]</code> <code>(3, 2)</code>, so ...
0
2016-10-02T15:42:03Z
[ "python", "numpy" ]
Python Numpy : operands could not be broadcast together with shapes when producting matrix
39,818,358
<pre><code>import numpy as np def grams(A): (m,n) = A.shape Q = A R = np.zeros((n,n)) for i in range(0,n-1): R[i,i] = np.linalg.norm(Q[:,i]) Q[:,i] =Q[:,i]/R[i,i] R[i,i+1:n] = np.transpose(Q[:,i])*Q[:,i+1:n] Q[:,i+1:n] = Q[:,i+1:n+1]-Q[:,i]*R[i,i+1:n] R[n,n] = np.lina...
0
2016-10-02T15:08:07Z
39,819,467
<p>Lets recreate this in a small case</p> <pre><code>In [105]: n=4 In [106]: m,n=2,4 In [107]: Q=np.arange(m*n).reshape(m,n) In [108]: R=np.zeros((n,n)) </code></pre> <p>So for one step, the target is a (3,) slot in <code>R</code></p> <pre><code>In [109]: i=0 In [110]: R[i,i+1:n] Out[110]: array([ 0., 0., 0.]) In ...
1
2016-10-02T17:04:41Z
[ "python", "numpy" ]
How to reindex a python array to move polyline starting point?
39,818,381
<p>I have a python array defining the points for a polyline P(x,y,z). I need to align the points with points on another polyline - to be precise, the point with index 0 on polyline 1 should be close to the point with index 0 of the second polyline. </p> <p>Think of a polyline circle. How can I move the "index number" ...
0
2016-10-02T15:10:52Z
39,820,075
<p>To shift to left by x points(assuming x is less than the length of array):</p> <pre><code>newPolyline = polyline[x:] + polyline[:x] </code></pre> <p>To shift right:</p> <pre><code>newPolyline = polyline[len(polyline) - x:] + polyline[:len(polyline) - x] </code></pre>
0
2016-10-02T18:10:48Z
[ "python", "arrays", "numpy" ]
Make view accessible only through redirect and from only one view in Django
39,818,402
<p>How do I make a view to be only accessible through <em>redirect</em> and from a only a particular <em>view</em>?</p> <p><strong>urls.py</strong>:</p> <pre><code>#Assuming namespace = 'myApp' url(r'^redarekt/$', views.redarekt, name='redarekt'), url(r'^reciva/$', views.reciva, name='reciva'), </code></pre> <p><st...
0
2016-10-02T15:11:52Z
39,819,628
<p>You can use <a href="https://docs.djangoproject.com/en/1.10/topics/http/sessions/#using-sessions-in-views" rel="nofollow"><code>request.session</code></a></p> <pre><code>@login_required() def redarekt(request): if request.user.is_authenticated() and request.user.is_active: request.session['pp_redarekt']...
1
2016-10-02T17:24:06Z
[ "python", "django" ]
TypeError: sequence item 1: expected a bytes-like object, str found
39,818,425
<p>I am trying to extract English titles from a wiki titles dump that's in a text file using regex in Python 3. The wiki dump contains titles in other languages also and some symbols. Below is my code:</p> <pre><code>with open('/Users/some/directory/title.txt', 'rb')as f: text=f.read() letters_only = re.sub(b"...
1
2016-10-02T15:14:59Z
39,818,449
<p>You have to choose between binary and text mode.</p> <p>Either you open your file as <code>rb</code> and then you can use <code>re.sub(b"[^a-zA-Z]", b" ", text)</code> (<code>text</code> is a <code>bytes</code> object)</p> <p>Or you open your file as <code>r</code> and then you can use <code>re.sub("[^a-zA-Z]", "...
2
2016-10-02T15:18:04Z
[ "python", "regex", "python-3.x" ]
TypeError: sequence item 1: expected a bytes-like object, str found
39,818,425
<p>I am trying to extract English titles from a wiki titles dump that's in a text file using regex in Python 3. The wiki dump contains titles in other languages also and some symbols. Below is my code:</p> <pre><code>with open('/Users/some/directory/title.txt', 'rb')as f: text=f.read() letters_only = re.sub(b"...
1
2016-10-02T15:14:59Z
39,818,472
<p>The problem is with the <code>repl</code> argument you supply, it isn't a <code>bytes</code> object:</p> <pre><code>letters_only = re.sub(b"[^a-zA-Z]", " ", b'Hello2World') # TypeError: sequence item 1: expected a bytes-like object, str found </code></pre> <p>Instead, supply <code>repl</code> as a bytes instance <...
4
2016-10-02T15:21:04Z
[ "python", "regex", "python-3.x" ]
TypeError: sequence item 1: expected a bytes-like object, str found
39,818,425
<p>I am trying to extract English titles from a wiki titles dump that's in a text file using regex in Python 3. The wiki dump contains titles in other languages also and some symbols. Below is my code:</p> <pre><code>with open('/Users/some/directory/title.txt', 'rb')as f: text=f.read() letters_only = re.sub(b"...
1
2016-10-02T15:14:59Z
39,818,516
<p>You can't use a <code>byte</code> string for your regex match when the replacement string isn't.<br> Essentially, you can't mix different objects (<code>byte</code>s and <code>string</code>s) when doing most tasks. In your code above, you are using a binary search string and a binary text, but your replacement strin...
1
2016-10-02T15:25:42Z
[ "python", "regex", "python-3.x" ]
retrieve series of slices of column headers based on truth of dataframe values
39,818,559
<p>consider the dataframe <code>df</code></p> <pre><code>np.random.seed([3,1415]) df = pd.DataFrame(np.random.choice((0, 1), (3, 3)), columns=['blah', 'meep', 'zimp']) df </code></pre> <p><a href="http://i.stack.imgur.com/H2ovB.png" rel="nofollow"><img src="http://i.stack.imgur.com/H2ovB.png" alt="e...
3
2016-10-02T15:29:22Z
39,819,278
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.mul.html" rel="nofollow"><code>mul</code></a> with <code>list comprehension</code>:</p> <pre><code>df = df.mul(df.columns.to_series(), axis=1) print (df) blah meep zimp 0 meep 1 blah 2 blah ...
3
2016-10-02T16:44:58Z
[ "python", "pandas", "numpy" ]
retrieve series of slices of column headers based on truth of dataframe values
39,818,559
<p>consider the dataframe <code>df</code></p> <pre><code>np.random.seed([3,1415]) df = pd.DataFrame(np.random.choice((0, 1), (3, 3)), columns=['blah', 'meep', 'zimp']) df </code></pre> <p><a href="http://i.stack.imgur.com/H2ovB.png" rel="nofollow"><img src="http://i.stack.imgur.com/H2ovB.png" alt="e...
3
2016-10-02T15:29:22Z
39,820,411
<p>I suggest to use <code>dot</code> after building a series of atomic lists:</p> <pre><code>s = pd.Series([[col] for col in df.columns]) s.index = df.columns df.dot(s) Out[35]: 0 [meep] 1 [blah] 2 [blah, zimp] dtype: object </code></pre>
2
2016-10-02T18:46:06Z
[ "python", "pandas", "numpy" ]
retrieve series of slices of column headers based on truth of dataframe values
39,818,559
<p>consider the dataframe <code>df</code></p> <pre><code>np.random.seed([3,1415]) df = pd.DataFrame(np.random.choice((0, 1), (3, 3)), columns=['blah', 'meep', 'zimp']) df </code></pre> <p><a href="http://i.stack.imgur.com/H2ovB.png" rel="nofollow"><img src="http://i.stack.imgur.com/H2ovB.png" alt="e...
3
2016-10-02T15:29:22Z
39,820,773
<p>Another solution using sum of products using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.sum.html" rel="nofollow"><code>np.sum</code></a> followed by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.split.html" rel="nofollow"><code>str.split</code></a> as shown:...
2
2016-10-02T19:25:23Z
[ "python", "pandas", "numpy" ]
retrieve series of slices of column headers based on truth of dataframe values
39,818,559
<p>consider the dataframe <code>df</code></p> <pre><code>np.random.seed([3,1415]) df = pd.DataFrame(np.random.choice((0, 1), (3, 3)), columns=['blah', 'meep', 'zimp']) df </code></pre> <p><a href="http://i.stack.imgur.com/H2ovB.png" rel="nofollow"><img src="http://i.stack.imgur.com/H2ovB.png" alt="e...
3
2016-10-02T15:29:22Z
39,822,673
<p>use <code>where</code> and <code>stack</code> to drop <code>0</code>s then grab indices left over</p> <pre><code># number of levels in columns num = df.columns.nlevels # handy list for stacking lvls = list(range(num)) # reverse (sort of) list for unstacking rlvls = [x * -1 - 1 for x in lvls] # get just levels in i...
1
2016-10-02T23:10:40Z
[ "python", "pandas", "numpy" ]
Python How to re-assign a static variable value of a python class with a return value of method
39,818,609
<p>I am trying to declare a static variable inside the class. I am trying to add a return value of a code inside a function. </p> <p>The return value is assigned to the static variable inside the class but when i try to create an object of the class and access the static variable value from another class, it still ret...
0
2016-10-02T15:34:05Z
39,818,703
<p>If you make auth_token a @classmethod, it will behave the way you want</p> <pre><code> @classmethod def auth_token(cls, token): cls.token = token return cls.token </code></pre> <p>I'm not sure I love the design, but that's your affair.</p> <p>EDIT: Here's an example of this code in action, in resp...
0
2016-10-02T15:44:35Z
[ "python", "python-2.7" ]
Parsing numbers in a given range with pyparsing
39,818,622
<p>How to extract numbers in a given range using pyparsing? I tried:</p> <pre><code># Number lower than 12: number = Word(nums).addCondition(lambda tokens: int(tokens[0]) &lt; 12) test_data = "10 23 11 14 115" print number.searchString(test_data) </code></pre> <p>but it returns:</p> <pre><code>[['10'], ['3'], ['11'...
1
2016-10-02T15:36:02Z
39,821,614
<p>The main issue here is that searchString (and the underlying scanString) go through the input string character by character looking for matches. So in your input (with position header for reference):</p> <pre><code> 1 012345678901234 &lt;- position 10 23 11 14 115 </code></pre> <p>searchString goes throug...
0
2016-10-02T20:54:02Z
[ "python", "pyparsing" ]
scrapy NBA schedule not collating correctly
39,818,661
<p>Trying to get a simple web scrape up and running. The goal is to dump the dt gm tm and ntv classes into csv - eventually. Here it is json for clarity. One step at a time.</p> <p>here's the spider:</p> <pre><code>import scrapy class QuotesSpider(scrapy.Spider): name = "schedule" start_urls = [ 'htt...
0
2016-10-02T15:40:47Z
39,828,487
<p>You probably want to be more specific on the table and rows you select.</p> <p>Take a look at the HTML for the start of the schedule:</p> <pre><code> &lt;div id="scheduleMain" style="margin:0 5px 0 0!important;"&gt; &lt;table border="0" cellpadding="0" cellspacing="0" class="genSchedTable tvindex"&gt; &...
0
2016-10-03T09:32:33Z
[ "python", "scrapy" ]
Python: dynamically accessing nested dictionary keys?
39,818,669
<p>Is there some simple way to access nested dictionary key when at first you don't know which key you will be accessing?</p> <p>For example:</p> <pre><code>dct = {'label': 'A', 'config': {'value': 'val1'}} </code></pre> <p>In this dictionary I will need to access either <code>label</code> key or <code>value</code> ...
0
2016-10-02T15:41:09Z
39,820,877
<p>If you know the key to be traversed, you can try out the following. This would work for any level of nested dicts. </p> <pre><code>dct = {'label': 'A', 'config': {'value': 'val1'}} label = True key = ('label',) if not label: key = ('config', 'value') ret = dct for k in key: ret = ret[k] print ret </code><...
1
2016-10-02T19:36:20Z
[ "python", "python-2.7", "dictionary" ]
How do you get data from QTableWidget that user has edited (Python with PyQT)
39,818,680
<p>I asked a similar question before, but the result didn't work, and I don't know why. Here was the original code:</p> <pre><code>def click_btn_printouts(self): self.cur.execute("""SELECT s.FullName, m.PreviouslyMailed, m.nextMail, m.learnersDate, m.RestrictedDate, m.DefensiveDate FROM Stu...
0
2016-10-02T15:42:35Z
39,837,800
<p>It is always difficult to answer without a minimal working example, so I produced one myself and put the suggestion from the <a href="http://stackoverflow.com/questions/39742199/how-do-i-get-the-information-that-the-user-has-changed-in-a-table-in-pyqt-with-p">other post</a> in, modifying it, such that it outputs the...
1
2016-10-03T18:07:44Z
[ "python", "pyqt" ]
Create dictionary where keys are variable names
39,818,733
<p>I quite regularly want to a dictionary where the key names are the variable names. For example if i have the variable <code>a</code> and <code>b</code> then to have a dictionary <code>{"a":a, "b":b}</code> (typically to return data at the end of a function).</p> <p>Is there any (ideally built in) ways in python of...
0
2016-10-02T15:47:33Z
39,818,804
<p>Have you tried something like:</p> <pre><code>a, b, c, d = 1, 2, 3, 4 dt = {k:v for k, v in locals().items() if not k.startswith('__')} print(dt) {'a': 1, 'd': 4, 'b': 2, 'c': 3} </code></pre>
0
2016-10-02T15:54:33Z
[ "python", "python-3.x" ]
Create dictionary where keys are variable names
39,818,733
<p>I quite regularly want to a dictionary where the key names are the variable names. For example if i have the variable <code>a</code> and <code>b</code> then to have a dictionary <code>{"a":a, "b":b}</code> (typically to return data at the end of a function).</p> <p>Is there any (ideally built in) ways in python of...
0
2016-10-02T15:47:33Z
39,818,967
<p>You can write your own function for <code>create_dict</code></p> <pre><code>def create_dict(*args): return dict({i:eval(i) for i in args}) a = "yo" b = 7 print (create_dict("a", "b")) </code></pre> <p>Which gives <code>{'a': 'yo', 'b': 7}</code> output.<br> Here's a simple generator for the same:</p> <pre><cod...
0
2016-10-02T16:10:06Z
[ "python", "python-3.x" ]
Create dictionary where keys are variable names
39,818,733
<p>I quite regularly want to a dictionary where the key names are the variable names. For example if i have the variable <code>a</code> and <code>b</code> then to have a dictionary <code>{"a":a, "b":b}</code> (typically to return data at the end of a function).</p> <p>Is there any (ideally built in) ways in python of...
0
2016-10-02T15:47:33Z
39,819,722
<p>Have you considered creating a class? A class can be viewed as a wrapper for a dictionary. </p> <pre><code># Generate some variables in the workspace a = 9; b = ["hello", "world"]; c = (True, False) # Define a new class and instantiate class NewClass(object): pass mydict = NewClass() # Set attributes of the new...
0
2016-10-02T17:34:23Z
[ "python", "python-3.x" ]
How do I return combination of same level nodes in one webelement in selenium?
39,818,842
<p>my knowledge of selenium at this point is a bit limited, but from what I understand driver.find_elements_by_xpath() returns a list of webelements. One can then iterate over the elements and do whatever one wants, like printing text. That part is easy. But now assume on a given page I would be looking for every comb...
1
2016-10-02T15:58:08Z
39,827,188
<p>Your approach is fine -- just find the first element and then check to make sure the next one (and one after) are the ones you are expecting, otherwise continue searching.</p> <p>For more complex cases like this, it might be easier to pull out the HTML of the body as text and run a (more powerful) regex on it. </p>...
0
2016-10-03T08:16:33Z
[ "python", "html", "selenium", "xpath" ]
How do I return combination of same level nodes in one webelement in selenium?
39,818,842
<p>my knowledge of selenium at this point is a bit limited, but from what I understand driver.find_elements_by_xpath() returns a list of webelements. One can then iterate over the elements and do whatever one wants, like printing text. That part is easy. But now assume on a given page I would be looking for every comb...
1
2016-10-02T15:58:08Z
39,837,076
<p>I'm not sure what code you are using for your approach but I would do something like this.</p> <pre><code>headings = driver.find_elements_by_css_selector("parent &gt; h1")) for i in range(len(headings)): heading = driver.find_element_by_css_selector("parent &gt; h1:nth-of-type(" + i + ")")) identifier = dri...
1
2016-10-03T17:24:01Z
[ "python", "html", "selenium", "xpath" ]
how to make vpython .exe using pyinstaller
39,818,847
<p>I have a simple script using vpython (just testing) and I want to create a .exe file with pyinstaller.</p> <p>This is the script:</p> <pre><code>from visual import* box() </code></pre> <p>Then I run in the console:</p> <pre><code>pyinstaller sss.py </code></pre> <p>But the .exe dont work(obviously)</p> <p>I'v...
1
2016-10-02T15:58:27Z
39,822,549
<p>I will reponse myself, maybe it helps someone.</p> <p>When pyinstaller is used with vpython and you try to run the .exe file, it has problem for find the TGA archives placed in </p> <pre><code>C:\Anaconda2\Lib\site-packages\visual_common </code></pre> <p>So we have to edit the archive materials.py</p> <pre><code...
0
2016-10-02T22:52:11Z
[ "python", "pyinstaller", "vpython" ]
pickle.load: ImportError: No module named k_means_
39,818,859
<p>I'm dumping a <code>sklearn.cluster.KMeans</code> object using <code>pickle</code> like this:</p> <pre><code>kmeans = KMeans(n_clusters=7) kmeans.fit(X) pickle.dump(kmeans, open(model_fname, "w"), protocol=2) </code></pre> <p>However, if I try to reload this pickle file:</p> <pre><code>if os.path.exists(model_f...
2
2016-10-02T15:59:19Z
39,819,394
<p>I just replaced <code>pickle</code> by <code>joblib</code>:</p> <pre><code>from sklearn.externals import joblib </code></pre>
2
2016-10-02T16:56:18Z
[ "python", "scikit-learn", "pickle" ]
using a nested if statement within a for loop
39,818,863
<p>i'm trying to read through a string (with no spaces) pull out instances where there is a single lowercase letter surrounded on both sides by 3 upper cases (i.e. HHSkSIO). I've written the code below:</p> <pre><code>def window(fseq, window_size=7): for i in xrange(len(fseq) - window_size + 1): yield fseq...
0
2016-10-02T15:59:52Z
39,818,899
<p>You have to call the <code>isupper</code> and <code>islower</code> methods:</p> <pre><code> if seq[:3].isupper() and seq[3].islower() and seq[4:].isupper(): print seq </code></pre>
1
2016-10-02T16:03:43Z
[ "python", "string", "iteration" ]
using a nested if statement within a for loop
39,818,863
<p>i'm trying to read through a string (with no spaces) pull out instances where there is a single lowercase letter surrounded on both sides by 3 upper cases (i.e. HHSkSIO). I've written the code below:</p> <pre><code>def window(fseq, window_size=7): for i in xrange(len(fseq) - window_size + 1): yield fseq...
0
2016-10-02T15:59:52Z
39,818,932
<p>The problem is that you are missing the () in your calls to .isupper, which always evaluate to true.</p> <p>Try:</p> <pre><code>def window(fseq, window_size=7): for i in range(len(fseq) - window_size + 1): yield fseq[i:i+window_size] for seq in window('asjdjdfkjdhfkdjhsdfkjsdHJJnJSSsdjkdsad', 7): ...
1
2016-10-02T16:06:56Z
[ "python", "string", "iteration" ]
Creating a dictionary with multiple values per key from a list of dictionaries
39,818,875
<p>I have the following list of dictionaries:</p> <pre><code>listofdics = [{'StrId': 11, 'ProjId': 1},{'StrId': 11,'ProjId': 2}, {'StrId': 22, 'ProjId': 3},{'StrId': 22, 'ProjId': 4}, {'StrId': 33, 'ProjId': 5},{'StrId': 33, 'ProjId': 6}, {'StrId': 34, 'ProjId': 7}] </code></p...
0
2016-10-02T16:01:12Z
39,819,029
<p>It's unclear why you need to have such output <code>new_listofdics = [{11:[1,2]}, {22:[3,4]}, {33:[5,6]], {34:[7]}]</code>, because it's better to have just <code>dict</code> object.</p> <p>So program would look like this</p> <pre><code>&gt;&gt;&gt; from collections import defaultdict &gt;&gt;&gt; listofdics = [{'...
2
2016-10-02T16:18:29Z
[ "python", "dictionary" ]
My accumulator is registering as a string....SO LOST
39,818,882
<p>My problem is probably simple as usual guys and gals, I've been working on this thing for 13 hours now and I can't get this this to accumulate the names variable.</p> <p>I need it to count players that I have input data for. This is the error message I'm getting:</p> <pre><code>line 25, in main name += 1 TypeE...
0
2016-10-02T16:02:00Z
39,819,017
<p>You need a separate variable for counting the number of scores that have been written:</p> <pre><code>def main(): outfile = open('golf.txt', 'w') # Change this: count = 0 print("You will be asked to enter players names and scores") print("When you have no more names, enter End") print("\n...
1
2016-10-02T16:16:50Z
[ "python", "accumulator" ]
Send excel file for downloading GAE python
39,818,916
<p>I am using Google App Engine with python 2.7. And there is need to generate in-memory xls-file and send it to user for downloading.</p> <p>I found amount of topics in web, but any of them can't help me. Related topics that I've tried to use: 1) <a href="http://stackoverflow.com/questions/7254317/how-can-i-store-exc...
0
2016-10-02T16:05:22Z
39,819,521
<p>Try this:</p> <pre><code>output = StringIO.StringIO() ....... self.response.headers[b'Content-Type'] = b'application/vnd.ms-excel; charset=utf-8' self.response.headers[b'Content-Disposition'] = b'attachment; filename=test.xlsx' self.response.write(output.getvalue()) </code></pre>
1
2016-10-02T17:11:47Z
[ "python", "excel", "google-app-engine" ]
function that reverses digits, takes into consideration the sign
39,818,994
<p>I've looked on the site to try and figure out how to do this but I'm still stuck. </p> <p>My function is supposed to reverse digits, so reverse_digits(8765) returns 5678. This is easily done by :</p> <pre><code>def reverse_digits(num): return int(str(num)[::-1]) </code></pre> <p>However, my code needs to 1) t...
0
2016-10-02T16:13:00Z
39,819,027
<p>Try to use the isdigit() string method.</p> <pre><code>def reverse_digit(num): num_str = str(num)[::-1].strip('-') if not num_str.isdigit(): &lt;do what u want&gt; if num &lt; 0: return -int(num_str) else: return int(num_str) </code></pre>
2
2016-10-02T16:18:14Z
[ "python" ]
function that reverses digits, takes into consideration the sign
39,818,994
<p>I've looked on the site to try and figure out how to do this but I'm still stuck. </p> <p>My function is supposed to reverse digits, so reverse_digits(8765) returns 5678. This is easily done by :</p> <pre><code>def reverse_digits(num): return int(str(num)[::-1]) </code></pre> <p>However, my code needs to 1) t...
0
2016-10-02T16:13:00Z
39,819,041
<p>Just don't put the <code>-</code> into the reversed string:</p> <pre><code>def reverse_digits(num): return (-1 if num&lt;0 else 1) * int(str(abs(num))[::-1]) </code></pre>
4
2016-10-02T16:20:06Z
[ "python" ]
Comparing 2 different dictionaries with random function
39,819,061
<p>So, what I am trying to achieve here is to take 2 dictionaries, take the values of both dictionaries in the same "spot" and be able to apply any function to it. Here's an example of some pseudo code:</p> <pre><code>If f(a, b) returns a + b d1 = {1:30, 2:20, 3:30, 5:80} d2 = {1:40, 2:50, 3:60, 4:70, 6:90} then funct...
2
2016-10-02T16:22:15Z
39,819,513
<p>Although there maybe a more efficient way to achieve what you want, i used the information <a href="https://docs.python.org/2/library/sets.html" rel="nofollow">here</a> to create the following functions:</p> <pre><code>def f1(a,b): return a+b def f2(a,b): return a&gt;b def function2(d1,d2): out1 = {} ...
0
2016-10-02T17:10:34Z
[ "python" ]
Comparing 2 different dictionaries with random function
39,819,061
<p>So, what I am trying to achieve here is to take 2 dictionaries, take the values of both dictionaries in the same "spot" and be able to apply any function to it. Here's an example of some pseudo code:</p> <pre><code>If f(a, b) returns a + b d1 = {1:30, 2:20, 3:30, 5:80} d2 = {1:40, 2:50, 3:60, 4:70, 6:90} then funct...
2
2016-10-02T16:22:15Z
39,820,980
<p>Firstly find the intersection and the unions of the two dictionaries (as sets) The intersections are used for the first item of the tuple The differences are used for the second item of the tuple.</p> <p>The functor is the operation to perform on dictionary items with keys from the intersection values. This is the ...
0
2016-10-02T19:44:52Z
[ "python" ]
For loop to evaluate accuracy doesn't execute
39,819,090
<p>So I've the following numpy arrays.</p> <ul> <li>X validation set, X_val: (47151, 32, 32, 1)</li> <li>y validation set (labels), y_val_dummy: (47151, 5, 10) </li> <li>y validation prediction set, y_pred: (47151, 5, 10)</li> </ul> <p>When I run the code, it seems to take forever. Can someone suggest why? I believe...
1
2016-10-02T16:25:44Z
39,841,336
<p>You're main problem is that you're generating a massive number of very large lists for no real reason</p> <pre><code>for i in range(X_val.shape[0]): # this line generates a 47151 x 5 x 10 array every time pred_list_i = [y_pred_array[i] for y_pred in y_pred_array] </code></pre> <p>What's happening...
0
2016-10-03T22:23:32Z
[ "python", "numpy" ]
How to pass slice into a function by reference
39,819,104
<p>If I have</p> <pre><code>a = [1, 2, 3] def foo (arr): for i in len (arr): arr [i] += 1 def bar (arr): foo (arr[:2]) bar (a) print (a) </code></pre> <p>I want output as </p> <pre><code>&gt;&gt;&gt; [2, 3, 3 ] </code></pre> <p>How do I go about this?</p> <p>Motivation: I want a priority queue where I c...
0
2016-10-02T16:27:59Z
39,819,137
<p>Use a <em>list comprehension</em> and update the initial list using a full slice assignment with <code>[:]</code>:</p> <pre><code>def foo(arr): arr[:] = [x+1 for x in arr] </code></pre> <p><em>Trial:</em></p> <pre><code>&gt;&gt;&gt; a = [1, 2, 3] &gt;&gt;&gt; def foo(arr): ... arr[:] = [x+1 for x in arr] .....
1
2016-10-02T16:30:53Z
[ "python", "python-3.x", "pass-by-reference", "slice" ]
How to pass slice into a function by reference
39,819,104
<p>If I have</p> <pre><code>a = [1, 2, 3] def foo (arr): for i in len (arr): arr [i] += 1 def bar (arr): foo (arr[:2]) bar (a) print (a) </code></pre> <p>I want output as </p> <pre><code>&gt;&gt;&gt; [2, 3, 3 ] </code></pre> <p>How do I go about this?</p> <p>Motivation: I want a priority queue where I c...
0
2016-10-02T16:27:59Z
39,819,154
<p><em>Slicing the list will create a new list with the sliced contents</em>, as such <code>arr[:2]</code> loses the reference to the original <code>a</code>.</p> <p>Apart from that, iterating as you did won't change the list at all, it just changes an <code>item</code> and disregards the value.</p> <p>If you want to...
0
2016-10-02T16:32:28Z
[ "python", "python-3.x", "pass-by-reference", "slice" ]
How to pass slice into a function by reference
39,819,104
<p>If I have</p> <pre><code>a = [1, 2, 3] def foo (arr): for i in len (arr): arr [i] += 1 def bar (arr): foo (arr[:2]) bar (a) print (a) </code></pre> <p>I want output as </p> <pre><code>&gt;&gt;&gt; [2, 3, 3 ] </code></pre> <p>How do I go about this?</p> <p>Motivation: I want a priority queue where I c...
0
2016-10-02T16:27:59Z
39,819,234
<p>To be honest instead of going for slice, I would just pass the indexes;</p> <pre><code>a = [1, 2, 3] def foo(array, start, stop, jmp= 1): for idx in range(start, stop + 1, jmp): array[idx] += 1 def bar(array): foo(array, 1, 2) bar(a) print(a) [1, 3, 4] </code></pre>
0
2016-10-02T16:40:24Z
[ "python", "python-3.x", "pass-by-reference", "slice" ]
Flask request.form contains data but request.data is empty and request.get_json() returns error
39,819,151
<p>I am trying to create a data entry form "dynamically" (currently, I am using an array with 3 values, but in the future the number of elements in the array might vary) with nested dictionaries. This seems to work fine and the form is "properly" renders the html template (properly = I see what I would expect to see wh...
1
2016-10-02T16:32:17Z
39,819,328
<p>As it was mentioned <a href="http://stackoverflow.com/a/16664376/3124746">here</a></p> <blockquote> <p><code>request.data</code> Contains the incoming request data as string in case it came with a mimetype Flask does not handle.</p> </blockquote> <p>That's why you get empty string in <code>request.data</code></p...
0
2016-10-02T16:49:57Z
[ "python", "flask", "wtforms", "wtforms-json" ]
Does Python's distutils set include paths for frameworks (osx) when compiling extensions?
39,819,220
<p>I've been working on an extension module for Python but in OSX Sierra it no longer finds headers belonging to the frameworks I'm linking to. It always found them before without any special effort. Has something changed lately regarding include paths in this tool chain?</p>
0
2016-10-02T16:38:46Z
39,820,702
<p>I have to pass <code>cc -F /Library/Frameworks</code> for clang 7.2.0 and 8.0.0. Then it can find the headers.</p>
0
2016-10-02T19:19:03Z
[ "python", "distutils", "macos-sierra" ]
How can I use an if-else condition inside a list comprehension to overwrite an existing list?
39,819,236
<p>I'm trying to multiply numbers greater than 3 by two, and subtract one from everything else. However, nothing happens to the list. This is my code:</p> <pre><code>lst = [1,2,3,4,5,6,7,8,9,10] print (lst) [x*2 if x &gt; 3 else x-1 for x in lst] print (lst) </code></pre> <p>Why aren't the contents of the <em...
-1
2016-10-02T16:40:35Z
39,819,267
<p>You didnt re-assigned it to the variable name.</p> <pre><code>lst = [1,2,3,4,5,6,7,8,9,10] print (lst) lst = [x*2 if x &gt; 3 else x-1 for x in lst] print (lst) </code></pre>
0
2016-10-02T16:43:28Z
[ "python", "list-comprehension", "in-place" ]
How can I use an if-else condition inside a list comprehension to overwrite an existing list?
39,819,236
<p>I'm trying to multiply numbers greater than 3 by two, and subtract one from everything else. However, nothing happens to the list. This is my code:</p> <pre><code>lst = [1,2,3,4,5,6,7,8,9,10] print (lst) [x*2 if x &gt; 3 else x-1 for x in lst] print (lst) </code></pre> <p>Why aren't the contents of the <em...
-1
2016-10-02T16:40:35Z
39,819,300
<h2>List Comprehensions and Assignment</h2> <p>You're missing an assignment. <a href="https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions" rel="nofollow">List comprehensions</a> like yours don't do in-place modifications to the list elements. Instead, the expression returns a new list, so you mu...
0
2016-10-02T16:47:09Z
[ "python", "list-comprehension", "in-place" ]
Python pexpect Check if server is up
39,819,284
<p>I am automating few configuration steps on CentOS. In order to do so i need to reboot the system also. I am invoking the "reboot" command the via python pexepct, however i need to wait till the systems boots up for remaining script to executes. For that i am have written this small piece of code.</p> <pre><code> ...
1
2016-10-02T16:45:21Z
39,823,601
<p>You can try this:</p> <pre><code>import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # wait host to finish reboot, check specific port connection (usually ssh port if you want to exec remote commands) while True: try: s.connect(('hostname', 22)) print "Port 22 reachable" ...
2
2016-10-03T01:55:18Z
[ "python", "pexpect" ]
sockets irc bot not sending complete message
39,819,305
<p>I am trying to make an irc bot. It connects but doesn't send the complete message. If I want to send "hello world" it only sends "hello". It just sends everything until the first space. </p> <p>In this program if you type hello in irc, the bot is supposed to send hello world. But it only sends hello.</p> <pre><cod...
0
2016-10-02T16:47:37Z
39,819,779
<p>You forgot a : before the message. This should work:</p> <pre><code>def send(self, chan, msg): self.irc.send("PRIVMSG " + chan + " :" + msg + "\n") </code></pre>
2
2016-10-02T17:40:32Z
[ "python", "sockets", "irc" ]
Dealing with multiple Python versions?
39,819,314
<p>I have a problem with my Pip version. I am trying out to install the pyDatalog package, which isn't supported by Anaconda.</p> <pre><code> The following specifications were found to be in conflict: - pydatalog - python 3.5* </code></pre> <p>In my Ubuntu, I have two versions of Python (2.7 and Anaconda with 3...
0
2016-10-02T16:48:23Z
39,821,908
<p>Take a look at pyenv located in <a href="https://github.com/yyuu/pyenv/blob/master/README.md" rel="nofollow">https://github.com/yyuu/pyenv/blob/master/README.md</a>. </p> <p>You can install multiple versions of python and pip. </p> <p>The README has instructions for installing pyenv, installing wanted python vers...
1
2016-10-02T21:31:34Z
[ "python", "python-2.7", "pip", "conda", "pydatalog" ]
How to do logical operation between DataFrame and Series?
39,819,323
<p>Suppose I have a bool <code>DataFrame df</code> and a bool <code>Series x</code> with the same index, and I want to do logical operation between <code>df</code> and <code>x</code> per column. Is there any short and fast way like <code>DataFrame.sub</code> compare to using <code>DataFrame.apply</code>?</p> <pre><cod...
2
2016-10-02T16:48:59Z
39,819,434
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.mul.html" rel="nofollow"><code>mul</code></a>, but need cast to <code>int</code> and then to <code>bool</code>, because <code>UserWarning</code>:</p> <pre><code>print (df.astype(int).mul(x.values, axis=0).astype(bool)) x ...
4
2016-10-02T17:00:45Z
[ "python", "pandas", "dataframe", "boolean", "logical-operators" ]
Convert 12 hour time string into datetime or time
39,819,384
<p>Ive been trying to use <code>time.strptime(string1,'%H:%M')</code>, with no success</p> <p>How can I get the following:</p> <pre><code>Input Output 3:14AM -&gt; 03:14 9:33PM -&gt; 21:33 12:21AM -&gt; 00:21 12:15PM -&gt; 12:15 </code></pre>
-1
2016-10-02T16:55:06Z
39,819,437
<p>You're missing <code>%p</code> (Locale’s equivalent of either AM or PM).</p> <pre><code>time.strptime(string1,'%H:%M%p') </code></pre>
0
2016-10-02T17:01:12Z
[ "python", "datetime", "time" ]
Convert 12 hour time string into datetime or time
39,819,384
<p>Ive been trying to use <code>time.strptime(string1,'%H:%M')</code>, with no success</p> <p>How can I get the following:</p> <pre><code>Input Output 3:14AM -&gt; 03:14 9:33PM -&gt; 21:33 12:21AM -&gt; 00:21 12:15PM -&gt; 12:15 </code></pre>
-1
2016-10-02T16:55:06Z
39,819,463
<p>The problem requires that you first <code>strptime</code> using <code>%I</code> for the 12 hour time and adding the directive <code>%p</code> for AM or PM to get a time object; altogther <code>'%I:%M%p'</code>. Then use <code>strftime</code> to format the time object into a string:</p> <hr> <p><em>Trials:</em></p>...
1
2016-10-02T17:04:15Z
[ "python", "datetime", "time" ]
Convert 12 hour time string into datetime or time
39,819,384
<p>Ive been trying to use <code>time.strptime(string1,'%H:%M')</code>, with no success</p> <p>How can I get the following:</p> <pre><code>Input Output 3:14AM -&gt; 03:14 9:33PM -&gt; 21:33 12:21AM -&gt; 00:21 12:15PM -&gt; 12:15 </code></pre>
-1
2016-10-02T16:55:06Z
39,819,464
<p>Use <code>%I</code> for 12 hour times and <code>%p</code> for the <code>am</code> or <code>pm</code> as follows:</p> <pre><code>from datetime import datetime for t in ["3:14AM", "9:33PM", "12:21AM", "12:15PM"]: print datetime.strptime(t, '%I:%M%p').strftime("%H:%M") </code></pre> <p>Giving you the following o...
1
2016-10-02T17:04:23Z
[ "python", "datetime", "time" ]
Average function excluding value for each row in Pandas DataFrame
39,819,391
<p>Is there a simple way to calculate the average for each column in a pandas DataFrame and for each row <em>exclude</em> the specific value? The <code>x</code> in each row below marks the value in each iteration to be excluded from the calculation:</p> <pre><code> a b a b ...
2
2016-10-02T16:55:59Z
39,819,536
<p>To start off with the first step, let's say we were interested in summing instead of calculating the average values. In that case, we would be adding all elems along each col except the current elem. Other way to look at it/solve it would be to sum all elems along each col and subtract the current elem itself. So, e...
3
2016-10-02T17:13:49Z
[ "python", "pandas" ]
Display url variable from views.py in Django template
39,819,505
<p>I want have my <em>url</em> come from <strong>views.py</strong> and then I can pass it as variable to <code>href</code> tag in template.</p> <p><strong>views.py:</strong></p> <pre><code>context { 'urlLink': "{% url 'myapp:theURL' %}" ... } </code></pre> <p><strong>index.html:</strong></p> <pre><code>&lt;...
1
2016-10-02T17:09:36Z
39,819,537
<p>you need <a href="https://docs.djangoproject.com/en/1.10/ref/urlresolvers/#reverse" rel="nofollow">reverse</a></p> <pre><code>context { 'urlLink': "%s" % reverse('view_name') } </code></pre> <p>you cannot use <code>{% url 'myapp:theURL' %}</code> in views.py since this is a template tag</p>
1
2016-10-02T17:13:52Z
[ "python", "django" ]
Display url variable from views.py in Django template
39,819,505
<p>I want have my <em>url</em> come from <strong>views.py</strong> and then I can pass it as variable to <code>href</code> tag in template.</p> <p><strong>views.py:</strong></p> <pre><code>context { 'urlLink': "{% url 'myapp:theURL' %}" ... } </code></pre> <p><strong>index.html:</strong></p> <pre><code>&lt;...
1
2016-10-02T17:09:36Z
39,819,538
<p>If you need to use something similar to the <code>{% url %}</code> template tag in your view code, Django provides the <code>django.core.urlresolvers.reverse()</code>. The <a href="https://docs.djangoproject.com/en/dev/ref/urlresolvers/#reverse" rel="nofollow">reverse</a> function has the following signature:</p> <...
2
2016-10-02T17:14:00Z
[ "python", "django" ]
Print "Match Found" for each line the search is in and "Match not Found" if the search isnt in the whole file
39,819,548
<p>I want to print "Match Found" and the line that the match is in if the search is in a line in the file. Note - the match can be in more than one line and if so it should print every line the match is in. I have got this part working but i want to print "Match Not Found" once if the search isn't in the whole file. So...
0
2016-10-02T17:14:36Z
39,819,677
<p>The <code>else</code> block of the <code>for</code> would have been a great choice if you had to <code>break</code> the iteration once an item is found; but that isn't the case.</p> <p>I think you may want to set a <em>flag</em> instead of using the <code>else</code> and testing after the <code>for</code> is comple...
0
2016-10-02T17:30:13Z
[ "python", "python-3.x" ]
Print "Match Found" for each line the search is in and "Match not Found" if the search isnt in the whole file
39,819,548
<p>I want to print "Match Found" and the line that the match is in if the search is in a line in the file. Note - the match can be in more than one line and if so it should print every line the match is in. I have got this part working but i want to print "Match Not Found" once if the search isn't in the whole file. So...
0
2016-10-02T17:14:36Z
39,819,799
<p>First of all, I think you are misunderstanding the way of how "else" statement after the for loop works. It will execute only if the for loop wasn't break.</p> <pre><code>n = 10 for idx in range(n): if idx &gt; 11: print('Yey, we reached {}'.format(idx)) break else: print('Damn, we almost had ...
0
2016-10-02T17:42:23Z
[ "python", "python-3.x" ]
Replacing the existing MainWindow with a new window with Python, PyQt, Qt Designer
39,819,700
<p>I'm new to Python GUI programming I'm have trouble making a GUI app. I have a main window with only a button widget on it. What i want to know is how to replace the existing window with a new window when an event occurs (such as a button click).<br> An answer to a similar question here <a href="http://stackoverflow....
1
2016-10-02T17:32:23Z
39,838,313
<p>You probably don't want to actually create and delete a bunch of windows, but if you really want to, you could do it like this</p> <pre><code>def doSomething(self): # Code to replace the main window with a new window window = OtherWindow() window.show() self.close() </code></pre> <p>The in the <cod...
0
2016-10-03T18:41:54Z
[ "python", "pyqt", "qt-designer" ]
Replacing the existing MainWindow with a new window with Python, PyQt, Qt Designer
39,819,700
<p>I'm new to Python GUI programming I'm have trouble making a GUI app. I have a main window with only a button widget on it. What i want to know is how to replace the existing window with a new window when an event occurs (such as a button click).<br> An answer to a similar question here <a href="http://stackoverflow....
1
2016-10-02T17:32:23Z
39,838,590
<p>You can use the QStackedWindow to create a entire new window and hten connect it to the main window through onclick() event.</p> <pre><code>button.clicked.connect(self.OtherWindow) </code></pre> <p>Or else you can simply use the</p> <pre><code>class OtherWindow(self): Owindow = OtherWindow() Owindow.sho...
0
2016-10-03T18:59:16Z
[ "python", "pyqt", "qt-designer" ]
Replacing the existing MainWindow with a new window with Python, PyQt, Qt Designer
39,819,700
<p>I'm new to Python GUI programming I'm have trouble making a GUI app. I have a main window with only a button widget on it. What i want to know is how to replace the existing window with a new window when an event occurs (such as a button click).<br> An answer to a similar question here <a href="http://stackoverflow....
1
2016-10-02T17:32:23Z
39,860,670
<p>Here is a simple example, you just have to use your own logistic but it's a simple way to represent what you are looking for.</p> <p>You can use QWindow instead of QWidgets if your prefer, or different layout to dispose your "objects" or whatever. Maybe change a bit how to add items inside layout if not widget... t...
0
2016-10-04T19:52:06Z
[ "python", "pyqt", "qt-designer" ]
Duplicate results in Xpath and not CSS selectors in scrapy
39,819,860
<p>So I am playing around with scrapy through the <a href="https://doc.scrapy.org/en/latest/intro/tutorial.html" rel="nofollow">tutorial</a>. I am trying to scrape the text, author and tags of each quote in the <a href="http://quotes.toscrape.com/page/1/" rel="nofollow">companion website</a> when using CSS selectors li...
1
2016-10-02T17:48:09Z
39,821,410
<p>Try <code>.//</code> instead of <code>//</code> for your relative searches e.g. </p> <p><code>print quote.xpath(".//*[@class='text']/text()").extract()</code></p> <p>When you use <code>//</code>, although you're searching from <code>quote</code>, it takes this to mean an absolute search so its context is still the...
2
2016-10-02T20:31:50Z
[ "python", "xpath", "css-selectors", "scrapy" ]
Duplicate results in Xpath and not CSS selectors in scrapy
39,819,860
<p>So I am playing around with scrapy through the <a href="https://doc.scrapy.org/en/latest/intro/tutorial.html" rel="nofollow">tutorial</a>. I am trying to scrape the text, author and tags of each quote in the <a href="http://quotes.toscrape.com/page/1/" rel="nofollow">companion website</a> when using CSS selectors li...
1
2016-10-02T17:48:09Z
39,827,996
<p>When you use // it will get all results from response. If you use .// then it scope will be limited to that selector. Try <code>.//</code> instead of <code>//</code>. It will solve your problem :-)</p>
0
2016-10-03T09:07:18Z
[ "python", "xpath", "css-selectors", "scrapy" ]
In which way are these two PowerPoint Shapes different (accessed via API)
39,819,876
<p>As part of an open source assistive technology project (<a href="https://hackaday.io/project/15567-the-open-voice-factory" rel="nofollow">here</a>), I am accessing a PowerPoint file by python API (<a href="https://python-pptx.readthedocs.io/en/latest/" rel="nofollow">python-pptx</a>). </p> <p>Some shapes are caus...
1
2016-10-02T17:49:26Z
39,913,256
<p>You need to call:</p> <pre><code>shape.fill.solid() </code></pre> <p>before attempting to access the <code>fore_color</code> attribute.</p> <p>A fill can have several types, each of which have a different attribute set. The <code>.fore_color</code> attribute is particular to a solid fill. By default, the fill is ...
0
2016-10-07T08:52:40Z
[ "python", "powerpoint" ]
Quicksort with insertion sort Python not working
39,819,878
<p>I've been trying to run the quicksort with a switch to insertion sort when the sub array size is less than 10. So it turns out, i'm not getting a sorted list.</p> <p>Where am i going wrong?</p> <pre><code>import random import time m = 0 def quicksort(numList, first, last): if first&lt;last: sizeArr =...
0
2016-10-02T17:49:48Z
39,819,992
<p>You have an off-by-one error in <code>insert_sort</code> function. Iterate over <code>range(first, last+1)</code> and it will sort correctly.</p>
0
2016-10-02T18:02:10Z
[ "python", "quicksort", "insertion-sort" ]
How the below program is possible in python
39,819,922
<p>I came with a situation where the method of class A to be called from class B.</p> <pre><code>class A(object): def __init__(self, a): self.a = a def abc(self): print self.a class B(A): def __init__(self): super(B, self).abc() def method1(): a = A(2) method1() b = B() Ex...
-1
2016-10-02T17:54:16Z
39,820,045
<p>Your B class __init__ method is not taking any argument, while the __init__ of class A require you to pass one (named "a"), and yet, you are not providing it. Neither in your B class or by passing it to A.</p> <p>However, this would work.</p> <pre><code>class A(object): def __init__(self, a): self.a = ...
2
2016-10-02T18:07:46Z
[ "python", "python-2.7" ]
How the below program is possible in python
39,819,922
<p>I came with a situation where the method of class A to be called from class B.</p> <pre><code>class A(object): def __init__(self, a): self.a = a def abc(self): print self.a class B(A): def __init__(self): super(B, self).abc() def method1(): a = A(2) method1() b = B() Ex...
-1
2016-10-02T17:54:16Z
39,820,728
<p>Here:</p> <pre><code>class B(A): def __init__(self): super(B, self).abc() </code></pre> <p>The constructor of <code>A</code> is never called, so the initialization done in <code>A.__init__</code> is missing. It fails in <code>print self.a</code>, because there is no <code>a</code>. The super construct...
0
2016-10-02T19:20:46Z
[ "python", "python-2.7" ]
Selenium webdriver seems not working properly with Firefox 49.0. Am I missing something?
39,819,937
<p>I have gone through previous questions but did not find anyone else running into my issue.</p> <p>This simple code hangs</p> <pre><code>from selenium import webdriver d = webdriver.Firefox(); </code></pre> <p>The browser gets launched, but it just hangs there. After sometime, it crashes and I get the error</p> <...
1
2016-10-02T17:56:38Z
39,824,443
<p>Selenium 3 is still in beta state, and geckodriver is highly unstable. Dig deep and you will find the reported issues with geckodriver.</p>
0
2016-10-03T04:00:18Z
[ "python", "selenium", "firefox", "selenium-webdriver", "ubuntu-14.04" ]
Selenium webdriver seems not working properly with Firefox 49.0. Am I missing something?
39,819,937
<p>I have gone through previous questions but did not find anyone else running into my issue.</p> <p>This simple code hangs</p> <pre><code>from selenium import webdriver d = webdriver.Firefox(); </code></pre> <p>The browser gets launched, but it just hangs there. After sometime, it crashes and I get the error</p> <...
1
2016-10-02T17:56:38Z
39,853,263
<p>Try renaming the downloaded Gecko Driver to Wires and Set the Capabilities as mentioned Below.</p> <pre><code>System.setProperty("webdriver.gecko.driver", "//home//.....//BrowserDrivers//wires"); DesiredCapabilities capabilities = DesiredCapabilities.firefox(); capabilities.setCapability("marionette", true); Driver...
0
2016-10-04T13:10:27Z
[ "python", "selenium", "firefox", "selenium-webdriver", "ubuntu-14.04" ]
Selenium webdriver seems not working properly with Firefox 49.0. Am I missing something?
39,819,937
<p>I have gone through previous questions but did not find anyone else running into my issue.</p> <p>This simple code hangs</p> <pre><code>from selenium import webdriver d = webdriver.Firefox(); </code></pre> <p>The browser gets launched, but it just hangs there. After sometime, it crashes and I get the error</p> <...
1
2016-10-02T17:56:38Z
39,854,643
<p><a href="http://stackoverflow.com/questions/39715653/selenium-starts-but-does-not-load-a-page/39720178#39720178">Duplicate Question</a></p> <p>There is some issue with Firefox version greater than 48.Better you downgrade the Firefox to lower than 47. I was having the same problem.</p>
0
2016-10-04T14:15:08Z
[ "python", "selenium", "firefox", "selenium-webdriver", "ubuntu-14.04" ]
Python - Override parent class argument
39,819,959
<p>I have a super class and a sub class.</p> <pre><code>class Vehicle: def __init__(self, new_fuel, new_position): self.fuel = new_fuel self.position = new_position class Car(Vehicle): # Here, I am stating that when Car is initialized, the position will be # at (0, 0), so when you call it, y...
-1
2016-10-02T17:58:48Z
39,820,234
<p>As far as I understand what you are trying to achieve, just simply delete the "new_position" parameter from your Car __init__ method.</p> <pre><code>class Vehicle: def __init__(self, new_fuel, new_position): self.fuel = new_fuel self.position = new_position class Car(Vehicle): # Here, I am st...
1
2016-10-02T18:26:43Z
[ "python" ]
Beautifulsoup get text based on nextSibling tag name
39,820,006
<p>I'm scraping multiple pages that all have a similar format, but it changes a little here and there and there are no classes to use to search for what I need.</p> <p>The format looks like this:</p> <pre><code>&lt;div id="mainContent"&gt; &lt;p&gt;Some Text I don't want&lt;/p&gt; &lt;p&gt;Some Text I don't ...
2
2016-10-02T18:03:22Z
39,820,505
<p>You want only the <code>p</code> tags which are before <code>ol</code> tag. Find the <code>ol</code> tags first and then find the previous <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#tag" rel="nofollow">Tag</a> objects which are in this case, the <code>p</code> tag. Now your code is not working b...
2
2016-10-02T18:55:39Z
[ "python", "html", "beautifulsoup" ]
Beautifulsoup get text based on nextSibling tag name
39,820,006
<p>I'm scraping multiple pages that all have a similar format, but it changes a little here and there and there are no classes to use to search for what I need.</p> <p>The format looks like this:</p> <pre><code>&lt;div id="mainContent"&gt; &lt;p&gt;Some Text I don't want&lt;/p&gt; &lt;p&gt;Some Text I don't ...
2
2016-10-02T18:03:22Z
39,820,600
<p>You can use a <em>css selector</em>, i.e <code>ul ~ p</code> to find all the p tags preceded by the <em>ul</em>:</p> <pre><code>html = """&lt;div id="mainContent"&gt; &lt;p&gt;Some Text I don't want&lt;/p&gt; &lt;p&gt;Some Text I don't want&lt;/p&gt; &lt;p&gt;Some Text I don't want&lt;/p&gt; &lt;sp...
2
2016-10-02T19:06:55Z
[ "python", "html", "beautifulsoup" ]
How to dynamically display time data stream on matplotlib
39,820,036
<p>I'm using matplotlib to display data saved on a csv file periodically, now the data is plotted well but the time axis is hardly moving, in fact the script is trying to show all the data stored on that file, I want to see only latest data and be able to scrol horizontaly to see older data this is a part of the scri...
0
2016-10-02T18:06:18Z
39,821,197
<p>From that video, it looks like you want something like the following - I can still see a scrolling window in the video you posted so I'm still a little confused as to what you want. This uses <code>fig.canvas.draw</code> but there are other options using the matplotlib animation module (you didn't specify that it h...
0
2016-10-02T20:09:59Z
[ "python", "python-2.7", "python-3.x", "matplotlib", "plot" ]
Python 3 regex How to use grouping properly?
39,820,159
<p><strong>EDIT: Sorry, I am just allowed to insert 2 links, the other ones are as plain text here.</strong></p> <p>Hi I am very new to Python and regex. I searched at regex101 and many other sites how to use it properly but it just isn't working and I don't know what to do any more.</p> <p>I have some IP cameras at ...
0
2016-10-02T18:18:51Z
39,820,289
<p>You don't need to make one gigantic regex that matches everything. It's better to make several smaller regex that matches the specific camera. </p> <p>So if you have want to process the camera 1 and camera 2 the same your code could look something like this. </p> <pre><code>import re cam1 = re.compile(r'some rege...
0
2016-10-02T18:31:21Z
[ "python", "scripting", "subtitle" ]
When to use a class instead of a dict
39,820,214
<p>User data, as follows:</p> <pre><code>user = {"id": 1, "firstName": "Bar", "surname": "Foosson", "age": 20} </code></pre> <p>is sent to an application via json. </p> <p>In many places in the code the following it done:</p> <pre><code>user["firstName"] + " " + user["surname"] </code></pre> <p>which leads me to b...
0
2016-10-02T18:24:23Z
39,820,446
<p>I'm sure you are hesitant to use classes because of the need to write boilerplate code.</p> <p>But there's a nice library that may make your life easier: <a href="https://attrs.readthedocs.io/en/stable/" rel="nofollow"><code>attrs</code></a>.</p> <p>Glyph has a post with a self-speaking title: <a href="https://gly...
1
2016-10-02T18:49:14Z
[ "python" ]
When to use a class instead of a dict
39,820,214
<p>User data, as follows:</p> <pre><code>user = {"id": 1, "firstName": "Bar", "surname": "Foosson", "age": 20} </code></pre> <p>is sent to an application via json. </p> <p>In many places in the code the following it done:</p> <pre><code>user["firstName"] + " " + user["surname"] </code></pre> <p>which leads me to b...
0
2016-10-02T18:24:23Z
39,820,587
<p>Dictionaries are great for storage and retrieval, but if you need more functionality on top of that, a class is usually the way to go. That way you can also assure certain attributes are set, etc.</p> <p>For your situation, if a user's attributes are read-only, my approach would actually be using <a href="https://d...
1
2016-10-02T19:05:37Z
[ "python" ]
Python: Connect using sockets via external IP
39,820,253
<p>Today, I have made my very first sockets program - I made a client and a server that message each other (kind of like a chat) using sockets. When using the internal IP as 'host', The connection is established, otherwise using the external IP, no connection is established.</p> <p>Edit 1:</p> <pre><code>#Client s =...
0
2016-10-02T18:28:01Z
39,820,511
<p>Use <code>DynDNS.com</code> or <code>NoIP.com</code> portal. You install program on laptop which check your IP frequencly and sends current IP to portal which assigns this IP to your address like "my_laptop.noip.com". Then people can access your laptop using "my_laptop.noip.com" instead of IP address.</p> <p>You al...
0
2016-10-02T18:57:17Z
[ "python", "sockets", "networking" ]
ValueError in computing precision using scikit-learn
39,820,260
<pre><code>from sklearn.metrics import precision_score precision_score(expected, predicted) </code></pre> <p>where expected is <code>array([ 4., 3.])</code></p> <p>and predicted is <code>array([ 2., 4.])</code></p> <p>I get the foll. error: <code>*** ValueError: pos_label=1 is not a valid label: array([ 2., 3., ...
1
2016-10-02T18:28:39Z
39,820,415
<p>You need the <code>average</code> parameter for <em>multiclass</em> labels.</p> <p>Else you would need to set <code>pos_label</code> as one of the class labels in both arrays i.e. 2, 3 or 4:</p> <pre><code>&gt;&gt;&gt; # score for all classes &gt;&gt;&gt; precision_score(expected, predicted, average=None) array([ ...
1
2016-10-02T18:46:17Z
[ "python", "scikit-learn", "precision" ]
how to import scripts as modules in ipyhon?
39,820,350
<p>So, I've two python files:</p> <p>the 1st "m12345.py"</p> <pre><code>def my(): return 'hello world' </code></pre> <p>the 2nd "1234.py":</p> <pre><code>from m12345 import * a = m12345.my() print(a) </code></pre> <p>On ipython I try to exec such cmds:</p> <pre><code>exec(open("f:\\temp\\m12345.py").read()) e...
1
2016-10-02T18:39:37Z
39,820,619
<p>You have to create a new module (for example <code>m12345</code>) by calling <code>m12345 = imp.new_module('m12345')</code> and then exec the python script in that module by calling <code>exec(open('path/m12345.py').read(), m12345.__dict__)</code>. See the example below:</p> <pre><code>import imp pyfile = open('pa...
1
2016-10-02T19:09:34Z
[ "python", "ipython", "python-import" ]
how to import scripts as modules in ipyhon?
39,820,350
<p>So, I've two python files:</p> <p>the 1st "m12345.py"</p> <pre><code>def my(): return 'hello world' </code></pre> <p>the 2nd "1234.py":</p> <pre><code>from m12345 import * a = m12345.my() print(a) </code></pre> <p>On ipython I try to exec such cmds:</p> <pre><code>exec(open("f:\\temp\\m12345.py").read()) e...
1
2016-10-02T18:39:37Z
39,820,717
<p>First off, if you use the universal import (<code>from m12345 import *</code>) then you just call the <code>my()</code> function and not the <code>m12345.my()</code> or else you will get a </p> <blockquote> <p>NameError: name 'm12345' is not defined</p> </blockquote> <p>Secondly, you should add the following sni...
2
2016-10-02T19:19:47Z
[ "python", "ipython", "python-import" ]
Computing product of ith row of array1 and ith column of array2 - NumPy
39,820,372
<p>I have a matrix <code>M1</code> of shape <code>(N*2)</code> and another matrix <code>M2</code> <code>(2*N)</code>, I want to obtain a result of <code>(N)</code>, each element <code>i</code> is the product of <code>i</code>th row of <code>M1</code> and <code>i</code>th column of <code>M2</code>. I tried to use dot i...
1
2016-10-02T18:41:38Z
39,820,461
<p><strong>Approach #1</strong></p> <p>You can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html" rel="nofollow"><code>np.einsum</code></a> -</p> <pre><code>np.einsum('ij,ji-&gt;i',M1,M2) </code></pre> <p><strong>Explanation :</strong> </p> <p>The original loopy solution would look ...
1
2016-10-02T18:50:40Z
[ "python", "numpy", "matrix" ]
Extract header names from a CSV and use it to plot against each other in Python?
39,820,386
<p>I am pretty new to python and coding in general. I have this code so far.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>import numpy as np import matplotlib.pyplot...
0
2016-10-02T18:42:36Z
39,822,297
<p>If you don't mind using/installing another module then <strong>pandas</strong> should do it. </p>
0
2016-10-02T22:16:53Z
[ "python", "matplotlib" ]
Extract header names from a CSV and use it to plot against each other in Python?
39,820,386
<p>I am pretty new to python and coding in general. I have this code so far.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>import numpy as np import matplotlib.pyplot...
0
2016-10-02T18:42:36Z
39,822,357
<p>Using <code>pandas</code> you can do:</p> <pre><code>import pandas as pd data = pd.read_csv("yourFile.csv", delimiter=",") </code></pre> <p>and plot columns with names <code>ColName1</code>, <code>ColName2</code> against each other with:</p> <pre><code>data.plot(x='Col1', y='Col2') </code></pre> <p>If you have a...
0
2016-10-02T22:25:26Z
[ "python", "matplotlib" ]
C# - Using method from a Python file
39,820,443
<p>I have two files, a regular python (.py) file and a visual studio C# file (.cs). I want to use a function in the python file which returns a string and use that string in the C# file. </p> <p>Basically:</p> <pre><code>#This is the Python file! def pythonString(): return "Some String" </code></pre> <p>and</p> ...
2
2016-10-02T18:48:53Z
39,820,925
<p>Check out IronPython! :)</p> <p>Good declaration: <a href="https://blogs.msdn.microsoft.com/charlie/2009/10/25/running-ironpython-scripts-from-a-c-4-0-program/" rel="nofollow">https://blogs.msdn.microsoft.com/charlie/2009/10/25/running-ironpython-scripts-from-a-c-4-0-program/</a></p> <p>Hope this helps, it's pret...
2
2016-10-02T19:40:26Z
[ "c#", "python", ".net", "ironpython", "python.net" ]
C# - Using method from a Python file
39,820,443
<p>I have two files, a regular python (.py) file and a visual studio C# file (.cs). I want to use a function in the python file which returns a string and use that string in the C# file. </p> <p>Basically:</p> <pre><code>#This is the Python file! def pythonString(): return "Some String" </code></pre> <p>and</p> ...
2
2016-10-02T18:48:53Z
39,898,727
<p>You can also try pythonnet:</p> <p><a href="http://www.python4.net" rel="nofollow">python4.net</a></p>
0
2016-10-06T14:30:47Z
[ "c#", "python", ".net", "ironpython", "python.net" ]
Edit distance specifc implementation for number . PYTHON
39,820,462
<p>I got a question on code chef asking the modified version of edit distance , where it is edit distance between 2 numbers , where only deletion operation is allowed and deletion cost = deleted number .</p> <p>So I tried this to implement on python . But getting </p> <pre><code>TypeError: 'function' object has no at...
1
2016-10-02T18:50:47Z
39,820,516
<p>you have typo here <code>delt[S%10,T%10]</code> </p> <p>This means that you cannot index them like a list because <strong>getitem</strong> is the method which handles this operation.<code>delt</code> is a function, not a list </p> <p>Corrected: </p> <pre><code>return min(EditDistRec(S/10,T/10) + delt(S%10,T%10),...
1
2016-10-02T18:57:30Z
[ "python", "python-2.7" ]
How to programmatically catch which command failed on a try block
39,820,476
<p>I'm trying to get some data from an JSON API. I don't want all the data that the API returns so I wrote a method that reads all the data and returns a dictionary with the relevant fields. Sometimes though, some data are missing and I would like to replace the fields that are missing with an underscore. A sample of t...
1
2016-10-02T18:52:41Z
39,820,500
<p>You can probably get that information from the members of the <code>KeyError</code> exception object, but a simpler way would be to just use <code>get()</code> that will return a default value if the key is not there.</p> <pre><code>return { 'foo': data.get('foo', '_'), 'bar': data.get('bar', '_'), } </cod...
3
2016-10-02T18:55:09Z
[ "python" ]
How to programmatically catch which command failed on a try block
39,820,476
<p>I'm trying to get some data from an JSON API. I don't want all the data that the API returns so I wrote a method that reads all the data and returns a dictionary with the relevant fields. Sometimes though, some data are missing and I would like to replace the fields that are missing with an underscore. A sample of t...
1
2016-10-02T18:52:41Z
39,820,521
<p>Instead of using try block, you can use <code>dict.get(key, default_val)</code></p> <p>For example:</p> <pre><code>ret_dict = dict( foo=data.get('foo', '-'), bar=data.get('bar', '-') ) return ret_dict </code></pre>
2
2016-10-02T18:58:15Z
[ "python" ]
How to programmatically catch which command failed on a try block
39,820,476
<p>I'm trying to get some data from an JSON API. I don't want all the data that the API returns so I wrote a method that reads all the data and returns a dictionary with the relevant fields. Sometimes though, some data are missing and I would like to replace the fields that are missing with an underscore. A sample of t...
1
2016-10-02T18:52:41Z
39,820,536
<p>Use <a href="https://docs.python.org/3/library/stdtypes.html#dict.get" rel="nofollow"><code>.get</code></a> method of <a href="https://docs.python.org/3/library/stdtypes.html#mapping-types-dict" rel="nofollow"><code>dict</code></a>:</p> <pre><code>def get_data(data): return { # If you want to accept fal...
2
2016-10-02T19:00:09Z
[ "python" ]
How to programmatically catch which command failed on a try block
39,820,476
<p>I'm trying to get some data from an JSON API. I don't want all the data that the API returns so I wrote a method that reads all the data and returns a dictionary with the relevant fields. Sometimes though, some data are missing and I would like to replace the fields that are missing with an underscore. A sample of t...
1
2016-10-02T18:52:41Z
39,820,785
<p>If you want to avoid the repetitiveness of typing <code>.get(attr, '_')</code> for each key, you can use a <a href="https://docs.python.org/3/library/collections.html#collections.defaultdict" rel="nofollow"><code>defaultdict</code></a>, setting it to return <code>_</code> when a key is trying to be accessed but miss...
1
2016-10-02T19:26:35Z
[ "python" ]
In Django, how do I update a user profile if a model is added to database?
39,820,496
<p>I'm creating a site where users can upload files. I have my upload form working, and it correctly associates the current user with the uploaded file. Once it's uploaded however, I would like the User Profile model to update the number of files uploaded for that specific user. I'm using django-allauth with a custom ...
1
2016-10-02T18:54:55Z
39,821,139
<p>You can use Post Save Signal in Django</p> <pre><code>from django.db.models.signals import * from django.db.models import F def file_upload_count(sender, instance, created, *args, **kwargs): if created: UserProfile.objects.filter(user = instance).update(filesuploaded = F('filesuploaded')+1) post_save....
0
2016-10-02T20:04:01Z
[ "python", "django", "django-allauth" ]
In Django, how do I update a user profile if a model is added to database?
39,820,496
<p>I'm creating a site where users can upload files. I have my upload form working, and it correctly associates the current user with the uploaded file. Once it's uploaded however, I would like the User Profile model to update the number of files uploaded for that specific user. I'm using django-allauth with a custom ...
1
2016-10-02T18:54:55Z
39,822,404
<p>Theres a few ways to solve this, how best to go about it depends on your use case. In my current site I use a mix of properties and signals to acheive this functionality.</p> <p>Using a property - less db writes works &amp; even if you execute bulk deletes on a model, but generates a query everytime you display it....
0
2016-10-02T22:31:22Z
[ "python", "django", "django-allauth" ]
TypeError: coercing to Unicode: need string or buffer, list found: how to create a loop
39,820,542
<p>I'm working on a python script that will add a folder and all of its contents to a zip file using both <code>zipfile</code> and <code>os</code>.</p> <pre><code>z = ZipFile("mynewfile.zip", "w") z.write(os.walk(directory)) z.printdir() z.close() </code></pre> <p>Unfortunatly I've found that this is considered a lis...
-1
2016-10-02T19:01:04Z
39,821,453
<p>The following code should do it. Since files is a list. You simply iterate over that list and write the filenames to the zipfile. In the code below I'm also using the context manager <code>with</code> with that I don't need to close the file manually, because it does that for me. </p> <pre><code>from zipfile import...
0
2016-10-02T20:36:48Z
[ "python" ]
Python: How to connect to a server database?
39,820,550
<p>Which modules would you recommand for connecting a SQL database on the server and how to install and use them?</p> <p>I'm developing with Python and PyQt5 an application which needs results from a server database.</p>
-1
2016-10-02T19:02:14Z
39,820,609
<p>I suppose it depends on what database you're looking to use. If you're using mysql you might want to check out <a href="https://github.com/PyMySQL" rel="nofollow">https://github.com/PyMySQL</a> . I have been using it and seems to be working out quite nicely. </p>
1
2016-10-02T19:07:54Z
[ "python", "sql", "database", "client" ]