title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
sequence
Delete trailing marks ]]
40,056,331
<p>Doing some regex and I can't sus out how I can get rid of the ]] marks from this string</p> <p>Regex:</p> <pre><code>&lt;title&gt;&lt;!\[CDATA\[(.*?)&lt;/title&gt; </code></pre> <p>String:</p> <pre><code>&lt;item&gt; &lt;title&gt;&lt;![CDATA[Coronation Street star Jean Alexander dies aged 90]]&gt;&lt;/title&gt; &lt;description&gt; </code></pre> <p>Returned: Coronation Street star Jean Alexander dies aged 90]]</p> <p>What I want returned: Coronation Street star Jean Alexander dies aged 90</p>
-2
2016-10-15T07:28:10Z
40,056,415
<p>You have to escape the square brackets in the end too.</p> <pre><code>string = "&lt;title&gt;&lt;![CDATA[Coronation Street star Jean Alexander dies aged 90]]&gt;&lt;/title&gt;" result = re.findall(r"\[.*\[(.*?)\]\]", string) print(result) </code></pre>
0
2016-10-15T07:37:33Z
[ "python", "regex" ]
Delete trailing marks ]]
40,056,331
<p>Doing some regex and I can't sus out how I can get rid of the ]] marks from this string</p> <p>Regex:</p> <pre><code>&lt;title&gt;&lt;!\[CDATA\[(.*?)&lt;/title&gt; </code></pre> <p>String:</p> <pre><code>&lt;item&gt; &lt;title&gt;&lt;![CDATA[Coronation Street star Jean Alexander dies aged 90]]&gt;&lt;/title&gt; &lt;description&gt; </code></pre> <p>Returned: Coronation Street star Jean Alexander dies aged 90]]</p> <p>What I want returned: Coronation Street star Jean Alexander dies aged 90</p>
-2
2016-10-15T07:28:10Z
40,056,953
<p>I infer that you'd like an answer with respect to using a regex with python. So, here's some code that performs the desired action:</p> <pre><code>import re string = "&lt;title&gt;&lt;![CDATA[Coronation Street star Jean Alexander dies aged 90]]&gt;&lt;/title&gt;" result = re.findall(r"\[.*\[(.*?)\]\]", string) print ' '.join(result) </code></pre> <p>Note: this code runs under python 2.8 May run code <a href="http://www.tutorialspoint.com/execute_python_online.php?PID=0Bw_CjBb95KQMQzAxQ2pfRWxBekU" rel="nofollow">here</a>.</p> <p>A few points about the code. The findall method of the regular expression object is available once the code imports that object. Your regex needs a little bit of tweaking in order for the two terminating brackets to not appear by <em>including them in the regex</em>. Now, the result will be a list with the correct data and that list is then converted by next line of code into a string.</p> <p>I find it easier personally using PHP for something like this, so I'll also show you a PHP solution that runs on PHP versions 5 and 7:</p> <pre><code>&lt;?php $subject = "[CDATA[Coronation Street star Jean Alexander dies aged 90]]"; $pattern = "/\[.*\[(.*?)\]\]/"; preg_match($pattern, $subject, $matches); var_dump($matches[1]); </code></pre> <p>With PHP the result is immediately available as a string in element 1 of $matches as long as preg_match is successful.</p> <p>See <a href="https://3v4l.org/9NVLl" rel="nofollow">live code</a>.</p>
0
2016-10-15T08:45:36Z
[ "python", "regex" ]
Is it required to build tensorflow from source to use inception?
40,056,498
<p>I have already asked <a href="https://github.com/tensorflow/models/issues/534" rel="nofollow">this question </a> in their repository, but they redirected me here on stack overflow. So, is it required to build <code>tensorflow</code> from the sources to use <code>inception</code>? Or a binary install of <code>tensorflow</code> enough to use <code>inception</code>? Thanks in advance.</p>
0
2016-10-15T07:47:08Z
40,059,248
<p>It works fine from the binary install. </p> <p>The <a href="https://github.com/tensorflow/models/" rel="nofollow">tensorflow-models repo</a> has an <a href="https://github.com/tensorflow/models/blob/master/slim/slim_walkthough.ipynb" rel="nofollow">example notebook</a> with the boiler-plate code you need to get it running.</p> <p>There is also <a href="https://www.tensorflow.org/versions/r0.11/tutorials/image_recognition/index.html" rel="nofollow">an example</a> in the tutorials on the main site. </p>
0
2016-10-15T12:52:26Z
[ "python", "machine-learning", "tensorflow" ]
Why sessionid is empty string return response Set-Cookie on django?
40,056,543
<p>There is question for me , why django sessionid is empty value, return set-cookie</p> <p>however sessionid value is empty but set Set-Cookie,</p> <p>request on cookie :</p> <pre><code>Cookie: sessionid=;csrftoken=BF8nOVWsMJaX9Gi3aJijGSO97iTyLpNY </code></pre> <p>here sessionid is empty now response this request from django:</p> <pre><code>HTTP/1.1 200 OK Date: Sun, 09 Oct 2016 08:17:15 GMT Content-Type: application/json Connection: keep-alive Set-Cookie: sessionid=; expires=Thu, 01-Jan-1970 00:00:00 GMT; Max-Age=0; Path=/ Content-Length: 18 </code></pre> <p>why any check sessionid is empty or no from django? and response like without Set-Cookie:</p> <pre><code>HTTP/1.1 200 OK Date: Sun, 09 Oct 2016 08:17:15 GMT Content-Type: application/json Connection: keep-alive Content-Length: 18 </code></pre>
0
2016-10-15T07:52:52Z
40,058,848
<p>Try to login to you django project and then check the <code>sessionid</code> value. You will see the cookie's value there. If Django does need to keep some data in the cookie, it will not. </p>
0
2016-10-15T12:10:09Z
[ "python", "django", "cookies" ]
Pydev import not working, but Terminal import does
40,056,578
<p>I recently installed a library (obspy) on my MBP with anaconda. The installation seemed successful but for some reason I can't get it to run in my Eclipse (PyDev) environment. Going into the python shell on Terminal does however work. How can make the two consistent?</p>
1
2016-10-15T07:56:00Z
40,130,637
<p>Check that you have the same Python in both places and the same PYTHONPATH in both cases.</p> <p>To do that, create a script with:</p> <pre><code>import sys print('\n'.join(sorted(sys.path))) print(sys.executable) </code></pre> <p>and run from your terminal and from Eclipse to see if you have the same thing in both.</p>
0
2016-10-19T11:49:53Z
[ "python", "anaconda", "pydev" ]
pexpect child.before and child.after is empty
40,056,626
<pre><code>&gt;&gt;&gt; ssh_stuff ['yes/no', 'Password:', 'password', 'Are you sure you want to continue connecting'] &gt;&gt;&gt; prompt ['$', '#'] &gt;&gt;&gt; child = pexpect.spawn('ssh kumarshubham@localhost') &gt;&gt;&gt; child.expect(ssh_stuff) 1 &gt;&gt;&gt; child.sendline(getpass.getpass()) Password: 11 &gt;&gt;&gt; child.expect(prompt) 0 &gt;&gt;&gt; child.sendline('ls -l') 6 &gt;&gt;&gt; child.expect(prompt) 0 &gt;&gt;&gt; print child.before, child.after </code></pre> <p>can one tell me why my child.before and after is empty, it should return directory listing.</p>
0
2016-10-15T08:01:44Z
40,058,683
<p>To match a literal <code>$</code> char you have to use <code>\$</code> so try with <code>prompt = ['\$', '#']</code> (or simply <code>prompt = '[$#]'</code>). And according to pexpect's doc:</p> <blockquote> <p>The <code>$</code> pattern for end of line match is useless. The <code>$</code> matches the end of string, but <code>Pexpect</code> reads from the child one character at a time, so <strong>each character looks like the end of a line</strong>.</p> </blockquote>
0
2016-10-15T11:52:26Z
[ "python", "pexpect" ]
print a list of dictionaries in table form
40,056,747
<p>assume I have this list as global list </p> <pre><code> dataset =[{'Major': 'Biology', 'GPA': '2.4', 'Name': 'Edward'}, {'Major': 'Physics', 'GPA': '2.9', 'Name':'Emily'}, {'Major':'Mathematics', 'GPA': '3.5', 'Name': 'Sarah'}] </code></pre> <p>and a want a function print() to print it as </p> <pre><code> name major GPA =============================== edward Biology 2.4 Emily physics 2.9 sarah mathematics 3.5 </code></pre>
-2
2016-10-15T08:18:11Z
40,056,776
<pre><code>for dicts in dataset: print(dicts.get('Name')), print(dicts.get('Major')), print(dicts.get('GPA')), </code></pre> <p>Example </p> <pre><code>&gt;&gt;&gt; dataset =[{'Major': 'Biology', 'GPA': '2.4', 'Name': 'Edward'}, {'Major': 'Physics', 'GPA': '2.9', 'Name': 'Emily'}, {'Major': 'Mathematics', 'GPA': '3.5', 'Name': 'Sarah'}] &gt;&gt;&gt; &gt;&gt;&gt; for dicts in dataset: ... print(dicts.get('Name')), ... print(dicts.get('Major')), ... print(dicts.get('GPA')), ... Edward Biology 2.4 Emily Physics 2.9 Sarah Mathematics 3.5 </code></pre>
0
2016-10-15T08:22:06Z
[ "python" ]
print a list of dictionaries in table form
40,056,747
<p>assume I have this list as global list </p> <pre><code> dataset =[{'Major': 'Biology', 'GPA': '2.4', 'Name': 'Edward'}, {'Major': 'Physics', 'GPA': '2.9', 'Name':'Emily'}, {'Major':'Mathematics', 'GPA': '3.5', 'Name': 'Sarah'}] </code></pre> <p>and a want a function print() to print it as </p> <pre><code> name major GPA =============================== edward Biology 2.4 Emily physics 2.9 sarah mathematics 3.5 </code></pre>
-2
2016-10-15T08:18:11Z
40,056,796
<p>you can use module <a href="https://pypi.python.org/pypi/tabulate" rel="nofollow">tabulate</a></p> <pre><code>&gt;&gt;&gt; import tabulate &gt;&gt;&gt; dataset =[{'Major': 'Biology', 'GPA': '2.4', 'Name': 'Edward'}, {'Major': 'Physics', 'GPA': '2.9', 'Name': 'Emily'}, {'Major': 'Mathematics', 'GPA': '3.5', 'Name': 'Sarah'}] &gt;&gt;&gt; header = dataset[0].keys() &gt;&gt;&gt; rows = [x.values() for x in dataset] &gt;&gt;&gt; print tabulate.tabulate(rows, header) Major GPA Name ----------- ----- ------ Biology 2.4 Edward Physics 2.9 Emily Mathematics 3.5 Sarah </code></pre> <p>you can use <code>tablefmt</code> parameter for different table format</p> <pre><code>&gt;&gt;&gt; print tabulate.tabulate(rows, header, tablefmt='grid') +-------------+-------+--------+ | Major | GPA | Name | +=============+=======+========+ | Biology | 2.4 | Edward | +-------------+-------+--------+ | Physics | 2.9 | Emily | +-------------+-------+--------+ | Mathematics | 3.5 | Sarah | +-------------+-------+--------+ &gt;&gt;&gt; print tabulate.tabulate(rows, header, tablefmt='rst') =========== ===== ====== Major GPA Name =========== ===== ====== Biology 2.4 Edward Physics 2.9 Emily Mathematics 3.5 Sarah =========== ===== ====== </code></pre>
3
2016-10-15T08:25:06Z
[ "python" ]
print a list of dictionaries in table form
40,056,747
<p>assume I have this list as global list </p> <pre><code> dataset =[{'Major': 'Biology', 'GPA': '2.4', 'Name': 'Edward'}, {'Major': 'Physics', 'GPA': '2.9', 'Name':'Emily'}, {'Major':'Mathematics', 'GPA': '3.5', 'Name': 'Sarah'}] </code></pre> <p>and a want a function print() to print it as </p> <pre><code> name major GPA =============================== edward Biology 2.4 Emily physics 2.9 sarah mathematics 3.5 </code></pre>
-2
2016-10-15T08:18:11Z
40,056,851
<p>How about this: </p> <pre><code>from __future__ import print_function dataset =[{'Major': 'Biology', 'GPA': '2.4', 'Name': 'Edward'},Physics', 'GPA': '2.9', 'Name': 'Emily'},Mathematics', 'GPA': '3.5', 'Name': 'Sarah'}] [print("%s %s: %s\n"%(item['Name'],item['Major'],item['GPA'])) for item in dataset] </code></pre> <p>result: </p> <pre><code>Edward Biology: 2.4 Emily Physics: 2.9 Sarah Mathematics: 3.5 </code></pre>
0
2016-10-15T08:32:37Z
[ "python" ]
python calling variables from another script into current script
40,056,800
<p>I'm trying to call a variable from another script into my current script but running into "variable not defined" issues.</p> <p>botoGetTags.py</p> <pre><code>20 def findLargestIP(): 21 for i in tagList: 22 #remove all the spacing in the tags 23 ec2Tags = i.strip() 24 #seperate any multiple tags 25 ec2SingleTag = ec2Tags.split(',') 26 #find the last octect of the ip address 27 fullIPTag = ec2SingleTag[1].split('.') 28 #remove the CIDR from ip to get the last octect 29 lastIPsTag = fullIPTag[3].split('/') 30 lastOctect = lastIPsTag[0] 31 ipList.append(lastOctect) 32 largestIP = int(ipList[0]) 33 for latestIP in ipList: 34 if int(latestIP) &gt; largestIP: 35 largestIP = latestIP 36 return largestIP 37 #print largestIP 38 39 if __name__ == '__main__': 40 getec2Tags() 41 largestIP = findLargestIP() 42 print largestIP </code></pre> <p>So this script ^ correctly returns the value of <code>largestIP</code> but in my other script </p> <p>terraform.py</p> <pre><code> 1 import botoGetTags 8 largestIP = findLargestIP() </code></pre> <p>before I execute any of the functions in my script, terraTFgen.py, I get:</p> <pre><code>Traceback (most recent call last): File "terraTFgen.py", line 8, in &lt;module&gt; largestIP = findLargestIP() NameError: name 'findLargestIP' is not defined </code></pre> <p>I thought that if I import another script I could use those variables in my current script is there another step I should take?</p> <p>Thanks</p>
0
2016-10-15T08:25:20Z
40,056,824
<p>You imported the module, not the function. So you need to refer to the function via the module:</p> <pre><code>import botoGetTags largestIP = botoGetTags.findLargestIP() </code></pre> <p>Alternatively you could import the function directly:</p> <pre><code>from botoGetTags import findLargestIP largestIP = findLargestIP() </code></pre>
2
2016-10-15T08:27:56Z
[ "python", "function", "import" ]
What does the following segment do - Pyhon
40,056,813
<p>I have a problem with the following function. I can't understand what it does, because I'm new to Python, can you help me, please. Thanks in advance.</p> <pre><code>def foo(limit): a = [True] * limit a[0] = a[1] = False for (i,b) in enumerate(a): if b: yield i for n in xrange(i*i,limit,i): a[n] = False </code></pre>
-2
2016-10-15T08:26:51Z
40,093,364
<p>This is example of Binary Indexed Tree. </p>
0
2016-10-17T18:35:55Z
[ "python" ]
Nested For Loop to Access MultiIndex Pandas Dataframe
40,056,866
<p>I have a Dataframe with 3 levels of MultiIndex. They are "Category", "Brand" and "Zip Code". There is one series ("Sales") in the Dataframe. I'd like to loop around the "Category" and "Brand" index levels and serve up a Dataframe with "Zip Code" as the Index and "Sales" as a series.</p> <p>When I only have two multi-index level I have used <code>groupby</code> e.g.</p> <pre><code>for name, group in df.groupby(level = 0): </code></pre> <p>I'm struggling to see how to iterate through the next index level.</p>
0
2016-10-15T08:34:03Z
40,058,345
<p>Not sure how you want your DataFrame grouped, but I see 2 options. The first option will give you a DataFrame with the zip codes as the index ordered as they currently are within the MultiIndex. The second option will group the zip codes such that you have an index of only the unique zip codes and the sales numbers could be aggregated with whatever function you fancy. These can both be accomplished a couple of ways:</p> <p>1a)</p> <pre><code>df = df.reset_index([0,1], drop=True) </code></pre> <p>1b)</p> <pre><code>df.index = df.index.droplevel([0,1]) </code></pre> <p>2a)</p> <pre><code>df = df.reset_index([0,1], drop=True).groupby(by='Zip Code') </code></pre> <p>2b) </p> <pre><code>df.index = df.index.droplevel([0,1]) df = df.groupby(by='Zip Code') </code></pre> <p>Hope that helps.</p>
0
2016-10-15T11:16:15Z
[ "python", "pandas", "dataframe" ]
How to create an instance of a class inside a method within the class, python
40,056,915
<p>My class deals with lists of ints and computing them so they don't have reoccurring values. I have implemented a new method 'intersect' which takes in two intSet objects and creates a new object with the values that appear in both objects lists (vals). </p> <p>Origially i was creating a new list inside the method (instead of an object) to add the ints found in both lists however i thought it would be fitting to create a new object and add the values to val in the new object. However I get the error <code>NameError: global name 'inSet' is not defined</code></p> <p>Here's my code: </p> <pre><code>class intSet(object): """An intSet is a set of integers The value is represented by a list of ints, self.vals. Each int in the set occurs in self.vals exactly once.""" def __init__(self): """Create an empty set of integers""" self.vals = [] def insert(self, e): """Assumes e is an integer and inserts e into self""" if not e in self.vals: self.vals.append(e) def member(self, e): """Assumes e is an integer Returns True if e is in self, and False otherwise""" return e in self.vals def remove(self, e): """Assumes e is an integer and removes e from self Raises ValueError if e is not in self""" try: self.vals.remove(e) except: raise ValueError(str(e) + ' not found') def __str__(self): """Returns a string representation of self""" self.vals.sort() return '{' + ','.join([str(e) for e in self.vals]) + '}' def intersect(self, other): #intersected = [] intersected = inSet() for x in self.vals: if x in other.vals: #intersected.append(x) intersected.insert(x) return intersected a= {-15,-14,-5,-2,-1,1,3,4,11,18} b= {-12,-3,3,8,12,16,18,20} set1 = intSet() set2 = intSet() [set1.insert(x) for x in a] [set2.insert(x) for x in a] print set1.intersect(set2) </code></pre> <p>Bonus question, most the code was written by the admins for the MOOC, 6.00.1x. I just had to implement the 'intersect' method. Why are curly braces which are for dictionary purposes used instead on list [] braces ? </p>
0
2016-10-15T08:38:57Z
40,056,942
<p>It's intSet, not inSet, you've misspelled it in your intersect method. And as a habit it's better to start your classes with a capital (although there are no fixed rules, this is a habit widely adhered to).</p> <p>About the curly braces, they are not only for dictionaries but also for Python sets. So by using them in the __str__ method, the output suggests that instances of your class are indeed a kind of sets.</p>
1
2016-10-15T08:42:59Z
[ "python", "class", "oop", "methods" ]
Python ValueError: too many values to unpack in a While loop
40,056,973
<p>I am getting this exception from the following code and mainly form the second line in the while loop, any hint please? Thank you.</p> <pre><code>def SampleLvl(self, mods, inds, M): calcM = 0 total_time = 0 p = np.arange(1, self.last_itr.computedMoments()+1) psums_delta = _empty_obj() psums_fine = _empty_obj() while calcM &lt; M: curM = np.minimum(M-calcM, self.params.maxM) values, samples_time = self.fn.SampleLvl(inds=inds, M=curM) total_time += samples_time delta = np.sum(values * \ _expand(mods, 1, values.shape), axis=1) A1 = np.tile(delta, (len(p),) + (1,)*len(delta.shape) ) A2 = np.tile(values[:, 0], (len(p),) + (1,)*len(delta.shape) ) B = _expand(p, 0, A1.shape) psums_delta += np.sum(A1**B, axis=1) psums_fine += np.sum(A2**B, axis=1) calcM += values.shape[0] return calcM, psums_delta, psums_fine, total_time </code></pre> <p>I got this error</p> <p>, line 740, in SampleLvl values, samples_time = self.fn.SampleLvl(inds=inds, M=curM) ValueError: too many values to unpack</p>
0
2016-10-15T08:47:54Z
40,057,047
<p>In this line:</p> <pre><code>values, samples_time = self.fn.SampleLvl(inds=inds, M=curM) </code></pre> <p>you assign the result of <code>SampleLvl</code> to 2 variables, but your function, <code>SampleLvl</code>, that you seem to call recursively in that line, returns a 4-tuple. I assume that <code>self.fn.SampleLvl</code> is the same function you're in already. If that's the case you've also omitted the <code>mods</code> param in the call.</p> <p>Another remark is that a bit more context would be handy. I just assume that there's only one <code>SampleLvl</code>, so <code>self==self.fn</code>, but there may in fact be 2 different functions with the same name involved, which, without context, I find confusing.</p>
0
2016-10-15T08:56:34Z
[ "python", "python-2.7" ]
Python ValueError: too many values to unpack in a While loop
40,056,973
<p>I am getting this exception from the following code and mainly form the second line in the while loop, any hint please? Thank you.</p> <pre><code>def SampleLvl(self, mods, inds, M): calcM = 0 total_time = 0 p = np.arange(1, self.last_itr.computedMoments()+1) psums_delta = _empty_obj() psums_fine = _empty_obj() while calcM &lt; M: curM = np.minimum(M-calcM, self.params.maxM) values, samples_time = self.fn.SampleLvl(inds=inds, M=curM) total_time += samples_time delta = np.sum(values * \ _expand(mods, 1, values.shape), axis=1) A1 = np.tile(delta, (len(p),) + (1,)*len(delta.shape) ) A2 = np.tile(values[:, 0], (len(p),) + (1,)*len(delta.shape) ) B = _expand(p, 0, A1.shape) psums_delta += np.sum(A1**B, axis=1) psums_fine += np.sum(A2**B, axis=1) calcM += values.shape[0] return calcM, psums_delta, psums_fine, total_time </code></pre> <p>I got this error</p> <p>, line 740, in SampleLvl values, samples_time = self.fn.SampleLvl(inds=inds, M=curM) ValueError: too many values to unpack</p>
0
2016-10-15T08:47:54Z
40,057,254
<p>You will get a <code>ValueError: too many values to unpack</code> when you try and assign more variables into less variables. </p> <p>For example, if you had a function <code>foo()</code> which returns <code>(a, b, c)</code> you could do: <code>a, b, c = foo()</code> but you would get an error if you tried to do <code>a, b = foo()</code> as the function returns more variables than you are trying to assign to. </p> <p>You do this here:</p> <pre><code>values, samples_time = self.fn.SampleLvl(inds=inds, M=curM) </code></pre> <p>Hope this helps! </p>
0
2016-10-15T09:16:13Z
[ "python", "python-2.7" ]
string is a JSON object or JSON array in Python?
40,056,998
<p>I am reading JSON file line by line. Few lines contain JSON objects while other contains JSON array. I am using <code>json.loads(line)</code> function to get JSON from each line. </p> <pre><code>def read_json_file(file_name): json_file = [] with open(file_name) as f: for line in f: json_file.append((line)) json_array = [] for obj in json_file: try: json_array.append(json.loads(obj)) except ValueError: print("data was not valid JSON") return json_array </code></pre> <p>Is there any way that I can find out that object I am reading is JSON Object or JSON array? I want to save all the result in json_array.</p> <p>I will be thankful to you if anyone can help me.</p>
2
2016-10-15T08:50:32Z
40,057,142
<p>The problem with your code - if line does not contain <em>full</em> JSON object - it seldom does - it will nearly always fail.</p> <p>Unlike in Java, in Python JSON is naturally represented by hierarchical mixture of list and dictionary elements. So, if you are looking for list elements in your JSON, you may use recursive search.</p> <p>If you want to check if your file is valid JSON - the code below is simpler and shorter test</p> <pre><code>try: with open(file_name) as f: json_obj = json.load(f) except: print "Not valid JSON" </code></pre> <p><strong>EDIT</strong> Is it JSON file or JSON schema?</p> <p>In the latter, you may just check if your object is list</p> <pre><code>obj = json.loads(line) isintance(obj, list) </code></pre> <p>As I have already stated, there's no such thing as "JSON object" in Python</p> <p>PS If you read file line by line, and each line is JSON object - it's not a JSON file, it's a file where each string contains JSON. Otherwise, your test will fail on the first line already, which will be just </p> <pre><code>{ </code></pre>
0
2016-10-15T09:05:36Z
[ "python", "json", "python-3.x" ]
string is a JSON object or JSON array in Python?
40,056,998
<p>I am reading JSON file line by line. Few lines contain JSON objects while other contains JSON array. I am using <code>json.loads(line)</code> function to get JSON from each line. </p> <pre><code>def read_json_file(file_name): json_file = [] with open(file_name) as f: for line in f: json_file.append((line)) json_array = [] for obj in json_file: try: json_array.append(json.loads(obj)) except ValueError: print("data was not valid JSON") return json_array </code></pre> <p>Is there any way that I can find out that object I am reading is JSON Object or JSON array? I want to save all the result in json_array.</p> <p>I will be thankful to you if anyone can help me.</p>
2
2016-10-15T08:50:32Z
40,057,410
<p>In python, JSON object is converted into <code>dict</code> and JSON list is converted into <code>list</code> datatypes.</p> <p>So, if you want to check the line content which should be valid <strong>JSON</strong>, is <code>JSON Object</code> or <code>JSON Array</code>, then this code will helps you:-</p> <pre><code>import json # assume that, each line is valid json data obj = json.loads(line) # if returns true, then JSON Array isintance(obj, list) # if returns true, then JSON Object. isintance(obj, dict) </code></pre>
2
2016-10-15T09:35:39Z
[ "python", "json", "python-3.x" ]
Create AbstractBaseUser
40,057,001
<p>Try to create AbstractBaseUser and custom auth.</p> <p>models.py </p> <pre><code>class Account(AbstractBaseUser): account_id = models.AutoField(primary_key=True) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) birthday_date = models.DateField(blank=True, null=True) sex = models.TextField(blank=True, null=True) # This field type is a guess. country = models.CharField(max_length=255, blank=True, null=True) city = models.CharField(max_length=255, blank=True, null=True) email = models.CharField(unique=True, max_length=320) mobile_number = models.CharField(unique=True, max_length=45, blank=True, null=True) registration_date = models.DateTimeField() expired_date = models.DateField(blank=True, null=False) account_type = models.TextField() # This field type is a guess. objects = AccountManager USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name', 'registration_date', 'account_type'] class Meta: managed = False db_table = 'account' </code></pre> <p>AccountManager</p> <pre><code>class AccountManager(BaseUserManager): def create_user(self, first_name, last_name, birthday_date, sex, country, city, email, mobile_number, registration_date, expired_date, account_type, password): fields = [first_name, last_name, birthday_date, sex, country, email, mobile_number, registration_date, expired_date, account_type, password] user = self.model( email=self.normalize_email(email), first_name=first_name, last_name=last_name, birthday_date=birthday_date, sex=sex, country=country, city=city, mobile_number=mobile_number, registration_date=registration_date, expired_date=expired_date, account_type=account_type, ) user.set_password(password) user.save() return user </code></pre> <p>setting.py</p> <pre><code> INSTALLED_APPS = [ 'models', ...] AUTH_USER_MODEL = 'models.Account' AUTHENTICATION_BACKENDS = ('models.backend.EmailOrPhoneBackend',) </code></pre> <p>backend.py</p> <pre><code>class EmailOrPhoneBackend(object): def authenticate(self, username=None, password=None, **kwargs): try: # Try to fetch the user by searching the username or email field user = Account.objects.get(Q(mobile_number=username) | Q(email=username)) if user.check_password(password): return user except Account.DoesNotExist: # Run the default password hasher once to reduce the timing # difference between an existing and a non-existing user (#20760). Account().set_password(password) </code></pre> <p>I try to creatae new user by parsing post data and saving it to db:</p> <pre><code>def post(self, request, *args, **kwargs): postDict = dict(request.POST) account = Account(); for element in postDict: jsonPostDict = json.loads(element) for value in jsonPostDict: print('key is : ' + value) print('value is : ' + jsonPostDict[value]) if value == 'firstName': account.first_name = jsonPostDict[value] print('set first name') if value == 'lastName': account.last_name = jsonPostDict[value] print('set last name') if value == 'email': account.email = jsonPostDict[value] print('set email') if value == 'password': account.set_password(jsonPostDict[value]) print('set password') account.account_type = 'free' account.save() return HttpResponseRedirect("/admin", request, *args, **kwargs) </code></pre> <p>Log: </p> <pre><code>key is : firstName value is : a set first name key is : email value is : [email protected] set email key is : password value is : qwdsfgh23e set password key is : lastName value is : a set last name Internal Server Error: /signup Traceback (most recent call last): File "/usr/local/lib/python3.4/dist-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) psycopg2.ProgrammingError: ERROR: row "password" in table "account" does not exist LINE 1: INSERT INTO "account" ("password", "last_login", "first_name... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/local/lib/python3.4/dist-packages/django/core/handlers/exception.py", line 39, in inner response = get_response(request) File "/usr/local/lib/python3.4/dist-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.4/dist-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.4/dist-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.4/dist-packages/django/views/generic/base.py", line 88, in dispatch return handler(request, *args, **kwargs) File "/usr/finstatement/project/account_management/views.py", line 44, in post account.save() File "/usr/local/lib/python3.4/dist-packages/django/contrib/auth/base_user.py", line 80, in save super(AbstractBaseUser, self).save(*args, **kwargs) File "/usr/local/lib/python3.4/dist-packages/django/db/models/base.py", line 796, in save force_update=force_update, update_fields=update_fields) File "/usr/local/lib/python3.4/dist-packages/django/db/models/base.py", line 824, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "/usr/local/lib/python3.4/dist-packages/django/db/models/base.py", line 908, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "/usr/local/lib/python3.4/dist-packages/django/db/models/base.py", line 947, in _do_insert using=using, raw=raw) File "/usr/local/lib/python3.4/dist-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/local/lib/python3.4/dist-packages/django/db/models/query.py", line 1045, in _insert return query.get_compiler(using=using).execute_sql(return_id) File "/usr/local/lib/python3.4/dist-packages/django/db/models/sql/compiler.py", line 1054, in execute_sql cursor.execute(sql, params) File "/usr/local/lib/python3.4/dist-packages/django/db/backends/utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/usr/local/lib/python3.4/dist-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/usr/local/lib/python3.4/dist-packages/django/db/utils.py", line 94, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/usr/local/lib/python3.4/dist-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/usr/local/lib/python3.4/dist-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: ОШИБКА: row "password" in table "account" does not exist LINE 1: INSERT INTO "account" ("password", "last_login", "first_name... ^ [15/Oct/2016 08:40:22] "POST /signup HTTP/1.1" 500 147276 </code></pre> <p>I should add password row to my database or, I make some mistakes in customization of auth or backend?</p>
0
2016-10-15T08:50:47Z
40,058,619
<p>Look at you <code>Account</code> model. There is no <code>password</code> field. You should add this field and than you can save data there.</p>
0
2016-10-15T11:46:04Z
[ "python", "django", "postgresql" ]
using confusion matrix as scoring metric in cross validation in scikit learn
40,057,049
<p>I am creating a pipeline in scikit learn, </p> <pre><code>pipeline = Pipeline([ ('bow', CountVectorizer()), ('classifier', BernoulliNB()), ]) </code></pre> <p>and computing the accuracy using cross validation</p> <pre><code>scores = cross_val_score(pipeline, # steps to convert raw messages into models train_set, # training data label_train, # training labels cv=5, # split data randomly into 10 parts: 9 for training, 1 for scoring scoring='accuracy', # which scoring metric? n_jobs=-1, # -1 = use all cores = faster ) </code></pre> <p>How can I report confusion matrix instead of 'accuracy'?</p>
0
2016-10-15T08:56:54Z
40,058,433
<p>Short answer is "you cannot".</p> <p>You need to understand difference between <code>cross_val_score</code> and cross validation as model selection method. <code>cross_val_score</code> as name suggests, works only on <strong>scores</strong>. Confusion matrix is not a score, it is a kind of summary of what happened during evaluation. A major distinction is that a score is supposed to return <strong>an orderable object</strong>, in particular in scikit-learn - a <strong>float</strong>. So, based on score you can tell whether method b is better from a by simply comparing if b has bigger score. You cannot do this with confusion matrix which, again as name suggests, is a matrix. </p> <p>If you want to obtain confusion matrices for multiple evaluation runs (such as cross validation) you have to do this by hand, which is not that bad in scikit-learn - it is actually a few lines of code.</p> <pre><code>kf = cross_validation.KFold(len(y), n_folds=5) for train_index, test_index in kf: X_train, X_test = X[train_index], X[test_index] y_train, y_test = y[train_index], y[test_index] model.fit(X_train, y_train) print confusion_matrix(y_test, model.predict(X_test)) </code></pre>
1
2016-10-15T11:26:39Z
[ "python", "machine-learning", "scikit-learn" ]
Correct div-class combination for soup.select()
40,057,058
<p>I'm developing some scraping code and it keeps returning some errors which i imagine others might be able to help with. </p> <p>First I run this snippet:</p> <pre><code>import pandas as pd from urllib.parse import urljoin import requests base = "http://www.reed.co.uk/jobs" url = "http://www.reed.co.uk/jobs?datecreatedoffset=Today&amp;pagesize=100" r = requests.get(url).content soup = BShtml(r, "html.parser") df = pd.DataFrame(columns=["links"], data=[urljoin(base, a["href"]) for a in soup.select("div.pages a.page")]) df </code></pre> <p>I run this snippet on the first page of today's job postings. And I extract the URLs at the bottom of the page in order to find the total number of pages that exist at that point in time. The below regular expressions take this out for me:</p> <pre><code>df['partone'] = df['links'].str.extract('([a-z][a-z][a-z][a-z][a-z][a-z]=[0-9][0-9].)', expand=True) df['maxlink'] = df['partone'].str.extract('([0-9][0-9][0-9])', expand=True) pagenum = df['maxlink'][4] pagenum = pd.to_numeric(pagenum, errors='ignore') </code></pre> <p>Not on the third line above, the number of pages is always contained within the second from last (out of five) URLs in this list. I'm sure there's a more elegant way of doing this, but it suffices as is. I then feed the number i've taken from the URL into a loop:</p> <pre><code>result_set = [] loopbasepref = 'http://www.reed.co.uk/jobs?cached=True&amp;pageno=' loopbasesuf = '&amp;datecreatedoffset=Today&amp;pagesize=100' for pnum in range(1,pagenum): url = loopbasepref + str(pnum) + loopbasesuf r = requests.get(url).content soup = BShtml(r, "html.parser") df2 = pd.DataFrame(columns=["links"], data=[urljoin(base, a["href"]) for a in soup.select("div", class_="results col-xs-12 col-md-10")]) result_set.append(df2) print(df2) </code></pre> <p>This is where I get an error. What i'm attempting to do is loop through all the pages that list jobs starting at page 1 and going up to page N where N = pagenum, and then extract the URL that links through to each individual job page and store that in a dataframe. I've tried various combinations of <code>soup.select("div", class_="")</code> but receive an error each time that reads: <code>TypeError: select() got an unexpected keyword argument 'class_'</code>.</p> <p>If anyone has any thoughts about this, and can see a good way forward, i'd appreciate the help!</p> <p>Cheers</p> <p>Chris</p>
2
2016-10-15T08:57:43Z
40,062,555
<p>You can just keep looping until there is no next page:</p> <pre><code>import requests from bs4 import BeautifulSoup from urllib.parse import urljoin base = "http://www.reed.co.uk" url = "http://www.reed.co.uk/jobs?datecreatedoffset=Today&amp;pagesize=100" def all_urls(): r = requests.get(url).content soup = BeautifulSoup(r, "html.parser") # get the urls from the first page yield [urljoin(base, a["href"]) for a in soup.select("div.details h3.title a[href^=/jobs]")] nxt = soup.find("a", title="Go to next page") # title="Go to next page" is missing when there are no more pages while nxt: # wash/repeat until no more pages r = requests.get(urljoin(base, nxt["href"])).content soup = BeautifulSoup(r, "html.parser") yield [urljoin(base, a["href"]) for a in soup.select("div.details h3.title a[href^=/jobs]")] nxt = soup.find("a", title="Go to next page") </code></pre> <p>Just loop over the generator function to get the urls from each page:</p> <pre><code>for u in (all_urls()): print(u) </code></pre> <p>I also use <code>a[href^=/jobs]</code> in the selector as there are other tags that match so we make sure we just pull the job paths.</p> <p>In your own code, the correct way to use a selector would be:</p> <pre><code>soup.select("div.results.col-xs-12.col-md-10") </code></pre> <p>You syntax is for <em>find</em> or <em>find_all</em> where you use <code>class_=...</code> for css classes:</p> <pre><code>soup.find_all("div", class_="results col-xs-12 col-md-10") </code></pre> <p>But that is not the correct selector regardless.</p> <p>Not sure why you are creating multiple dfs but if that is what you want:</p> <pre><code>def all_urls(): r = requests.get(url).content soup = BeautifulSoup(r, "html.parser") yield pd.DataFrame([urljoin(base, a["href"]) for a in soup.select("div.details h3.title a[href^=/jobs]")], columns=["Links"]) nxt = soup.find("a", title="Go to next page") while nxt: r = requests.get(urljoin(base, nxt["href"])).content soup = BeautifulSoup(r, "html.parser") yield pd.DataFrame([urljoin(base, a["href"]) for a in soup.select("div.details h3.title a[href^=/jobs]")], columns=["Links"]) nxt = soup.find("a", title="Go to next page") dfs = list(all_urls()) </code></pre> <p>That would give you a list of dfs:</p> <pre><code>In [4]: dfs = list(all_urls()) dfs[0].head() In [5]: dfs[0].head(10) Out[5]: Links 0 http://www.reed.co.uk/jobs/tufting-manager/308... 1 http://www.reed.co.uk/jobs/financial-services-... 2 http://www.reed.co.uk/jobs/head-of-finance-mul... 3 http://www.reed.co.uk/jobs/class-1-drivers-req... 4 http://www.reed.co.uk/jobs/freelance-middlewei... 5 http://www.reed.co.uk/jobs/sage-200-consultant... 6 http://www.reed.co.uk/jobs/bereavement-support... 7 http://www.reed.co.uk/jobs/property-letting-ma... 8 http://www.reed.co.uk/jobs/graduate-recruitmen... 9 http://www.reed.co.uk/jobs/solutions-delivery-... </code></pre> <p>But if you want just one then use the original code with <a href="https://docs.python.org/3/library/itertools.html#itertools.chain.from_iterable" rel="nofollow">itertools.chain</a>:</p> <pre><code> from itertools import chain df = pd.DataFrame(columns=["links"], data=list(chain.from_iterable(all_urls()))) </code></pre> <p>Which will give you all the links in one df:</p> <pre><code>In [7]: from itertools import chain ...: df = pd.DataFrame(columns=["links"], data=list(chain.from_iterable(all_ ...: urls()))) ...: In [8]: df.size Out[8]: 675 </code></pre>
0
2016-10-15T18:13:13Z
[ "python", "html", "web-scraping", "beautifulsoup" ]
Why is pandas map slower than list comprehension
40,057,064
<p>Does someone know why pandas/numpy map is slower then list comprehension? I thought I could optimize my code replacing the list comprehensions by map. Since map doesn't need the list append operation.</p> <p>Here is one test:</p> <pre><code>df = pd.DataFrame(range(100000)) </code></pre> <p><strong>List comprehension:</strong></p> <pre><code>%timeit -n 10 df["A"] = [x for x in df[0]] #10 loops, best of 3: 550 ms per loop </code></pre> <p><strong>Pandas map</strong> </p> <pre><code>%timeit -n 10 df["A"] = df[0].map(lambda x: x) #10 loops, best of 3: 797 ms per loop </code></pre> <p><strong>Update</strong> based on comment bellow - list comprehension and map calling same function f, list comprehension faster</p> <pre><code>def f(x): return x %timeit -n 100 df["A"] = df[0].map(f) #100 loops, best of 3: 475 ms per loop %timeit -n 100 df["A"] = [f(x) for x in df[0]] #100 loops, best of 3: 399 ms per loop </code></pre>
1
2016-10-15T08:58:11Z
40,057,151
<p>Here are my results:</p> <p>list comprehension:</p> <pre><code>In [33]: %timeit df["A"] = [x for x in df[0]] 10 loops, best of 3: 72.6 ms per loop </code></pre> <p>simple column assignment:</p> <pre><code>In [34]: %timeit df["A"] = df[0] The slowest run took 5.75 times longer than the fastest. This could mean that an intermediate result is being cached. 1000 loops, best of 3: 661 µs per loop </code></pre> <p>using <code>.map()</code> method:</p> <pre><code>In [35]: map_df = pd.Series(np.random.randint(0, 10**6, 100000)) In [36]: %timeit df["A"] = df[0].map(map_df) 10 loops, best of 3: 19.8 ms per loop </code></pre>
0
2016-10-15T09:06:08Z
[ "python", "performance", "pandas", "list-comprehension" ]
Django get form not ordered list
40,057,092
<p>i changed my admin form when creating new objects to hide some fields, but it orders fields alphabetically, i want to order them as they are in my model.any suggestions?</p> <pre><code>_add_fields = ('name', 'size', 'slug', 'img', 'description', 'quantity') def get_form(self, request, obj=None, **kwargs): model_form = super(ItemAdmin, self).get_form( request, obj, **kwargs ) if obj is None: model_form._meta.fields = self._add_fields model_form.base_fields = { field: model_form.base_fields[field] for field in self._add_fields } return model_form </code></pre>
1
2016-10-15T09:00:51Z
40,057,855
<p>You need to use <code>OrderedDict</code> from <code>collections</code> module to achieve that:</p> <pre><code>from django.contrib import admin from collections import OrderedDict class ItemAdmin(admin.ModelAdmin): _add_fields = ('name', 'category', 'img', 'description', 'quantity') def get_form(self, request, obj=None, **kwargs): model_form = super(ItemAdmin, self).get_form( request, obj, **kwargs ) if obj is None: model_form._meta.fields = self._add_fields d = OrderedDict() for field in self._add_fields: d[field] = model_form.base_fields[field] model_form.base_fields = d return model_form </code></pre>
1
2016-10-15T10:24:21Z
[ "python", "django", "django-admin" ]
Python dynamic function building and closure rule
40,057,122
<p>While interactively executing the following code in <a href="http://pythontutor.com/visualize.html" rel="nofollow">http://pythontutor.com/visualize.html</a>, the frame of each call to <code>build_match_and_apply_functions</code> appears gray in the graphical view:</p> <p><a href="https://i.stack.imgur.com/sxo9k.png" rel="nofollow"><img src="https://i.stack.imgur.com/sxo9k.png" alt="screenshot from pythontutor"></a></p> <p>This program is for getting a plural of a word , which is quoted from the chapter in DIVE in Python 3</p> <p>CODE: </p> <pre><code>import re def build_match_and_apply_functions(pattern, search, replace): def matches_rule(word): return re.search(pattern, word) def apply_rule(word): return re.sub(search, replace, word) return (matches_rule, apply_rule) patterns = \ ( ('[sxz]$', '$', 'es'), ('[^aeioudgkprt]h$', '$', 'es'), ('(qu|[^aeiou])y$', 'y$', 'ies'), ('$', '$', 's') ) rules = [build_match_and_apply_functions(pattern, search, replace) for (pattern, search, replace) in patterns] def plural(noun): for matches_rule, apply_rule in rules: if matches_rule(noun): return apply_rule(noun) plural('vacancy') </code></pre> <p>question:</p> <p>1) what does gray frame mean? it is a closure that still takes memory?</p> <p>2) can I go in memory block. so i can figure out in the objects area , are all matches_rule functions the same or not? if they are the same , f2/f3/f4/f5 should be there to offer pattern/search/replace values.</p> <p>if not, if all matches_rules functions have already be changed to different functions , f2 3 4 5 could be end of live and dispear. they are useless.</p> <p>i dont know , that is how dynamic language works and being built.</p> <hr> <p>pythontutor.com ANALYZE DIGRAM really surprised me, tutor did the good job </p> <p>if u dont expirence it, please copy the link below and paste my code in it. i bet you are having fun with it.</p> <p><a href="http://pythontutor.com/visualize.html" rel="nofollow">http://pythontutor.com/visualize.html</a></p>
1
2016-10-15T09:03:42Z
40,058,432
<p>The gray frames are the execution frames, which contain the closure. They can theoretically be read from memory.</p> <p>For example, I managed to read the data from the frames with the following code (CPython v3.5):</p> <p>Some utilities first:</p> <pre><code>import gc, inspect, ctypes, random def all_live_ids(): """Get all valid object IDs""" for obj in gc.get_objects(): yield id(obj) def getobj(obj_id): """Get the object from object ID""" if obj_id in all_live_ids(): return ctypes.cast(obj_id, ctypes.py_object).value else: return None frame_ids = [] def print_frames(): for fid in frame_ids: frame = getobj(fid) if frame: print('frame', hex(fid), 'is alive and has pattern:', frame.f_locals['pattern']) else: print('frame', hex(fid), 'is dead') </code></pre> <p>Then a simplified version of the code from the question:</p> <pre><code>def build_match_and_apply_functions(pattern, search, replace): frame = inspect.currentframe() frame_ids.append(id(frame)) print('executing frame', frame, 'pattern:', pattern) def matches_rule(word): return re.search(pattern, word) return matches_rule rule1 = build_match_and_apply_functions('[sxz]$', '$', 'es') rule2 = build_match_and_apply_functions('[^aeioudgkprt]h$', '$', 'es') print('\nbefore gc.collect():') print_frames() gc.collect() print('\nafter gc.collect():') print_frames() </code></pre> <p>In my case, it printed:</p> <pre><code>executing frame &lt;frame object at 0x0071EDB0&gt; pattern: [sxz]$ executing frame &lt;frame object at 0x00C0E4B0&gt; pattern: [^aeioudgkprt]h$ before gc.collect(): frame 0x71edb0 is alive and has pattern: [sxz]$ frame 0xc0e4b0 is alive and has pattern: [^aeioudgkprt]h$ after gc.collect(): frame 0x71edb0 is dead frame 0xc0e4b0 is dead </code></pre> <h2>What did I do?</h2> <p>I remembered IDs of all frames in <code>frame_ids</code>. In CPython, <code>id</code> returns the memory address of the object.</p> <p>Then I used <a href="http://stackoverflow.com/a/15702647/389289">this solution</a> to convert IDs back to objects.</p> <p>I had to do that in order to be able to get the frame without ever storing a reference to the frame (Usualy <code>weakref</code> does that, but not with <code>frame</code> objects`)</p> <h2>There is a catch</h2> <p>Notice that the frames disappeared after <code>gc.collect</code>. The frames are not needed once the function finishes, but there were some circular references which prevented their immediate deletion. <code>gc.collect</code> is smart enough to detect those and delete the unneeded frames. With different code, that may happen even without calling <code>gc.collect</code> and I believe it should happen in <a href="http://pythontutor.com/" rel="nofollow">http://pythontutor.com/</a> as well, but their internals are in some sort of conflict with the garbace collector.</p>
1
2016-10-15T11:26:29Z
[ "python", "functional-programming", "closures" ]
Python Pandas Data Formatting: Diffnce in passing index and iloc
40,057,128
<p>This is the sample data:</p> <pre><code>dict_country_gdp = pd.Series([52056.01781,40258.80862,40034.85063,39578.07441], index = ['Luxembourg','Norway', 'Japan', 'Switzerland']) </code></pre> <p>What is the difference between <code>dict_country_gdp[0]</code> and <code>dict_country_gdp.iloc[0]</code>? </p> <p>While the result is the same, when to use which?</p>
1
2016-10-15T09:04:36Z
40,057,921
<p>As you are working with one dimensional series, [] or .iloc will give same results. </p> <p><strong>ONE DIMENSIONAL SERIES:</strong></p> <pre><code>import pandas as pd dict_country_gdp = pd.Series([52056.01781, 40258.80862,40034.85063,39578.07441]) dict_country_gdp Out[]: 0 52056.01781 1 40258.80862 2 40034.85063 3 39578.07441 dtype: float64 dict_country_gdp[0] Out[]: 52056.017809999998 dict_country_gdp.iloc[0] Out[]: 52056.017809999998 </code></pre> <p><strong>MULTI-DIMENSIONAL SERIES:</strong> </p> <pre><code>dict_country_gdp = pd.Series([52056.01781, 40258.80862,40034.85063,39578.07441],[52056.01781, 40258.80862,40034.85063,39578.07441]) dict_country_gdp Out[]: 52056.01781 52056.01781 40258.80862 40258.80862 40034.85063 40034.85063 39578.07441 39578.07441 dtype: float64 </code></pre> <p>Now in this scenario, you cannot access series using [] operator. </p> <pre><code>dict_country_gdp[0] Out[]: KeyError: 0.0 dict_country_gdp.iloc[0] Out[]: 52056.017809999998 </code></pre> <p>iloc provides more control while accessing multidimensional series:</p> <pre><code>dict_country_gdp[0:2] Out[]: Series([], dtype: float64) dict_country_gdp.iloc[0:2] Out[]: 52056.01781 52056.01781 40258.80862 40258.80862 dtype: float64 </code></pre> <p><a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-integer" rel="nofollow">Documentation</a> states:</p> <p>.iloc is primarily integer position based (from 0 to length-1 of the axis), but may also be used with a boolean array. .iloc will raise IndexError if a requested indexer is out-of-bounds, except slice indexers which allow out-of-bounds indexing. (this conforms with python/numpy slice semantics). Allowed inputs are:</p> <ul> <li>An integer e.g. 5</li> <li>A list or array of integers [4, 3, 0]</li> <li>A slice object with ints 1:7</li> <li>A boolean array</li> <li>A callable function with one argument (the calling <strong>Series, DataFrame or Panel</strong>) and that returns valid output for indexing (one of the above)</li> </ul> <p>This is why one cannot use [] operator with dataframe objects. Only iloc can be used when it comes to dataframes and multidimensional series. </p>
0
2016-10-15T10:31:59Z
[ "python", "pandas", "dictionary" ]
How can I just import a subdir and use "subdir.pythonfile.function" in python?
40,057,198
<p>I have a python project with following structure:<br> project<br> --subdir<br> ----__init__.py<br> ----func.py (has a function a)<br> --main.py<br></p> <p>I want to use the function "a" in main.py. So I can<br> <code>import subdir.func as F</code><br> <code>F.a()</code></p> <p>But this is not what I want to do, I want to use<br> <code>import subdir</code><br> <code>subdir.func.a()</code><br></p> <p>How can I do that easily?</p> <hr> <p>Solved, Thanks.</p>
0
2016-10-15T09:10:16Z
40,057,470
<p>Keep your directory structure as it is and add this line in your <strong>init</strong>.py :</p> <pre><code>from . import func </code></pre>
0
2016-10-15T09:42:41Z
[ "python", "import", "subdirectory" ]
How can I just import a subdir and use "subdir.pythonfile.function" in python?
40,057,198
<p>I have a python project with following structure:<br> project<br> --subdir<br> ----__init__.py<br> ----func.py (has a function a)<br> --main.py<br></p> <p>I want to use the function "a" in main.py. So I can<br> <code>import subdir.func as F</code><br> <code>F.a()</code></p> <p>But this is not what I want to do, I want to use<br> <code>import subdir</code><br> <code>subdir.func.a()</code><br></p> <p>How can I do that easily?</p> <hr> <p>Solved, Thanks.</p>
0
2016-10-15T09:10:16Z
40,057,727
<p>Let me discuss here your current scenario first. If you print files of 'subdir' here:</p> <pre><code> import subdir as SD print(SD.__file__) </code></pre> <p>It should show the <strong>init</strong>.pyc file name with absolute path. So to resolve issue you have to import the func.py file in <strong>init</strong>.py file</p> <pre><code> from . import func </code></pre>
0
2016-10-15T10:09:52Z
[ "python", "import", "subdirectory" ]
How to monitor a python process and restart it upon abnormal termination
40,057,204
<p>Assume that there is a <code>task.py</code>,breaking due to memory overflow.How can i monitor this and restart it?</p> <pre><code>import time while(1): print('.') # simulate breaks time.sleep(2) exit(0) </code></pre> <p>Thanks</p>
1
2016-10-15T09:11:12Z
40,057,267
<p>You can use a watchdog. Make your worker process update a dummyfile say every 10 secs. Have another, completely independent, process check if the last access wasn't longer that say 20 secs ago. If it was, restart your worker process.</p> <p>There are all kinds of nifty OS-dependent ways to do the same, but this low-tech one always works, even trivially over a network, assuming your clocks are synchronized.</p>
1
2016-10-15T09:18:15Z
[ "python", "linux", "bash" ]
How to monitor a python process and restart it upon abnormal termination
40,057,204
<p>Assume that there is a <code>task.py</code>,breaking due to memory overflow.How can i monitor this and restart it?</p> <pre><code>import time while(1): print('.') # simulate breaks time.sleep(2) exit(0) </code></pre> <p>Thanks</p>
1
2016-10-15T09:11:12Z
40,057,432
<p>If it actually runs out of memory it should get <a href="https://www.kernel.org/doc/gorman/html/understand/understand016.html" rel="nofollow">OOM killed</a>. If you have another process which restarts it continuously (for example <code>while true; do /path/to/my_script.py; done</code>) it should get up and running again immediately.</p>
0
2016-10-15T09:38:31Z
[ "python", "linux", "bash" ]
How to monitor a python process and restart it upon abnormal termination
40,057,204
<p>Assume that there is a <code>task.py</code>,breaking due to memory overflow.How can i monitor this and restart it?</p> <pre><code>import time while(1): print('.') # simulate breaks time.sleep(2) exit(0) </code></pre> <p>Thanks</p>
1
2016-10-15T09:11:12Z
40,059,325
<p>Something like this should work:</p> <pre><code>while ! /path/to/task.py; do echo 'restarting task...' done </code></pre> <p>If <em>task.py</em> exits with non-zero exit status the loop will continue and run the script again. The loop will only break when <em>task.py</em> exits with <code>0</code>.</p> <p>If your program is errored and yield to non-zero exit at all time, this will end up being an infinite loop. So it's better to restrict the number of restart tries by a max_try value:</p> <pre><code>#!/bin/bash max_try=100 count=1 while ! python /path/to/task.py; do ((count++)) # increment (Bashism) #count=$(expr $count + 1) # increment (portable) if [ $count -gt $max_try ]; then break; fi echo 'restarting task...' done </code></pre>
1
2016-10-15T13:01:24Z
[ "python", "linux", "bash" ]
Regex expression excluding "-" tag
40,057,218
<p>Hi right now my regex expression is working as intended. However i wish to specifically exclude items such as how do i update my regex such that it would exclude entries with "-\d*"/ negative quantity? ?</p> <p><a href="https://regex101.com/r/4EUzLo/1" rel="nofollow">https://regex101.com/r/4EUzLo/1</a></p>
2
2016-10-15T09:12:39Z
40,057,403
<p>This should work for you:</p> <pre><code>'\d+\s*([a-zA-Z].*\w)\s+\d.*' </code></pre> <p>The <code>'\d+</code> will only match the positive quantities, and with less steps.</p> <p>Now, just extract the info from the capture group.</p> <p><kbd> <a href="https://regex101.com/r/UylZqb/1" rel="nofollow">Demo</a> </kbd></p>
1
2016-10-15T09:35:10Z
[ "python", "regex" ]
Watch requset in gmail API doesnt work
40,057,253
<p>I am trying to make a watch request using python referring <a href="https://developers.google.com/gmail/api/guides/push" rel="nofollow">google APIs</a> but it does not work. </p> <pre><code>request = { 'labelIds': ['INBOX'], 'topicName': 'projects/myproject/topics/mytopic' } gmail.users().watch(userId='me', body=request).execute() </code></pre> <p>I could not find a library or a package to use <code>gmail.users()</code> function. how to make watch request using an access token</p>
2
2016-10-15T09:16:12Z
40,079,139
<p>Do it in gmail python client(provide by google).under main function </p> <pre><code>request = { 'labelIds': ['INBOX'], 'topicName': 'projects/myprojects/topics/getTopic' } print(service.users().watch(userId='me', body=request).execute()) </code></pre>
0
2016-10-17T05:36:54Z
[ "python", "gmail-api", "google-cloud-pubsub" ]
Beginner python project on school managment system?
40,057,361
<p>i am beginner in programming and just got the hang of python language.i am doing a small project on a miniature school management system using the class defined below.i need help in reading and writing these details into a csv file.i also want to know how to modify these details.i hope you would help me with this in python language itself.</p> <pre><code>class student: def __init__ (self): self.adno=0 self.name="null" self.m = [0,0,0,0,0] self.m[0]=0 self.m[1]=0 self.m[2]=0 self.m[3]=0 self.m[4]=0 def inp(self): print "Enter the details:\n" self.appno=input("Enter the application number :") self.name=raw_input("Enter the name :") print "\nEnter the mark for \n" self.m[0]=input("English : ") self.m[1]=input("Mathematics : ") self.m[2]=input("chemistry : ") self.m[3]=input("Physics : ") self.m[4]=input("computer science: ") def out(self): print "\nApplication number :%d\nName :%s\n" %(self.appno,self.name) print "\nMarks : \n\n" print "English : ",self.m[0] print "Mathematics : ",self.m[1] print "Science : ",self.m[2] print "Social Science : ",self.m[3] print "Second Language: ",self.m[4] </code></pre>
-5
2016-10-15T09:27:52Z
40,057,556
<p>Instead of using csv files, you can also use <strong>Pickle</strong></p> <p>Saving a student:</p> <pre><code>import pickle file = open("student_record.pkl", "w") pickle.dump(file, student_object) file.close() </code></pre> <p>Loading a student's record:</p> <pre><code>import pickle file = open("student_record.pkl") student_object = pickle.load(file) </code></pre> <p>You can also save multiple student classes in one file by putting a list into pickle.dump().</p>
1
2016-10-15T09:53:16Z
[ "python" ]
In Python why do some people include len(s)-2 in some cases for finding a word in a string?
40,057,515
<p>Consider:</p> <pre><code>s = input("Enter a string") n=0 for count in range(len(s)): if s[count:count+3] == "bob": n = n+1 print("Number of times bob occurs is: " ,n) </code></pre> <p>Why do some people use <code>range(len(s)-2)</code> in their code instead of <code>range(len(s))</code> although both give the right output?</p> <p>I just don't understand the <code>len(s)-2</code> part.</p>
0
2016-10-15T09:48:55Z
40,057,575
<p>The last two <code>count</code> values in the for loop, <code>count = len(s)-2</code> and <code>len(s)-1</code> lead to substrings with only 2 or 1 characters, which cannot be equal to a 3 character string.</p>
1
2016-10-15T09:55:18Z
[ "python", "string" ]
In Python why do some people include len(s)-2 in some cases for finding a word in a string?
40,057,515
<p>Consider:</p> <pre><code>s = input("Enter a string") n=0 for count in range(len(s)): if s[count:count+3] == "bob": n = n+1 print("Number of times bob occurs is: " ,n) </code></pre> <p>Why do some people use <code>range(len(s)-2)</code> in their code instead of <code>range(len(s))</code> although both give the right output?</p> <p>I just don't understand the <code>len(s)-2</code> part.</p>
0
2016-10-15T09:48:55Z
40,057,578
<p>"bob" has three characters. So if we want to search "bob" from a given word, you only need to check till the [-3] letter...</p> <p>That's why people search till len(s)-2.</p>
0
2016-10-15T09:55:36Z
[ "python", "string" ]
python webdriver eror
40,057,725
<p>I have recently downloaded selenium and tried to run this script: </p> <pre><code> from selenium import webdriver driver = webdriver.Firefox() </code></pre> <p>but I get this error:</p> <pre><code>Traceback (most recent call last): File "&lt;pyshell#3&gt;", line 1, in &lt;module&gt; driver = webdriver.Firefox() File "C:\Heights\PortableApps\PortablePython2.7.6.1\App\lib\site-packages\selenium-3.0.1-py2.7.egg\selenium\webdriver\firefox\webdriver.py", line 145, in __init__ keep_alive=True) File "C:\Heights\PortableApps\PortablePython2.7.6.1\App\lib\site-packages\selenium-3.0.1-py2.7.egg\selenium\webdriver\remote\webdriver.py", line 92, in __init__ self.start_session(desired_capabilities, browser_profile) File "C:\Heights\PortableApps\PortablePython2.7.6.1\App\lib\site-packages\selenium-3.0.1-py2.7.egg\selenium\webdriver\remote\webdriver.py", line 179, in start_session response = self.execute(Command.NEW_SESSION, capabilities) File "C:\Heights\PortableApps\PortablePython2.7.6.1\App\lib\site-packages\selenium-3.0.1-py2.7.egg\selenium\webdriver\remote\webdriver.py", line 236, in execute self.error_handler.check_response(response) File "C:\Heights\PortableApps\PortablePython2.7.6.1\App\lib\site-packages\selenium-3.0.1-py2.7.egg\selenium\webdriver\remote\errorhandler.py", line 192, in check_response raise exception_class(message, screen, stacktrace) WebDriverException: Message: Expected browser binary location, but unable to find binary in default location, no 'firefox_binary' capability provided, and no binary flag set on the command line </code></pre> <p>Oh by the way this open me geckodriver.exe before its write the eror</p>
0
2016-10-15T10:09:39Z
40,079,431
<p>I got around this by manually setting the binary location as per the following answer:</p> <p><a href="http://stackoverflow.com/a/25715497">http://stackoverflow.com/a/25715497</a></p> <p>Remember to set your binary to the actual location of the firefox binary on your computer</p> <p>eg:</p> <pre><code>from selenium.webdriver.firefox.firefox_binary import FirefoxBinary binary = FirefoxBinary(r'C:\Program Files (x86)\Mozilla Firefox\firefox.exe') self.browser = webdriver.Firefox(firefox_binary=binary) </code></pre> <p>(note: the 'r' before the first quote in the file path string makes python see the string as 'raw' text, and therefore you don't need to escape characters like '\' - you can just put in the path as it actually is)</p>
0
2016-10-17T06:01:37Z
[ "python", "selenium", "path", "webdriver" ]
NewbieQ: Jupyter HTML command not working when multiple code lines
40,057,970
<p>I'm new to Jupyter Notebook and have this simple line of code:</p> <pre><code>HTML('&lt;b&gt;Question&lt;/b&gt;') Q=1 </code></pre> <p>I have found that the first line only works when nothing else comes after it. Is this normal? Do I have to have each line of code in a separate cell?</p>
0
2016-10-15T10:37:23Z
40,107,177
<p>There are two things at play here:</p> <ol> <li><code>HTML</code> creates an HTML <em>object</em>, whose <a href="https://nbviewer.jupyter.org/github/ipython/ipython/blob/5.0.0/examples/IPython%20Kernel/Rich%20Output.ipynb" rel="nofollow">rich representation</a> is the HTML string <code>&lt;b&gt;...</code>. Instantiating such an object does not display it.</li> <li>If a cell ends in an expression (the cell has a result, in a way), the result of that expression is displayed automatically.</li> </ol> <p>So a cell that <em>ends with</em> <code>HTML(...)</code> will display that HTML because it is the 'result' of the cell. If you store the HTML object in a variable, you can display it at any time. IPython has a <code>display</code> function, which is like the Jupyter rich-media version of Python's builtin <code>print</code> function. To display objects at any point:</p> <pre><code>from IPython.display import display display(obj) </code></pre> <p>in your case:</p> <pre><code>display(HTML('&lt;b&gt;Question&lt;/b&gt;')) </code></pre> <p>Or you can store the HTML in a variable and display it later or repeatedly:</p> <pre><code>msg = HTML('&lt;b&gt;Question&lt;/b&gt;') for i in range(3): display(msg) </code></pre>
0
2016-10-18T11:35:34Z
[ "python", "jupyter" ]
import all csv files in directory as pandas dfs and name them as csv filenames
40,058,133
<p>I'm trying to write a script that will import all .csv files in a directory to my workspace as dataframes. Each dataframe should be named as the csv file (minus the extension: .csv).</p> <p>This is what i have so far, but struggling to understand how to assign the correct name to the dataframe in the loop. I've seen posts that suggest using <code>exec()</code> but this does not seem like a great solution.</p> <pre><code>path = "../3_Data/Benefits" # dir path all_files = glob.glob(os.path.join(path, "*.csv")) #make list of paths for file in all_files: dfn = file.split('\\')[-1].split('.')[0] # create string for df name dfn = pd.read_csv(file,skiprows=5) # This line should assign to the value stored in dfn </code></pre> <p>Any help appreciated, thanks.</p>
0
2016-10-15T10:53:54Z
40,059,175
<p><code>DataFrame</code> have no <code>name</code> their index can have a <code>name</code>. This is how to set it.</p> <pre><code>import glob import os path = "./data/" all_files = glob.glob(os.path.join(path, "*.csv")) #make list of paths for file in all_files: # Getting the file name without extension file_name = os.path.splitext(os.path.basename(file))[0] # Reading the file content to create a DataFrame dfn = pd.read_csv(file) # Setting the file name (without extension) as the index name dfn.index.name = file_name # Example showing the Name in the print output # FirstYear LastYear # Name # 0 1990 2007 # 1 2001 2001 # 2 2001 2008 </code></pre>
0
2016-10-15T12:45:36Z
[ "python", "csv", "pandas" ]
Pythn count multiple values in dictionary of list
40,058,134
<p>I have been trying to count the values in a dictionary with respect to the key. However, I could not achieved desired result. I will demonstrate with more details below:</p> <pre><code>from collections import Counter d = {'a': ['Adam','Adam','John'], 'b': ['John','John','Joel'], 'c': ['Adam','Adam','John} # create a list of only the values you want to count, # and pass to Counter() c = Counter([values[1] for values in d.itervalues()]) print c </code></pre> <p>My output:</p> <pre><code>Counter({'Adam': 2, 'John': 1}) </code></pre> <p>I want it to count everything in the list, not just first value of the list. Also, I want my result to be with respect to the key. I will show you my desired output below:</p> <pre><code>{'a': [{'Adam': 1, 'John': 2}, 'b':{'John': 2, 'Joel': 1}, 'c':{'Adam': 2, 'John': 1 }]} </code></pre> <p>Is it possible to get this desired output? Or anything close to it? I would like to welcome any suggestions or ideas that you have. Thank you.</p>
0
2016-10-15T10:53:55Z
40,058,177
<p>Try this using <code>dict comprehension</code></p> <pre><code>from collections import Counter d = {'a': ['Adam','Adam','John'], 'b': ['John','John','Joel'], 'c': ['Adam','Adam','John'} c = {i:Counter(j) for i,j in d.items()} print c </code></pre>
0
2016-10-15T10:58:54Z
[ "python", "list", "dictionary", "counter" ]
Pythn count multiple values in dictionary of list
40,058,134
<p>I have been trying to count the values in a dictionary with respect to the key. However, I could not achieved desired result. I will demonstrate with more details below:</p> <pre><code>from collections import Counter d = {'a': ['Adam','Adam','John'], 'b': ['John','John','Joel'], 'c': ['Adam','Adam','John} # create a list of only the values you want to count, # and pass to Counter() c = Counter([values[1] for values in d.itervalues()]) print c </code></pre> <p>My output:</p> <pre><code>Counter({'Adam': 2, 'John': 1}) </code></pre> <p>I want it to count everything in the list, not just first value of the list. Also, I want my result to be with respect to the key. I will show you my desired output below:</p> <pre><code>{'a': [{'Adam': 1, 'John': 2}, 'b':{'John': 2, 'Joel': 1}, 'c':{'Adam': 2, 'John': 1 }]} </code></pre> <p>Is it possible to get this desired output? Or anything close to it? I would like to welcome any suggestions or ideas that you have. Thank you.</p>
0
2016-10-15T10:53:55Z
40,058,190
<p>You're picking only the first elements in the each list with <code>values[1]</code>, instead, you want to iterate through each values using a <code>for</code> that follows the first:</p> <pre><code>&gt;&gt;&gt; from collections import Counter &gt;&gt;&gt; d = {'a': ['Adam','Adam','John'], 'b': ['John','John','Joel'], 'c': ['Adam','Adam','John']} &gt;&gt;&gt; Counter([v for values in d.itervalues() for v in values]) # iterate through each value Counter({'John': 4, 'Adam': 4, 'Joel': 1}) </code></pre>
1
2016-10-15T10:59:35Z
[ "python", "list", "dictionary", "counter" ]
Handling multiple variables in python
40,058,143
<p>Here's issue I am learning python newly i want to use loop for generating inputs from user which are then operated for some custom function (say Lcm or squaring them and returning ) so how to perform code Consider </p> <pre><code>k,l=0,0 while l&gt;=10: n_k=input("Enter") k=k+1 l=l+1 #Do something within for loop #here problem begins #lets say i am dividing each variable by c which is here in for loop for c in range(somevalue,0,-1): </code></pre> <p>now how should i operate the variables clearly i have no intention writting n_0%c ,n_1%c etc <br><b>Any Help???</b></p>
-2
2016-10-15T10:55:03Z
40,058,375
<p>Instead of n_k being a single variable i think you want n to be a <a href="https://docs.python.org/2/tutorial/datastructures.html" rel="nofollow">list</a>. A list is just a bunch of variables stored together. For example the code:</p> <pre><code>n = [1, 4, 2] print(n[0]) #0th element of the list print(n[1]) #1st element of the list print(n[2]) #2nd element of the list </code></pre> <p>outputs </p> <p>1<br> 4<br> 2<br></p> <p>the line n = [1, 4, 2] is just defining the list. The elements of the list are accessed using the n[index] notation.</p> <p>In python you can also add elements to a list at any time using the append statement. To illustrate let's define an empty list and add some elements to it.</p> <pre><code>n = [] n.append(8) </code></pre> <p>Now if we try </p> <pre><code>print(n[0]) </code></pre> <p>the code will print 8.</p> <p>So let's say we wanted to square a list of numbers we receive from user input, we would write</p> <pre><code>n = [] k = 0 num_inputs = 10 while k &lt; num_inputs: n.append(input("Enter:")) k = k + 1 k = 0 while k &lt; num_inputs: print(n[k] * n[k]) k = k + 1 </code></pre> <p>Hope it helps.</p>
0
2016-10-15T11:20:01Z
[ "python", "python-2.7", "loops", "variables", "for-loop" ]
How can I play MIDI tracks created using python-midi package?
40,058,310
<p>I want to create MIDI tracks in a Python program and be able to play them instantly (preferably without writing to disk). I have recently discovered the package <a href="https://github.com/vishnubob/python-midi" rel="nofollow">python-midi</a> which looks great. However I haven't figured out how to play the tracks created with this package. Do I need an additional package? Help would be appreciated.</p>
0
2016-10-15T11:12:41Z
40,059,738
<p>My solution if anyone is interested:</p> <p>I ended up using <a href="https://github.com/olemb/mido" rel="nofollow">mido</a> for my Python MIDI API, with Pygame as the backend. Works like a charm :)</p>
0
2016-10-15T13:41:56Z
[ "python", "api", "midi" ]
Matplotlib logarithmic x-axis and padding
40,058,391
<p>I am struggling with matplotlib and padding on the x-axis together with a logarithmic scale (see the first picture). Without a logarithmic scale, the padding applies nicely (see the second one). Any suggestations how to get a padding between plot lines and the axis line in the bottom left corner so that one can see the points on the line?</p> <p>Thanks.</p> <p>The code:</p> <pre><code>import matplotlib.pyplot as plt import numpy as np from matplotlib.pyplot import * from matplotlib.ticker import ScalarFormatter style.use('fivethirtyeight') fig, ax = plt.subplots() T = np.array([2**x for x in range(0,7+1)]) opt1 = np.array([x for x in range(0,7+1)]) opt2 = np.array([x*2 for x in range(0,7+1)]) opt3 = np.array([x*4 for x in range(0,7+1)]) ax.grid(True) xlabel("#nodes") ylabel("time(s)") legend(loc="best") title(r"Node start times") plt.xticks([2**x for x in range(0,7+1)]) plt.plot(T,opt1,"o-", label="opt1") plt.plot(T,opt2, "s-", label="opt2") plt.plot(T,opt3, "d-", label="opt2") plt.legend(loc="upper left") # This should be called after all axes have been added plt.tight_layout() plt.margins(0.05, 0.05) # 1, 2, 4, ... ax.set_xscale('log', basex=2) ax.xaxis.set_major_formatter(matplotlib.ticker.FormatStrFormatter("%d")) plt.show() #savefig("plot_1.pdf") </code></pre> <p><a href="https://i.stack.imgur.com/UoHFO.png" rel="nofollow"><img src="https://i.stack.imgur.com/UoHFO.png" alt="Plot Log Scale"></a> <a href="https://i.stack.imgur.com/69RP7.png" rel="nofollow"><img src="https://i.stack.imgur.com/69RP7.png" alt="Plot Normal"></a></p>
0
2016-10-15T11:21:23Z
40,058,832
<p>This does not address your padding issue, but you could use <code>clip_on=False</code> to prevent the points from being cut off. It seems you also need to make sure they're above the axes using <code>zorder</code></p> <pre><code>plt.plot(T,opt1,"o-", label="opt1", clip_on=False, zorder=10) plt.plot(T,opt2, "s-", label="opt2", clip_on=False, zorder=10) plt.plot(T,opt3, "d-", label="opt2", clip_on=False, zorder=10) </code></pre>
0
2016-10-15T12:08:05Z
[ "python", "matplotlib", "padding" ]
Python: count frequency of words from a column and store the results into another column on my data frame
40,058,436
<p>I want to count the number of each word that appears in each row of one column ('Comment') and store in a new column ('word') on my data frame called headlamp. I'm trying with the following down code, however, I get and error.</p> <pre><code>for i in range(0,len(headlamp)): headlamp['word'].apply(lambda text: Counter(" ".join(headlamp['Comment'][i].astype(str)).split(" ")).items()) --------------------------------------------------------------------------- KeyError Traceback (most recent call last) &lt;ipython-input-16-a0c20291b4f5&gt; in &lt;module&gt;() 1 for i in range(0,len(headlamp)): ----&gt; 2 headlamp['word'].apply(lambda text: Counter("".join(headlamp['Comment'][i].astype(str)).split(" ")).items()) C:\Users\Rafael\Anaconda2\envs\gl-env\lib\site-packages\pandas\core\frame.pyc in __getitem__(self, key) 1995 return self._getitem_multilevel(key) 1996 else: -&gt; 1997 return self._getitem_column(key) 1998 1999 def _getitem_column(self, key): C:\Users\Rafael\Anaconda2\envs\gl-env\lib\site-packages\pandas\core\frame.pyc in _getitem_column(self, key) 2002 # get column 2003 if self.columns.is_unique: -&gt; 2004 return self._get_item_cache(key) 2005 2006 # duplicate columns &amp; possible reduce dimensionality C:\Users\Rafael\Anaconda2\envs\gl-env\lib\site-packages\pandas\core\generic.pyc in _get_item_cache(self, item) 1348 res = cache.get(item) 1349 if res is None: -&gt; 1350 values = self._data.get(item) 1351 res = self._box_item_values(item, values) 1352 cache[item] = res C:\Users\Rafael\Anaconda2\envs\gl-env\lib\site-packages\pandas\core\internals.pyc in get(self, item, fastpath) 3288 3289 if not isnull(item): -&gt; 3290 loc = self.items.get_loc(item) 3291 else: 3292 indexer = np.arange(len(self.items))[isnull(self.items)] C:\Users\Rafael\Anaconda2\envs\gl-env\lib\site-packages\pandas\indexes\base.pyc in get_loc(self, key, method, tolerance) 1945 return self._engine.get_loc(key) 1946 except KeyError: -&gt; 1947 returnself._engine.get_loc(self._maybe_cast_indexer(key)) 1948 1949 indexer = self.get_indexer([key], method=method, tolerance=tolerance) pandas\index.pyx in pandas.index.IndexEngine.get_loc (pandas\index.c:4154)() pandas\index.pyx in pandas.index.IndexEngine.get_loc (pandas\index.c:4018)() pandas\hashtable.pyx in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:12368)() pandas\hashtable.pyx in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:12322)() KeyError: 'word' </code></pre> <p>Any help will be highly appreciate</p>
1
2016-10-15T11:26:51Z
40,059,993
<p>You can try this:</p> <pre><code>headlamp['word'] = headlamp['Comment'].apply(lambda x: len(x.split())) </code></pre> <p><strong>Example:</strong></p> <pre><code>headlamp = pd.DataFrame({'Comment': ['hello world','world','foo','foo and bar']}) print(headlamp) Comment 0 hello world 1 world 2 foo 3 foo and bar headlamp['word'] = headlamp['Comment'].apply(lambda x: len(x.split())) print(headlamp) Comment word 0 hello world 2 1 world 1 2 foo 1 3 foo and bar 3 </code></pre>
0
2016-10-15T14:06:32Z
[ "python", "pandas", "count", "counter", "frame" ]
Python: count frequency of words from a column and store the results into another column on my data frame
40,058,436
<p>I want to count the number of each word that appears in each row of one column ('Comment') and store in a new column ('word') on my data frame called headlamp. I'm trying with the following down code, however, I get and error.</p> <pre><code>for i in range(0,len(headlamp)): headlamp['word'].apply(lambda text: Counter(" ".join(headlamp['Comment'][i].astype(str)).split(" ")).items()) --------------------------------------------------------------------------- KeyError Traceback (most recent call last) &lt;ipython-input-16-a0c20291b4f5&gt; in &lt;module&gt;() 1 for i in range(0,len(headlamp)): ----&gt; 2 headlamp['word'].apply(lambda text: Counter("".join(headlamp['Comment'][i].astype(str)).split(" ")).items()) C:\Users\Rafael\Anaconda2\envs\gl-env\lib\site-packages\pandas\core\frame.pyc in __getitem__(self, key) 1995 return self._getitem_multilevel(key) 1996 else: -&gt; 1997 return self._getitem_column(key) 1998 1999 def _getitem_column(self, key): C:\Users\Rafael\Anaconda2\envs\gl-env\lib\site-packages\pandas\core\frame.pyc in _getitem_column(self, key) 2002 # get column 2003 if self.columns.is_unique: -&gt; 2004 return self._get_item_cache(key) 2005 2006 # duplicate columns &amp; possible reduce dimensionality C:\Users\Rafael\Anaconda2\envs\gl-env\lib\site-packages\pandas\core\generic.pyc in _get_item_cache(self, item) 1348 res = cache.get(item) 1349 if res is None: -&gt; 1350 values = self._data.get(item) 1351 res = self._box_item_values(item, values) 1352 cache[item] = res C:\Users\Rafael\Anaconda2\envs\gl-env\lib\site-packages\pandas\core\internals.pyc in get(self, item, fastpath) 3288 3289 if not isnull(item): -&gt; 3290 loc = self.items.get_loc(item) 3291 else: 3292 indexer = np.arange(len(self.items))[isnull(self.items)] C:\Users\Rafael\Anaconda2\envs\gl-env\lib\site-packages\pandas\indexes\base.pyc in get_loc(self, key, method, tolerance) 1945 return self._engine.get_loc(key) 1946 except KeyError: -&gt; 1947 returnself._engine.get_loc(self._maybe_cast_indexer(key)) 1948 1949 indexer = self.get_indexer([key], method=method, tolerance=tolerance) pandas\index.pyx in pandas.index.IndexEngine.get_loc (pandas\index.c:4154)() pandas\index.pyx in pandas.index.IndexEngine.get_loc (pandas\index.c:4018)() pandas\hashtable.pyx in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:12368)() pandas\hashtable.pyx in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:12322)() KeyError: 'word' </code></pre> <p>Any help will be highly appreciate</p>
1
2016-10-15T11:26:51Z
40,060,060
<p>Using the <a href="https://docs.python.org/2/library/collections.html#collections.Counter.most_common" rel="nofollow">most_common()</a> method you can achieve what you want.</p> <p>Feel free to use this piece of code:</p> <pre><code>import pandas as pd from collections import Counter df = pd.DataFrame({'Comment': ['This has has words words words that are written twice twice', 'This is a comment without repetitions', 'This comment, has ponctuations!']}, index = [0, 1, 2]) #you must create the new column before trying to assing any value df['Words'] = "" #counting frequencies i = 0 for row in df['Comment']: df['Words'][i] = str(Counter(row.split()).most_common()) i+=1 print df </code></pre> <p>Output:</p> <pre><code> Comment \ 0 This has has words words words that are writte... 1 This is a comment without repetitions 2 This comment, has ponctuations! Words 0 [('words', 3), ('twice', 2), ('has', 2), ('tha... 1 [('a', 1), ('comment', 1), ('This', 1), ('is',... 2 [('This', 1), ('comment,', 1), ('has', 1), ('p... </code></pre>
0
2016-10-15T14:11:50Z
[ "python", "pandas", "count", "counter", "frame" ]
python error: local variable 'a' referenced before assignment
40,058,439
<p>I'm trying to create a function with an interactive input to tell you what the 'SMILES' formula is for a fatty acid (chemical compound) but I keep getting this error:</p> <pre><code>def fatty_gen(chain_length, db_position, db_orientation): "Returns the SMILES code of the fatty acid, given its chain length, db position, db orientation" chain_length=input("What is the chain length/number of C?") chain_length2=int(chain_length) db_position = input("On which carbon does the double bond first appear") db_position2=int(db_position) db_orientation= input("What is the orientation of the double bond") db_orientation2=str(db_orientation) if db_orientation2 =="Z": a="/C=C\\" elif db_orientation2=="E": a="\C=C\\" else: a ="" return "C"*((db_position2)-1) + a + "C"*(chain_length2-db_position2-1) &lt;ipython-input-2-20b88ae22368&gt; in fatty_gen(chain_length, db_position, db_orientation) 13 a="\C=C\\" 14 ---&gt; 15 return "C"*((db_position2)-1) + a + "C"*(chain_length2-db_position2-1) 16 fatty_gen(1,1,1) UnboundLocalError: local variable 'a' referenced before assignment </code></pre> <p>UnboundLocalError: local variable 'a' referenced before assignment</p>
-1
2016-10-15T11:26:56Z
40,058,486
<p>If <code>db_orientation2</code> is neither <code>"Z"</code> nor <code>"E"</code> <code>a</code> variable is not defined.</p> <p>You need to add <code>else</code> clause like this:</p> <pre><code>if db_orientation2 == "Z": a = "/C=C\\" elif db_orientation2 == "E": a = "\C=C\\" else: a = "something else" </code></pre>
1
2016-10-15T11:31:56Z
[ "python" ]
python error: local variable 'a' referenced before assignment
40,058,439
<p>I'm trying to create a function with an interactive input to tell you what the 'SMILES' formula is for a fatty acid (chemical compound) but I keep getting this error:</p> <pre><code>def fatty_gen(chain_length, db_position, db_orientation): "Returns the SMILES code of the fatty acid, given its chain length, db position, db orientation" chain_length=input("What is the chain length/number of C?") chain_length2=int(chain_length) db_position = input("On which carbon does the double bond first appear") db_position2=int(db_position) db_orientation= input("What is the orientation of the double bond") db_orientation2=str(db_orientation) if db_orientation2 =="Z": a="/C=C\\" elif db_orientation2=="E": a="\C=C\\" else: a ="" return "C"*((db_position2)-1) + a + "C"*(chain_length2-db_position2-1) &lt;ipython-input-2-20b88ae22368&gt; in fatty_gen(chain_length, db_position, db_orientation) 13 a="\C=C\\" 14 ---&gt; 15 return "C"*((db_position2)-1) + a + "C"*(chain_length2-db_position2-1) 16 fatty_gen(1,1,1) UnboundLocalError: local variable 'a' referenced before assignment </code></pre> <p>UnboundLocalError: local variable 'a' referenced before assignment</p>
-1
2016-10-15T11:26:56Z
40,058,814
<pre><code>if db_orientation2 =="Z": a="/C=C\\" elif db_orientation2=="E": a="\C=C\\" elif db_orientation2=="": a="/C=C\\" else: a="" </code></pre> <p>Anyone know why the backslashes are appearing twice, despite it supposed to be understood as just one backslash?</p>
0
2016-10-15T12:06:34Z
[ "python" ]
How to select element locations from two Pandas dataframes of identical shape, where the values match within a certain range?
40,058,441
<p>How to select element locations from two Pandas dataframes of identical shape, where the values match within a certain range? A code to do this might be simple to write, but I want to know if there is a smart way to make this conditional selection (like loc) with Pandas data frames as I will need it for large image files and I believe Pandas is generally quick and efficient. </p>
0
2016-10-15T11:27:07Z
40,058,958
<p>I need more information about </p> <blockquote> <p>he values match within a certain range</p> </blockquote> <p>But this is an example selecting values that are the same in the two <code>DataFrame</code>. By replacing the test by any other test, you could reach your goals.</p> <pre><code># Test data df1 = DataFrame({'col1':[1.2, 3.2, 4.2], 'col2':[0, 2.1, 4.8], 'col3': [2.0, 0, 8.2]}) df2 = DataFrame({'col1':[2.2, 3.2, 4.2], 'col2':[4.1, 0, 4.8], 'col3': [2.0, 4.7, 8.2]}) # df1 # col1 col2 col3 # 0 1.2 0.0 2.0 # 1 3.2 2.1 0.0 # 2 4.2 4.8 8.2 # df2 # col1 col2 col3 # 0 2.2 4.1 2.0 # 1 3.2 0.0 4.7 # 2 4.2 4.8 8.2 # Assuming the two DataFrame have the same index and columns you can simply do that df2[df2 == df1] # col1 col2 col3 # 0 NaN NaN 2.0 # 1 3.2 NaN NaN # 2 4.2 4.8 8.2 </code></pre>
0
2016-10-15T12:21:12Z
[ "python", "pandas", "dataframe" ]
How can i write this without using the if statment
40,058,467
<pre><code>def in_puzzle_horizontal(puzzle, word): left_right = lr_occurrences(puzzle, word) right_left = lr_occurrences((rotate_puzzle(rotate_puzzle(puzzle))), word) total = left_right or right_left if total &gt; 0: return True else: return False </code></pre>
-1
2016-10-15T11:30:08Z
40,058,492
<p>You only have to replace the if statement by:</p> <pre><code>return total &gt; 0 </code></pre>
6
2016-10-15T11:32:40Z
[ "python", "if-statement" ]
How can i write this without using the if statment
40,058,467
<pre><code>def in_puzzle_horizontal(puzzle, word): left_right = lr_occurrences(puzzle, word) right_left = lr_occurrences((rotate_puzzle(rotate_puzzle(puzzle))), word) total = left_right or right_left if total &gt; 0: return True else: return False </code></pre>
-1
2016-10-15T11:30:08Z
40,058,508
<pre><code>left_right = lr_occurrences(puzzle, word) right_left = lr_occurrences((rotate_puzzle(rotate_puzzle(puzzle))), word) total = left_right or right_left return total &gt; 0 </code></pre>
1
2016-10-15T11:33:56Z
[ "python", "if-statement" ]
Python Unhandled Error Traceback (most recent call last):
40,058,474
<p>This is my code, I was looking for answers but none resolve my problem. I'm new to Twisted and still learning.</p> <p>Why do I get this error after I run <code>telnet localhost 72</code> in the Windows command prompt? </p> <p>This is my code:</p> <pre><code>from twisted.internet.protocol import Factory from twisted.protocols.basic import LineReceiver from twisted.internet import reactor class chatprotocol(LineReceiver): def __init__(self, factory): self.factory = factory self.name = None self.state = "REGiSTER" def connectionMade(self): self.sendLine("What's your Name?") def connectionLost(self, reason): if self.name in self.factory.users: del self.factory.Users[self.name] self.broadcastMessage("%s has left channel." % (self.name,)) def lineReceived(self, line): if self.state == "REGISTER": self.handle_REGISTER(line) else: self.handle_CHAT(line) def handle_REGISTER(self, name): if name in self.factory.users: self.sendLine("Name taken , please choose another") return self.sendline("welcome ,%s!" % (name,)) self.broadcastMessage("%s has joined the channel." % (name,)) self.name = name self.factory.users[name] = self self.state = "CHAT" def handle_CHAT(self, message): message = "&lt;%s&gt; %s" % (self.name, message) self.broadcastMessage(message) def broadcastMessage(self, message): for name, protocol in self.factory.users.iteritems(): if protocol != self: protocol.sendLine(message) class ChatFactory(Factory): def __init__(self): self.users = {} def buildProtocol(self, addr): return chatprotocol(self) reactor.listenTCP(72, ChatFactory()) reactor.run() </code></pre> <p>the error message:</p> <pre><code>Unhandled Error Traceback (most recent call last): File "C:\Python27\lib\site-packages\twisted\python\log.py", line 84, in callWithContext return context.call({ILogContext: newCtx}, func, *args, **kw) File "C:\Python27\lib\site-packages\twisted\python\context.py", line 118, in callWithContext return self.currentContext().callWithContext(ctx, func, *args, **kw) File "C:\Python27\lib\site-packages\twisted\python\context.py", line 81, in callWithContext return func(*args,**kw) File "C:\Python27\lib\site-packages\twisted\internet\selectreactor.py", line 149, in _doReadOrWrite why = getattr(selectable, method)() --- &lt;exception caught here&gt; --- File "C:\Python27\lib\site-packages\twisted\internet\tcp.py", line 1066, in doRead protocol = self.factory.buildProtocol(self._buildAddr(addr)) File "C:\Python27\lib\site-packages\twisted\internet\protocol.py", line 131, in buildProtocol p = self.protocol() exceptions.TypeError: 'NoneType' object is not callable </code></pre>
0
2016-10-15T11:30:43Z
40,077,577
<p>@firman Are you sure you're giving us the EXACT code that's causing issues? The code above (if it were written properly) cannot possibly give that error. The error occurs in the <code>buildProtocol</code> function of the <code>Factory</code> class, which you overloaded in your example. I've edited your question and corrected some syntax errors. Try it again and see if it works. If not then post your code that's giving you errors.</p> <p>The error you got is caused when you don't set the <code>protocol</code> variable in your factory object and it remains <code>None</code>. For example, let's comment out the <code>buildProtocol</code> function in your factory class so that it looks like this:</p> <pre><code>class ChatFactory(Factory): def __init__(self): self.users = {} # def buildProtocol(self, addr): # return chatprotocol(self) </code></pre> <p>I get the error you originally got:</p> <pre><code>--- &lt;exception caught here&gt; --- File "/Projects/virtenv/local/lib/python2.7/site-packages/twisted/internet/tcp.py", line 1066, in doRead protocol = self.factory.buildProtocol(self._buildAddr(addr)) File "/Projects/virtenv/local/lib/python2.7/site-packages/twisted/internet/protocol.py", line 131, in buildProtocol p = self.protocol() exceptions.TypeError: 'NoneType' object is not callable </code></pre> <p>To fix this issue, you can do 1 of 2 things. You can overload <code>buildProtocol()</code> to return the protocol object you want (you did this in your original example). Or you can set the factory object to a variable, then set the <code>protocol</code> class variable. So your main method should look like:</p> <pre><code>factory = ChatFactory() factory.protocol = chatprotocol reactor.listenTCP(72, factory) </code></pre>
0
2016-10-17T02:15:02Z
[ "python", "twisted" ]
Different Color Result Between Python OpenCV and MATLAB
40,058,686
<p>I'm going to convert RGB image to YIQ image and viceversa. The problem is Python give me a weird image, while MATLAB shows the right one. I spent hours to figure what's wrong, but i still have no idea.</p> <p>I use Python 3.5.2 with OpenCV 3.1.0 and MATLAB R2016a.</p> <p>Python code for RGB2YIQ:</p> <pre><code>import cv2 as cv import numpy as np def rgb2yiq(img): row, col, ch = img.shape Y = np.zeros((row,col)) I = np.zeros((row,col)) Q = np.zeros((row,col)) for i in range(row): for j in range(col): Y[i,j] = 0.299 * img[i,j,2] + 0.587 * img[i,j,1] + 0.114 * img[i,j,0] I[i,j] = 0.596 * img[i,j,2] - 0.274 * img[i,j,1] - 0.322 * img[i,j,0] Q[i,j] = 0.211 * img[i,j,2] - 0.523 * img[i,j,1] + 0.312 * img[i,j,0] yiq = cv.merge((Y,I,Q)) return yiq.astype(np.uint8) def main(): img = cv.imread("C:/Users/Kadek/Documents/MATLAB/peppers.jpg") img = rgb2yiq(img) cv.imwrite("YIQ.jpg",img) cv.namedWindow('Image', cv.WINDOW_NORMAL) cv.imshow('Image', img) cv.waitKey(0) cv.destroyAllWindows() main() </code></pre> <p>MATLAB code for RGB2YIQ:</p> <pre><code>img = imread('peppers.jpg'); [row col ch] = size(img); for x=1:row for y=1:col Y(x,y) = 0.299 * img(x,y,1) + 0.587 * img(x,y,2) + 0.114 * img(x,y,3); I(x,y) = 0.596 * img(x,y,1) - 0.274 * img(x,y,2) - 0.322 * img(x,y,3); Q(x,y) = 0.211 * img(x,y,1) - 0.523 * img(x,y,2) + 0.312 * img(x,y,3); end end yiq(:,:,1) = Y; yiq(:,:,2) = I; yiq(:,:,3) = Q; figure, imshow(yiq); </code></pre> <p><a href="http://image.prntscr.com/image/1d6348dcac804642a5a47f5a03d6da08.jpg" rel="nofollow">Result for RGB2YIQ</a></p> <p>Python code for YIQ2RGB:</p> <pre><code>import cv2 as cv import numpy as np def yiq2rgb(img): row, col, ch = img.shape r = np.zeros((row,col)) g = np.zeros((row,col)) b = np.zeros((row,col)) for i in range(row): for j in range(col): r[i,j] = img[i,j,0] * 1.0 + img[i,j,1] * 0.9562 + img[i,j,2] * 0.6214 g[i,j] = img[i,j,0] * 1.0 - img[i,j,1] * 0.2727 - img[i,j,2] * 0.6468 b[i,j] = img[i,j,0] * 1.0 - img[i,j,1] * 1.1037 + img[i,j,2] * 1.7006 rgb = cv.merge((b,g,r)) return rgb.astype(np.uint8) def main(): img = cv.imread("YIQ.jpg") img = yiq2rgb(img) cv.imwrite("test.jpg",img) cv.namedWindow('Image', cv.WINDOW_NORMAL) cv.imshow('Image', img) cv.waitKey(0) cv.destroyAllWindows() main() </code></pre> <p>MATLAB code for YIQ2RGB:</p> <pre><code>img = imread('YIQ.jpg'); [row col ch] = size(img); for x=1:row for y=1:col R(x,y) = 1.0 * img(x,y,1) + 0.9562 * img(x,y,2) + 0.6214 * img(x,y,3); G(x,y) = 1.0 * img(x,y,1) - 0.2727 * img(x,y,2) - 0.6468 * img(x,y,3); B(x,y) = 1.0 * img(x,y,1) - 1.1037 * img(x,y,2) + 1.7006 * img(x,y,3); end end rgb(:,:,1) = R; rgb(:,:,2) = G; rgb(:,:,3) = B; imwrite(rgb,'YIQ2RGB.jpg'); figure, imshow(rgb); </code></pre> <p><a href="http://image.prntscr.com/image/3dfff94420c0426093162fad4451ad76.jpg" rel="nofollow">Result for YIQ2RGB</a></p> <p>Some said that i used to convert the image to float64 before manipulates it. Already tried that, but nothing changed. I also used astype(np.uint8) to convert float64 to uint8 to avoid values outside [0..255]. In MATLAB there is no such problem.</p>
3
2016-10-15T11:52:36Z
40,060,066
<p>You obviously face a saturation problem, due to some computed component exceeding the range [0,255]. Clamp the values or adjust the gain.</p> <p>Then there seems to be a swapping of the components somewhere.</p>
0
2016-10-15T14:12:45Z
[ "python", "matlab", "opencv", "image-processing", "ipython" ]
Select hidden option value from source using python selenium chromedriver
40,058,697
<p>I am reading a Docx file [here is the <a href="https://www.dropbox.com/s/3za9qhzupc01azt/Taxatierapport%20SEK%20-%20Auto%20Centrum%20Bollenstreek%20-%20Peugeot%20308%20-%205603.docx?dl=0" rel="nofollow">link] </a>, parsing some text from that &amp; then Using python selenium bindings &amp; chrome-driver I am trying to click a Hidden option value from source (driver.page_source) . I know it isn't available to select. Here is my code so far :</p> <pre><code>import time, re from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from docx import opendocx, getdocumenttext from requests import Session def read_return(word_file): document = opendocx(word_file) paratextlist = getdocumenttext(document) newparatextlist = [] for paratext in paratextlist: newparatextlist.append((paratext.encode("utf-8")).strip('\n').strip('\t').strip('\r')) newparatextlist = str(newparatextlist).replace("]","").replace("[","") with open('sample.txt','wb')as writer: writer.write(newparatextlist) return newparatextlist word_file = read_return('Taxatierapport SEK - Auto Centrum Bollenstreek - Peugeot 308 - 5603.docx') x = lambda x:re.findall(x,word_file,re.DOTALL)[0].strip().replace("'","&amp;#39;").replace('"','&amp;#39;') Voertuig = x("::OBJECT::', '(.+?)'") Merk = x("::MERK::', '(.+?)'") Model = x("::TYPE::', '(.+?)'") TOELATING = x("::BOUWJAAR 1STE TOELATING::', '(.+?)'") d1 = TOELATING.split("-")[0] d2 = TOELATING.split("-")[1] d3 = TOELATING.split("-")[2] TRANSMISSIE = x("::TRANSMISSIE::', '(.+?)'") BRANDSTOF = x("::BRANDSTOF::', '(.+?)'") print "%r\n%r\n%r\n%r\n%r\n%r\n%r\n%r\n" %(Voertuig, Merk, Model, d1, d2, d3, TRANSMISSIE, BRANDSTOF) if Voertuig == "Personenauto": value = 1 elif Voertuig == "Personenbussen": value = 7 elif Voertuig == "Bedrijfsauto&amp;#39;s tot 3.5 ton": value = 3 elif Voertuig == "Bedrijfsauto&amp;#39;s 4x4": value = 2 elif Voertuig == "Motoren": value= 5 xr = 0; yr = 0; zr = 1972 while xr &lt; 32: if int(d1) == xr: dvalue1 = xr else: pass xr+=1 while yr &lt; 13: if int(d2) == yr: dvalue2 = yr else: pass yr+=1 while zr &lt; 2018: if int(d3) == zr: dvalue3 = zr else: pass zr+=1 driver = webdriver.Chrome('chromedriver.exe') driver.get('https://autotelexpro.nl/LoginPage.aspx') driver.find_element(By.XPATH, value ='//*[@id="ctl00_cp_LogOnView_LogOn_txtVestigingsnummer"]').send_keys('3783') driver.find_element(By.XPATH, value ='//*[@id="ctl00_cp_LogOnView_LogOn_txtGebruikersnaam"]').send_keys('Frank') driver.find_element(By.XPATH, value ='//*[@id="ctl00_cp_LogOnView_LogOn_Password"]').send_keys('msnauto2016') driver.find_element(By.XPATH, value ='//*[@id="ctl00_cp_LogOnView_LogOn_btnLogin"]').click() time.sleep(10) #try: driver.find_element(By.XPATH, value ='//select[@name="ctl00$cp$ucSearch_Manual$ddlVoertuigType"]/option[@value="'+str(value)+'"]').click() driver.find_element(By.XPATH, value ='//select[@name="ctl00$cp$ucSearch_Manual$ddlBouwdag"]/option[@value="'+str(dvalue1)+'"]').click() driver.find_element(By.XPATH, value ='//select[@name="ctl00$cp$ucSearch_Manual$ddlBouwmaand"]/option[@value="'+str(dvalue2)+'"]').click() driver.find_element(By.XPATH, value ='//select[@name="ctl00$cp$ucSearch_Manual$ddlBouwjaar"]/option[@value="'+str(dvalue3)+'"]').click() driver.find_element(By.XPATH, value ='//select[@name="ctl00$cp$ucSearch_Manual$ddlMerk"]/option[@value="130"]').click() #except: driver.quit() time.sleep(5) driver.quit() </code></pre> <p>so Using requests module i make a POST request to the link &amp; manage to get a response that does have the needed options data , See here : </p> <pre><code>&lt;select name="ctl00$cp$ucSearch_Manual$ddlMerk" onchange="updateInputForServerNoPB();InvalidateVehicleSearchResult();setTimeout(&amp;#39;__doPostBack(\&amp;#39;ctl00$cp$ucSearch_Manual$ddlMerk\&amp;#39;,\&amp;#39;\&amp;#39;)&amp;#39;, 0)" id="ctl00_cp_ucSearch_Manual_ddlMerk" class="NormalDropdownlist" style="width:174px;"&gt; &lt;option selected="selected" value="-1"&gt;- Kies merk -&lt;/option&gt; &lt;option value="95"&gt;Alfa Romeo&lt;/option&gt; &lt;option value="154"&gt;Aston Martin&lt;/option&gt; &lt;option value="96"&gt;Audi&lt;/option&gt; &lt;option value="97"&gt;Bentley&lt;/option&gt; &lt;option value="98"&gt;BMW&lt;/option&gt; &lt;option value="352"&gt;Bugatti&lt;/option&gt; &lt;option value="100"&gt;Cadillac&lt;/option&gt; &lt;option value="342"&gt;Chevrolet&lt;/option&gt; &lt;option value="101"&gt;Chevrolet USA&lt;/option&gt; &lt;option value="102"&gt;Chrysler&lt;/option&gt; &lt;option value="103"&gt;Citroen&lt;/option&gt; &lt;option value="337"&gt;Corvette&lt;/option&gt; &lt;option value="104"&gt;Dacia&lt;/option&gt; &lt;option value="105"&gt;Daihatsu&lt;/option&gt; &lt;option value="166"&gt;Daimler&lt;/option&gt; &lt;option value="162"&gt;Dodge&lt;/option&gt; &lt;option value="106"&gt;Donkervoort&lt;/option&gt; &lt;option value="107"&gt;Ferrari&lt;/option&gt; &lt;option value="108"&gt;Fiat&lt;/option&gt; &lt;option value="94"&gt;Ford&lt;/option&gt; &lt;option value="111"&gt;Honda&lt;/option&gt; &lt;option value="340"&gt;Hummer&lt;/option&gt; &lt;option value="112"&gt;Hyundai&lt;/option&gt; &lt;option value="365"&gt;Infiniti&lt;/option&gt; &lt;option value="113"&gt;Jaguar&lt;/option&gt; &lt;option value="114"&gt;Jeep&lt;/option&gt; &lt;option value="150"&gt;Kia&lt;/option&gt; &lt;option value="115"&gt;Lada&lt;/option&gt; &lt;option value="116"&gt;Lamborghini&lt;/option&gt; &lt;option value="117"&gt;Lancia&lt;/option&gt; &lt;option value="168"&gt;Land Rover&lt;/option&gt; &lt;option value="432"&gt;Landwind&lt;/option&gt; &lt;option value="118"&gt;Lexus&lt;/option&gt; &lt;option value="119"&gt;Lotus&lt;/option&gt; &lt;option value="120"&gt;Maserati&lt;/option&gt; &lt;option value="330"&gt;Maybach&lt;/option&gt; &lt;option value="121"&gt;Mazda&lt;/option&gt; &lt;option value="122"&gt;Mercedes-Benz&lt;/option&gt; &lt;option value="304"&gt;Mini&lt;/option&gt; &lt;option value="124"&gt;Mitsubishi&lt;/option&gt; &lt;option value="126"&gt;Morgan&lt;/option&gt; &lt;option value="127"&gt;Nissan&lt;/option&gt; &lt;option value="128"&gt;Opel&lt;/option&gt; &lt;option value="130"&gt;Peugeot&lt;/option&gt; &lt;option value="132"&gt;Porsche&lt;/option&gt; &lt;option value="134"&gt;Renault&lt;/option&gt; &lt;option value="135"&gt;Rolls-Royce&lt;/option&gt; &lt;option value="138"&gt;Saab&lt;/option&gt; &lt;option value="139"&gt;Seat&lt;/option&gt; &lt;option value="140"&gt;Skoda&lt;/option&gt; &lt;option value="226"&gt;smart&lt;/option&gt; &lt;option value="343"&gt;Spyker&lt;/option&gt; &lt;option value="210"&gt;SsangYong&lt;/option&gt; &lt;option value="141"&gt;Subaru&lt;/option&gt; &lt;option value="142"&gt;Suzuki&lt;/option&gt; &lt;option value="417"&gt;Think&lt;/option&gt; &lt;option value="144"&gt;Toyota&lt;/option&gt; &lt;option value="147"&gt;Volkswagen&lt;/option&gt; &lt;option value="145"&gt;Volvo&lt;/option&gt; &lt;/select&gt; </code></pre> <p>, I am wondering is there anyway's i can add the above string text to <strong>driver.page_source</strong> , So that i can iterate over the options values using <strong>driver</strong> properties ?</p>
0
2016-10-15T11:53:46Z
40,061,817
<pre><code>from selenium import webdriver from selenium.webdriver.common.by import By import time from selenium.webdriver.support.ui import Select driver = webdriver.Chrome() driver.maximize_window() driver.get('https://autotelexpro.nl/LoginPage.aspx') driver.find_element(By.XPATH, value ='//*[@id="ctl00_cp_LogOnView_LogOn_txtVestigingsnummer"]').send_keys('3783') driver.find_element(By.XPATH, value ='//*[@id="ctl00_cp_LogOnView_LogOn_txtGebruikersnaam"]').send_keys('Frank') driver.find_element(By.XPATH, value ='//*[@id="ctl00_cp_LogOnView_LogOn_Password"]').send_keys('msnauto2016') driver.find_element(By.XPATH, value ='//*[@id="ctl00_cp_LogOnView_LogOn_btnLogin"]').click() time.sleep(10) currentselection = driver.find_element_by_xpath(".//*[@id='ctl00_cp_ucSearch_Manual_ddlVoertuigType']") select = Select(currentselection) select.select_by_visible_text("Motoren") time.sleep(5) try: x=driver.find_element_by_xpath(".//*[@id='ctl00_cp_ucSearch_Manual_ddlBouwdag']") select = Select(x) select.select_by_visible_text("1") y=driver.find_element_by_xpath(".//*[@id='ctl00_cp_ucSearch_Manual_ddlBouwmaand']") select = Select(y) select.select_by_visible_text("1") z=driver.find_element_by_xpath(".//*[@id='ctl00_cp_ucSearch_Manual_ddlBouwjaar']") select = Select(z) select.select_by_visible_text("2017") time.sleep(5) car = driver.find_element_by_css_selector("#ctl00_cp_ucSearch_Manual_ddlMerk") select = Select(car) select.select_by_visible_text("BTC") except: print "Not able to select" </code></pre> <p>this code will help. See better way is explicit wait but for temp solution i have used time.sleep()</p> <p>Update: If you want to get the option from car dropdown this is a method which can be used:</p> <pre><code>def getallcarlist(): currentselection = driver.find_element_by_xpath(".//*[@id='ctl00_cp_ucSearch_Manual_ddlVoertuigType']") select = Select(currentselection) select.select_by_visible_text("Motoren") time.sleep(5) x = driver.find_element_by_xpath(".//*[@id='ctl00_cp_ucSearch_Manual_ddlBouwdag']") select = Select(x) select.select_by_visible_text("1") y = driver.find_element_by_xpath(".//*[@id='ctl00_cp_ucSearch_Manual_ddlBouwmaand']") select = Select(y) select.select_by_visible_text("1") z = driver.find_element_by_xpath(".//*[@id='ctl00_cp_ucSearch_Manual_ddlBouwjaar']") select = Select(z) select.select_by_visible_text("2017") time.sleep(5) car = driver.find_element_by_css_selector("#ctl00_cp_ucSearch_Manual_ddlMerk") carlist =[] for option in car.find_elements_by_tag_name('option'): carlist.append((option.text).encode('utf8')) return carlist </code></pre> <p>this is way to call it </p> <pre><code>listcar= getallcarlist() for c in listcar: print c </code></pre> <p>the output will be:</p> <pre><code>- Kies merk - AGM AJP Aprilia Benelli Beta BMW BTC Bullit Derbi Ducati Energica Gilera Harley Davidson Hesketh Honda Husqvarna Hyosung Indian Kawasaki KTM Kymco Longjia Mash Morgan Mors Moto Guzzi MV Agusta Nimoto Ossa Peugeot Piaggio Quadro Razzo Renault Royal Enfield Sachs Scomadi Suzuki SWM SYM Triumph Turbho Vespa Victory Volta Motorbikes Yamaha Yiben Zero Motorcycles </code></pre>
0
2016-10-15T16:59:41Z
[ "python", "python-2.7", "selenium", "post", "selenium-chromedriver" ]
Using multiple cores with Python and Eventlet
40,058,748
<p>I have a Python web application in which the client (<a href="http://emberjs.com/" rel="nofollow">Ember.js</a>) communicates with the server via WebSocket (I am using <a href="https://flask-socketio.readthedocs.io/en/latest/" rel="nofollow">Flask-SocketIO</a>). Apart from the WebSocket server the backend does two more things that are worth to be mentioned:</p> <ul> <li>Doing some image conversion (using <a href="http://www.graphicsmagick.org/" rel="nofollow">graphicsmagick</a>)</li> <li>OCR incoming images from the client (using <a href="https://github.com/tesseract-ocr" rel="nofollow">tesseract</a>)</li> </ul> <p>When the client submits an image its entity is created in the database and the id is put in an image conversion queue. The worker grabs it and does image conversion. After that the worker puts it in the OCR queue where it will be handled by the OCR queue worker.</p> <p>So far so good. The WS requests are handled synchronously in separate threads (Flask-SocketIO uses Eventlet for that) and the heavy computational action happens asynchronously (in separate threads as well).</p> <p>Now the problem: the whole application runs on a <strong>Raspberry Pi 3</strong>. If I do not make use of the 4 cores it has I only have <strong>one ARMv8 core clocked at 1.2 GHz</strong>. This is very little power for OCR. So I decided to find out how to use multiple cores with Python. Although I read about the problems with the <a href="http://www.infoworld.com/article/3079037/open-source-tools/multicore-python-a-tough-worthy-and-reachable-goal.html" rel="nofollow">GIL</a>) I found out about <a href="https://docs.python.org/2/library/multiprocessing.html" rel="nofollow">multiprocessing</a> where it says <code>The multiprocessing package offers both local and remote concurrency, effectively side-stepping the Global Interpreter Lock by using subprocesses instead of threads.</code>. Exactly what I wanted. So I instantly replaced the </p> <pre><code>from threading import Thread thread = Thread(target=heavy_computational_worker_thread) thread.start() </code></pre> <p>by</p> <pre><code>from multiprocessing import Process process = Process(target=heavy_computational_worker_thread) process.start() </code></pre> <p>The queue needed to be handled by the multiple cores as well So i had to change</p> <pre><code>from queue import Queue queue = multiprocessing.Queue() </code></pre> <p>to</p> <pre><code>import multiprocessing queue = multiprocessing.Queue() </code></pre> <p>as well. Problematic: the queue and the Thread libraries are <a href="http://eventlet.net/doc/patching.html" rel="nofollow">monkey patched</a> by Eventlet. If I stop using the monkey patched version of Thread and Queue and use the one from <code>multiprocsssing</code> instead then the request thread started by Eventlet blocks forever when accessing the queue.</p> <p>Now my question:</p> <p><strong>Is there any way I can make this application do the OCR and image conversion on a separate core?</strong></p> <p>I would like to keep using WebSocket and Eventlet if that's possible. The advantage I have is that the only communication interface between the processes would be the queue. </p> <p>Ideas that I already had: - Not using a Python implementation of a queue but rather using I/O. For example a dedicated Redis which the different subprocesses would access - Going a step further: starting every queue worker as a separate Python process (e.g. python3 wsserver | python3 ocrqueue | python3 imgconvqueue). Then I would have to make sure myself that the access on the queue and on the database would be non-blocking</p> <p>The best thing would be to keep the single process and make it work with multiprocessing, though.</p> <p>Thank you very much in advance</p>
3
2016-10-15T11:59:36Z
40,066,117
<p>Eventlet is currently incompatible with the multiprocessing package. There is an open issue for this work: <a href="https://github.com/eventlet/eventlet/issues/210" rel="nofollow">https://github.com/eventlet/eventlet/issues/210</a>.</p> <p>The alternative that I think will work well in your case is to use Celery to manage your queue. Celery will start a pool of worker processes that wait for tasks provided by the main process via a message queue (RabbitMQ and Redis are both supported).</p> <p>The Celery workers do not need to use eventlet, only the main server does, so this frees them to do whatever they need to do without the limitations imposed by eventlet.</p> <p>If you are interested in exploring this approach, I have a complete example that uses it: <a href="https://github.com/miguelgrinberg/flack" rel="nofollow">https://github.com/miguelgrinberg/flack</a>.</p>
3
2016-10-16T02:07:05Z
[ "python", "multithreading", "multiprocessing", "eventlet", "flask-socketio" ]
Python Openpxyl query workbook for list of contained worksheets
40,058,756
<p>Dear Python community,</p> <p>I'd like to parse a recent Excel .xlsx file with the installed Openpyxl module. I need to get a list of the worksheets contained within the workbook. How can I code that in Python?</p> <p>Thank you.</p> <p>Regards,</p>
-4
2016-10-15T12:00:53Z
40,058,898
<p>This is the right code : </p> <pre><code>from openpyxl import load_workbook wb = load_workbook(r"path_excel_file\filename.xlsx") for sheet in wb.worksheets: print str(sheet).replace('&lt;Worksheet "','').replace('"&gt;','') </code></pre>
0
2016-10-15T12:16:09Z
[ "python", "excel", "worksheet" ]
Error installing Pillow, Searched everywhere but could not find it! 3.5
40,058,772
<p>Using PyCharm, my project interpreter settings show that it is installed but when importing, it errors out saying it doesn't know what it is:</p> <pre><code>ImportError: No module named 'Pillow' </code></pre> <p>Python v3.5 </p> <p><img src="https://i.stack.imgur.com/HamZ5.png" alt="Error Image"></p> <p><img src="https://i.stack.imgur.com/zqT5t.png" alt="Project Interpreter settings"></p> <p>Code for importing:</p> <pre><code>from tkinter import * from Pillow import * import random </code></pre>
-1
2016-10-15T12:02:59Z
40,058,818
<p>As the docs show, you don't import Pillow in your code; the package is <code>PIL</code>.</p> <pre><code>from PIL import Image </code></pre> <p>etc.</p>
0
2016-10-15T12:06:57Z
[ "python" ]
PyInstaller Script Not found Error
40,058,788
<p>I made a script for an app and it works perfectly, and now I'm trying to use PyInstaller to execute it into an .app. I'm running the latest mac os version. It seems like PyInstaller can't find my script but it's spelled correctly and it actually exists. This is what I get:</p> <pre><code>Air-Andrej:~ Andrey$ pyinstaller -F --onefile bb.py 110 INFO: PyInstaller: 3.2 110 INFO: Python: 3.5.1 122 INFO: Platform: Darwin-15.6.0-x86_64-i386-64bit 124 INFO: wrote /Users/Andrey/bb.spec 127 INFO: UPX is not available. Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.5/bin/pyinstaller", line 11, in &lt;module&gt; sys.exit(run()) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/PyInstaller/__main__.py", line 90, in run run_build(pyi_config, spec_file, **vars(args)) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/PyInstaller/__main__.py", line 46, in run_build PyInstaller.building.build_main.main(pyi_config, spec_file, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/PyInstaller/building/build_main.py", line 788, in main build(specfile, kw.get('distpath'), kw.get('workpath'), kw.get('clean_build')) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/PyInstaller/building/build_main.py", line 734, in build exec(text, spec_namespace) File "&lt;string&gt;", line 16, in &lt;module&gt; File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/PyInstaller/building/build_main.py", line 162, in __init__ raise ValueError("script '%s' not found" % script) ValueError: script '/Users/Andrey/bb.py' not found </code></pre>
0
2016-10-15T12:04:28Z
40,058,984
<p>I just figured it out. It was expecting me to put the whole directory in, so that means that the computer was trying to find the file in the wrong directory or just stopped at a certain point.</p>
0
2016-10-15T12:23:43Z
[ "python", "pyinstaller" ]
Foreign key contraint is not getting set in SQLlite using flask alchemy
40,058,855
<p>I have below table schema defined in sqlalchemy where user_id is foreign key referencing to User's user_id table</p> <pre><code>class Manufacturer(Model): __tablename__='Manufacturer' Manufacturer_id=Column(Integer,primary_key=True,autoincrement=True) name=Column(String(length=100),nullable=False) description=Column(String(length=1000),nullable=False) user_id=Column(Integer,ForeignKey(User.user_id),nullable=False) </code></pre> <p>but when table is created in sqllite db foreign key not added to table and entry is getting inserted even though user table does not have value for userid</p> <p>i searched for this issue and found in order to solve this problem we need to set <code>PRAGMA foreign_keys = ON;</code><br> but i am not able to figure it out how this can be done with my current configuration for DB </p> <p>i have below code to create engine and to add record with SQL Configuration for engine :-</p> <p><code>engine=create_engine(SQLALCHEMY_DATABASE_URI) _Session=orm.sessionmaker(autocommit=False,autoflush=True,bind=engine) session=orm.scoped_session(_Session)</code></p> <p>code to add entry in table </p> <pre><code> man_details=Manufacturer(**param) session.add(man_details) session.commit() </code></pre> <p>Please suggest how i can set foreign key constraint from python-Flask-SQLAlchemy for tables created in SQLlite3</p>
0
2016-10-15T12:10:47Z
40,059,042
<p>below code worked for me and found it from below link -</p> <p><a href="http://stackoverflow.com/questions/2614984/sqlite-sqlalchemy-how-to-enforce-foreign-keys">Sqlite / SQLAlchemy: how to enforce Foreign Keys?</a></p> <pre><code> def _fk_pragma_on_connect(dbapi_con, con_record): dbapi_con.execute('pragma foreign_keys=ON') from sqlalchemy import event event.listen(engine, 'connect', _fk_pragma_on_connect) </code></pre>
0
2016-10-15T12:30:27Z
[ "python", "database", "sqlite", "session", "sqlalchemy" ]
randomly controlling the percentage of non zero values in a matrix using python
40,058,912
<p>I am looking to create matrices with different levels of sparsity. I intend to do that by converting all the values that are nonzero in the data matrix to 1's and the remaining entries would be 0.</p> <p>I was able to achieve that using the following code. But I am not sure how would I be able to randomly make the 1's to 0's in the final matrix with control on the percentage of 1's.</p> <p>For eg:</p> <p>the numpy.random.choice </p> <blockquote> <p>numpy.random.randint(2, size = data_shape, p=[0.75,0.25])</p> </blockquote> <p>enables us to create matrices with control over the percentage of 1's. How do I control the percentage of 1's in a similar way in the final matrix?</p> <pre><code>import numpy as np import scipy.sparse as sp import numpy.ma as ma indptr = np.array([0, 2, 3, 6]) indices = np.array([0, 2, 2, 0, 1, 2]) data = np.array([1, 2, 3, 4, 5, 6]) matrix = sp.csr_matrix((data, indices, indptr), shape=(3, 3)).toarray() print(matrix) mask = ma.masked_greater(matrix, 0) print(mask) print(mask.mask) matrix2 = mask.mask int_matrix = matrix2.astype(int) print(int_matrix) </code></pre> <p>Output:</p> <pre><code>Data matrix: [[1 0 2] [0 0 3] [4 5 6]] Masked matrix: [[-- 0 --] [0 0 --] [-- -- --]] Masked values: [[ True False True] [False False True] [ True True True]] Final matrix [[1 0 1] [0 0 1] [1 1 1]] </code></pre> <p>Thanks for the help!!!</p>
1
2016-10-15T12:17:38Z
40,070,362
<p>You could do something like this -</p> <pre><code>idx = np.flatnonzero(a) N = np.count_nonzero(a!=0) - int(round(0.25*a.size)) np.put(a,np.random.choice(idx,size=N,replace=False),0) </code></pre> <p><strong>Sample run</strong></p> <p>1) Input array :</p> <pre><code>In [259]: a Out[259]: array([[0, 1, 0, 1, 1], [0, 1, 1, 0, 1], [1, 1, 0, 0, 0], [1, 0, 1, 1, 0]]) </code></pre> <p>2) Get the non-zero indices :</p> <pre><code>In [260]: idx = np.flatnonzero(a) </code></pre> <p>3) Get the number of non-zeros to be set as zeros :</p> <pre><code>In [261]: N = np.count_nonzero(a!=0) - int(round(0.25*a.size)) </code></pre> <p>4) Finally we select N randomly chosen indices from idx and set those in <code>a</code> as zeros :</p> <pre><code>In [262]: np.put(a,np.random.choice(idx,size=N,replace=False),0) </code></pre> <p>5) Verify array -</p> <pre><code>In [263]: a Out[263]: array([[0, 0, 0, 1, 0], [0, 1, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 1, 0]]) </code></pre> <p>6) Finally, we see the percentage of non-zeros and verify it to be <code>25%</code> :</p> <pre><code>In [264]: np.count_nonzero(a!=0)/float(a.size) Out[264]: 0.25 </code></pre>
0
2016-10-16T12:42:09Z
[ "python", "python-3.x", "numpy", "matrix", "scipy" ]
python: while loop does not reach last iteration
40,058,988
<p>I don't get the result of this code:</p> <pre><code>a = i = 0.05 b = 1.0 while a &lt;= b: print a a += i </code></pre> <p>Of course this should print 0.05,0.1,...,1.0 but instead the iteration stops at 0.95. Is it a float issue?</p>
0
2016-10-15T12:23:57Z
40,058,994
<p>Yes, you're working with floating point numbers, so you won't end up exactly at 1.0. Set b to e.g. 1.001 to cater for the rounding errors. Note that your numbers will be represented in binary. If they were truly decimal, they could be represented exactly.</p> <p>By the way, I'd rather use:</p> <pre><code>for i in range (1, 21): print i/20. </code></pre> <p>Note that the . (or .0) behind the 20 makes it a float, forcing float division.</p>
0
2016-10-15T12:24:51Z
[ "python", "while-loop", "iteration" ]
python: while loop does not reach last iteration
40,058,988
<p>I don't get the result of this code:</p> <pre><code>a = i = 0.05 b = 1.0 while a &lt;= b: print a a += i </code></pre> <p>Of course this should print 0.05,0.1,...,1.0 but instead the iteration stops at 0.95. Is it a float issue?</p>
0
2016-10-15T12:23:57Z
40,059,057
<p>Perhaps a better answer would be the following:</p> <pre><code>a = i = 0.05 b = 1.0 a = i = int(a * 1000) b = int(b * 1000) while a &lt;= b: print a/1000.0 a += i </code></pre> <p>This way you wont need to deal with floating point numbers at all. Many ways to skin a cat.</p>
0
2016-10-15T12:32:19Z
[ "python", "while-loop", "iteration" ]
Combinations of chars via a generator in Python
40,058,993
<p>I am trying to get all the combinations with replacement (in other words, the cartesian product) of strings with length(8) . The output is too big and I am having trouble storing it in memory all at once , so my process gets killed before it finishes.</p> <p>This is the code I use which is way more faster than Python's stdlib itertools:</p> <pre><code>import numpy as np def cartesian(arrays, out=None): """Generate a cartesian product of input arrays. Parameters ---------- arrays : list of array-like 1-D arrays to form the cartesian product of. out : ndarray Array to place the cartesian product in. Returns ------- out : ndarray 2-D array of shape (M, len(arrays)) containing cartesian products formed of input arrays. Examples -------- &gt;&gt;&gt; cartesian(([1, 2, 3], [4, 5], [6, 7])) array([[1, 4, 6], [1, 4, 7], [1, 5, 6], [1, 5, 7], [2, 4, 6], [2, 4, 7], [2, 5, 6], [2, 5, 7], [3, 4, 6], [3, 4, 7], [3, 5, 6], [3, 5, 7]]) """ arrays = [np.asarray(x) for x in arrays] shape = (len(x) for x in arrays) dtype = arrays[0].dtype ix = np.indices(shape) ix = ix.reshape(len(arrays), -1).T if out is None: out = np.empty_like(ix, dtype=dtype) for n, arr in enumerate(arrays): out[:, n] = arrays[n][ix[:, n]] return out </code></pre> <p>How would I make it return a generator out of the result , instead of storing everything to memory all at once ?</p>
-1
2016-10-15T12:24:50Z
40,063,690
<p>My impression from other questions is that <code>product</code> is the fastest way of iteratively generating cartesian combinations:</p> <pre><code>In [494]: g=itertools.product([1,2,3],[4,5],[6,7]) In [495]: list(g) Out[495]: [(1, 4, 6), (1, 4, 7), (1, 5, 6), (1, 5, 7), (2, 4, 6), (2, 4, 7), (2, 5, 6), (2, 5, 7), (3, 4, 6), (3, 4, 7), (3, 5, 6), (3, 5, 7)] </code></pre> <p>Your code is a mapping of <code>np.indices</code>, which is slower:</p> <pre><code>In [499]: timeit np.indices((3,2,2)).reshape(3,-1).T The slowest run took 11.08 times longer than the fastest. This could mean that an intermediate result is being cached. 10000 loops, best of 3: 61.6 µs per loop In [500]: timeit list(itertools.product([1,2,3],[4,5],[6,7])) 100000 loops, best of 3: 3.51 µs per loop </code></pre>
0
2016-10-15T20:07:19Z
[ "python", "python-2.7", "numpy", "scikit-learn", "itertools" ]
How to use recursion in python
40,059,033
<p>I am trying to solve a problem which stimulate movements of a robot. The robot starts with position (0, 0, 'N'). The command is given in a list of strings. the 'turn' function turns from N to E to S to W and back to N. The move function moves in the specific direction: N,S in y axis and E,W in x axis. N: y+1 S: y-1 W: x-1 E: x+1</p> <p>The part I am having trouble with is, when trying to use shortcuts in the function. Using 'turnleft' instead of ['turn', 'turn', 'turn'], 'turnright' instead of 'turn'</p> <pre><code>def macro_interpreter(code, macros): </code></pre> <p>when call the function:</p> <pre><code>print(macro_interpreter(['turnleft', 'turnright'], {'turnleft': ['turn', 'turn', 'turn'], 'turnright' : ['turn'], 'bigleftturn' : ['move', 'move', 'turnleft', 'move', 'move'], 'bigrightturn' : ['move', 'move', 'turnright', 'move', 'move']})) </code></pre> <p>the definition of the term is given in a dictionary. My code only runs for the first command and then terminate, it ignores the second code in the list</p> <pre><code>def macro_interpreter(code, macros): x,y,index = 0, 0, 0 state = ['N', 'E', 'S', 'W'] for command in code: if command in macros: return macro_interpreter(macros[command], macros) else: if command == 'move': if state[index] == 'N': y += 1 elif state[index] == 'E': x += 1 elif state[index] == 'S': y -= 1 elif state[index] == 'W': x -= 1 elif command == 'turn': try: index = index + 1 except IndexError: index = 0 return (x, y, state[index]) </code></pre>
1
2016-10-15T12:29:19Z
40,059,201
<p>The line</p> <pre><code>return macro_interpreter (macros etc. </code></pre> <p>will do just that. It will leave the for loop and return from the outer call. End of story.</p>
0
2016-10-15T12:47:52Z
[ "python", "python-3.x" ]
How to use recursion in python
40,059,033
<p>I am trying to solve a problem which stimulate movements of a robot. The robot starts with position (0, 0, 'N'). The command is given in a list of strings. the 'turn' function turns from N to E to S to W and back to N. The move function moves in the specific direction: N,S in y axis and E,W in x axis. N: y+1 S: y-1 W: x-1 E: x+1</p> <p>The part I am having trouble with is, when trying to use shortcuts in the function. Using 'turnleft' instead of ['turn', 'turn', 'turn'], 'turnright' instead of 'turn'</p> <pre><code>def macro_interpreter(code, macros): </code></pre> <p>when call the function:</p> <pre><code>print(macro_interpreter(['turnleft', 'turnright'], {'turnleft': ['turn', 'turn', 'turn'], 'turnright' : ['turn'], 'bigleftturn' : ['move', 'move', 'turnleft', 'move', 'move'], 'bigrightturn' : ['move', 'move', 'turnright', 'move', 'move']})) </code></pre> <p>the definition of the term is given in a dictionary. My code only runs for the first command and then terminate, it ignores the second code in the list</p> <pre><code>def macro_interpreter(code, macros): x,y,index = 0, 0, 0 state = ['N', 'E', 'S', 'W'] for command in code: if command in macros: return macro_interpreter(macros[command], macros) else: if command == 'move': if state[index] == 'N': y += 1 elif state[index] == 'E': x += 1 elif state[index] == 'S': y -= 1 elif state[index] == 'W': x -= 1 elif command == 'turn': try: index = index + 1 except IndexError: index = 0 return (x, y, state[index]) </code></pre>
1
2016-10-15T12:29:19Z
40,059,229
<p>If you always hit the one <code>else</code> statement in the loop over the <code>code</code> commands, then you never will recurse because <code>command not in macros</code>. </p> <p>After the first iteration, <code>code == ['turn', 'turn', 'turn']</code>, but <code>macros</code> contains no key <code>"turn"</code></p> <hr> <p>If you wish to do this more correctly, then you can pass along x, y, and the "direction index state" as parameters to the function, then increment / modify those within the recursive call rather than only modify local variables of the function and always restart them back at (0,0, 0). </p> <p>Also, you need to replace that try except with <code>index = (index + 1) % len(state)</code> because no IndexError is going to be caught by incrementing a number </p> <hr> <p>So, something like this </p> <pre><code>state = ['N', 'E', 'S', 'W'] def macro_interpreter(code, macros, x=0,y=0,index=0): # TODO: check if x or y have gone outside "the board" # TODO: return to break from recursion for command in code: if command in macros: return macro_interpreter(macros[command], macros,x,y,index) else: if command == 'move': if state[index] == 'N': return macro_interpreter(code[1:], macros,x,y=y+1,index) </code></pre>
2
2016-10-15T12:50:02Z
[ "python", "python-3.x" ]
How to use recursion in python
40,059,033
<p>I am trying to solve a problem which stimulate movements of a robot. The robot starts with position (0, 0, 'N'). The command is given in a list of strings. the 'turn' function turns from N to E to S to W and back to N. The move function moves in the specific direction: N,S in y axis and E,W in x axis. N: y+1 S: y-1 W: x-1 E: x+1</p> <p>The part I am having trouble with is, when trying to use shortcuts in the function. Using 'turnleft' instead of ['turn', 'turn', 'turn'], 'turnright' instead of 'turn'</p> <pre><code>def macro_interpreter(code, macros): </code></pre> <p>when call the function:</p> <pre><code>print(macro_interpreter(['turnleft', 'turnright'], {'turnleft': ['turn', 'turn', 'turn'], 'turnright' : ['turn'], 'bigleftturn' : ['move', 'move', 'turnleft', 'move', 'move'], 'bigrightturn' : ['move', 'move', 'turnright', 'move', 'move']})) </code></pre> <p>the definition of the term is given in a dictionary. My code only runs for the first command and then terminate, it ignores the second code in the list</p> <pre><code>def macro_interpreter(code, macros): x,y,index = 0, 0, 0 state = ['N', 'E', 'S', 'W'] for command in code: if command in macros: return macro_interpreter(macros[command], macros) else: if command == 'move': if state[index] == 'N': y += 1 elif state[index] == 'E': x += 1 elif state[index] == 'S': y -= 1 elif state[index] == 'W': x -= 1 elif command == 'turn': try: index = index + 1 except IndexError: index = 0 return (x, y, state[index]) </code></pre>
1
2016-10-15T12:29:19Z
40,059,322
<p>I suspect it's because you return </p> <pre><code>macro_interpreter(macros[command], macros) </code></pre> <p>This simply exits the function once the recursed code is run. You'll see if you change</p> <pre><code>return macro_interpreter(macros[command], macros) </code></pre> <p>to</p> <pre><code>print macro_interpreter(macros[command], macros) </code></pre> <p>that the code will print what you want it to do. How you want to actually handle the output is up to you.</p>
0
2016-10-15T13:01:16Z
[ "python", "python-3.x" ]
How to use recursion in python
40,059,033
<p>I am trying to solve a problem which stimulate movements of a robot. The robot starts with position (0, 0, 'N'). The command is given in a list of strings. the 'turn' function turns from N to E to S to W and back to N. The move function moves in the specific direction: N,S in y axis and E,W in x axis. N: y+1 S: y-1 W: x-1 E: x+1</p> <p>The part I am having trouble with is, when trying to use shortcuts in the function. Using 'turnleft' instead of ['turn', 'turn', 'turn'], 'turnright' instead of 'turn'</p> <pre><code>def macro_interpreter(code, macros): </code></pre> <p>when call the function:</p> <pre><code>print(macro_interpreter(['turnleft', 'turnright'], {'turnleft': ['turn', 'turn', 'turn'], 'turnright' : ['turn'], 'bigleftturn' : ['move', 'move', 'turnleft', 'move', 'move'], 'bigrightturn' : ['move', 'move', 'turnright', 'move', 'move']})) </code></pre> <p>the definition of the term is given in a dictionary. My code only runs for the first command and then terminate, it ignores the second code in the list</p> <pre><code>def macro_interpreter(code, macros): x,y,index = 0, 0, 0 state = ['N', 'E', 'S', 'W'] for command in code: if command in macros: return macro_interpreter(macros[command], macros) else: if command == 'move': if state[index] == 'N': y += 1 elif state[index] == 'E': x += 1 elif state[index] == 'S': y -= 1 elif state[index] == 'W': x -= 1 elif command == 'turn': try: index = index + 1 except IndexError: index = 0 return (x, y, state[index]) </code></pre>
1
2016-10-15T12:29:19Z
40,059,495
<p>There are some amendments which i did in your code to support recursion properly. This code will do, what you want to acheive. </p> <pre><code>def macro_interpreter(code, macros, x=0, y=0, index=0): state = ['N', 'E', 'S', 'W'] for command in code: if command in macros: x, y, curr_state = macro_interpreter(macros[command], macros, x, y, index) # update new index with new state value index = state.index(curr_state) else: if command == 'move': if state[index] == 'N': y += 1 elif state[index] == 'E': x += 1 elif state[index] == 'S': y -= 1 elif state[index] == 'W': x -= 1 elif command == 'turn': index = (index + 1)%len(state) return (x, y, state[index]) </code></pre> <p>Now, if i run your test case</p> <pre><code>&gt;&gt; print macro_interpreter(['turnleft', 'turnright'], {'turnleft': ['turn', 'turn', 'turn'], 'turnright' : ['turn'], 'bigleftturn' : ['move', 'move', 'turnleft', 'move', 'move'], 'bigrightturn' : ['move', 'move', 'turnright', 'move', 'move']}) Output:- (0, 0, 'N') </code></pre> <p>I hope this will helps you. </p>
1
2016-10-15T13:17:44Z
[ "python", "python-3.x" ]
Error on join condition with SqlAlchemy
40,059,136
<p>I'm trying to use SQLAlchemy on my python app but I have a problem with the many to many relationship. I have 4 tables:</p> <p>users, flags, commandes, channels, and commandes_channels_flags</p> <p>commandes_channels_flags contain a foreign key for each concerned table (commandes, channels and flags)</p> <p>An user has a flag_id as foreign key too.</p> <p>So I try to link commandes, channels and flag. the objective is to know that a command can run on a channel for a flag.</p> <p>I did this:</p> <pre><code>from sqlalchemy import Column, Integer, String, ForeignKey from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship Base = declarative_base() class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) pseudo = Column(String(50), unique=True, nullable=False) flag_id = Column(ForeignKey('flags.id')) class Flag(Base): __tablename__ = 'flags' id = Column(Integer, primary_key=True) irc_flag = Column(Integer) nom = Column(String(50)) users = relationship("User", backref="flag", order_by="Flag.irc_flag") commande = relationship("Commande", secondary="commandes_channels_flags", back_populates="flags") channel = relationship("Channel", secondary="commandes_channels_flags", back_populates="flags") class Channel(Base): __tablename__ = 'channels' id = Column(Integer, primary_key=True) uri = Column(String(50)) topic = Column(String(255)) commande = relationship("Commande", secondary="commandes_channels_flags", back_populates="channels") flag = relationship("Flag", secondary="commandes_channels_flags", back_populates="channels") class Commande(Base): __tablename__ = 'commandes' id = Column(Integer, primary_key=True) pattern = Column(String(50)) channel = relationship("Channel", secondary="commandes_channels_flags", back_populates="commandes") flag = relationship("Flag", secondary="commandes_channels_flags", back_populates="commandes") class CommandeChannelFlag(Base): __tablename__ = 'commandes_channels_flags' id = Column(Integer, primary_key=True) commande_id = Column(ForeignKey('commandes.id')) channel_id = Column(ForeignKey('channels.id')) flag_id = Column(ForeignKey('flags.id')) </code></pre> <p>But I have this error:</p> <pre><code>sqlalchemy.exc.InvalidRequestError: Mapper 'Mapper|Commande|commandes' has no property 'channels' </code></pre> <p>I understand that I have an error in my tables linking but I can't find it.</p>
0
2016-10-15T12:40:24Z
40,059,622
<p><code>back_populates</code> needs to match the exact name of the related property on the other model. In <code>Channel</code>, you have <code>back_populates="channels"</code>, but in <code>Commande</code>, you have:</p> <pre><code>channel = relationship("Channel", secondary="commandes_channels_flags", back_populates="commandes") </code></pre> <p>Instead, change <code>channel = relationship</code> to <code>channels = relationship</code>.</p> <p>You'll also need to change the other relationship properties to <code>Flag.commandes</code>, <code>Flag.channels</code>, <code>Channel.commandes</code>, <code>Channel.flags</code>, and <code>Commande.flags</code> to match your <code>back_populates</code> arguments.</p>
1
2016-10-15T13:29:56Z
[ "python", "python-3.x", "sqlalchemy" ]
python pptx XyChart setting label font size
40,059,179
<p>Within an python-pptx-generated XYchart, I would like to add labels to each point of the series. Code looks like this:</p> <pre><code>for p, v in zip(chart.series[0].points, dataSeries): p.data_label.position = XL_LABEL_POSITION.ABOVE p.data_label.text_frame.clear() for paras in p.data_label.text_frame.paragraphs: paras.font.size = Pt(10) p.data_label.text_frame.text = str.format('{0:.1f}', v) </code></pre> <p>The new text is set correctly, but iterating through the paras to change font size has no effect. Any ideas how I could achieve a font size change for the labels?</p>
0
2016-10-15T12:45:50Z
40,063,902
<p>You need to set the font size <em>after</em> adding the text frame text.</p> <pre><code>data_label = p.data_label ... text_frame = data_label.text_frame # text_frame.clear() # this line is not needed, assigning to .text does this text_frame.text = str.format('{0:.1f}', v) for paragraph in text_frame.paragraphs: paragraph.font.size = Pt(10) # -- OR -- for run in text_frame.paragraphs[0].runs: run.font.size = Pt(10) </code></pre> <p>When you call <code>TextFrame.text</code>, all existing paragraphs are removed and a single new paragraph is added. Along the way, all character formatting is removed to produce a "clean slate" before adding the specified text.</p> <p>I don't recall whether PowerPoint respects the font set at the paragraph level (using the <code>a:defRPr</code> element). If not, you'll need to do it at the run level, as shown after the -- OR -- line.</p>
0
2016-10-15T20:30:32Z
[ "python", "fonts", "size", "labels", "python-pptx" ]
Python: Appending to a list, which is value of a dictionary
40,059,188
<p>Here is the code, which I would like to understand. I am creating a dict using elements of a list as keys and another list as default values. Then update this dict with another one. Finally, I would like to append to the list within dict. The append is happening multiple times for some of the elements. I would like append to happy only once for each of the values of dict. </p> <pre><code>l=['a','b','c'] bm=dict.fromkeys(l,['-1','-1']) u={'a':['Q','P']} bm.update(u) bm # {'a': ['Q', 'P'], 'c': ['-1', '-1'], 'b': ['-1', '-1']} for k in bm.keys(): bm[k].append('DDD') bm # {'a': ['Q', 'P', 'DDD'], 'c': ['-1', '-1', 'DDD', 'DDD'], 'b': ['-1', '-1', 'DDD', 'DDD']} </code></pre> <p>I was expecting appending <code>DDD</code> to happen once for <code>c</code> and <code>b</code> like this:</p> <pre><code>{'a': ['Q', 'P', 'DDD'], 'c': ['-1', '-1', 'DDD'], 'b': ['-1', '-1', 'DDD']} </code></pre>
1
2016-10-15T12:46:49Z
40,059,238
<p>this</p> <pre><code>bm=dict.fromkeys(l,['-1','-1']) </code></pre> <p>Is reusing the same list <code>['-1','-1']</code> for all keys, which explains the effect you're witnessing.</p> <p>to achieve what you want you could do this with a <em>dict comprehension</em></p> <pre><code>bm = {x:[-1,1] for x in ['a','b','c']} </code></pre> <p>(the loop within the dict comp ensures that a different instance of the <code>[-1,1]</code> list is created for each value, which guarantees independence)</p> <p>Full example:</p> <pre><code>bm = {x:[-1,1] for x in ['a','b','c']} u={'a':['Q','P']} bm.update(u) print(bm) for k in bm.keys(): bm[k].append('DDD') print(bm) </code></pre> <p>result:</p> <pre><code>{'c': [-1, 1], 'a': ['Q', 'P'], 'b': [-1, 1]} {'c': [-1, 1, 'DDD'], 'a': ['Q', 'P', 'DDD'], 'b': [-1, 1, 'DDD']} </code></pre> <p>Note: if you want that all accessed keys create a default value when not present you can use <code>defaultdict</code> with a lambda which creates a different instance of <code>['-1','-1']</code> every time.</p> <pre><code>from collections import defaultdict bm = defaultdict(lambda : ['-1','-1']) </code></pre>
1
2016-10-15T12:51:23Z
[ "python" ]
What would be wrong with this function that return a rounded number in millions
40,059,195
<p>I'm a beginner doing an online course using ipython notebook and panda.</p> <p>We are given a function</p> <pre><code>def roundToMillions (value): result = round(value / 1000000) return result </code></pre> <p>and some tests </p> <pre><code>roundToMillions(4567890.1) == 5 roundToMillions(0) == 0 # always test with zero... roundToMillions(-1) == 0 # ...and negative numbers roundToMillions(1499999) == 1 # test rounding to the nearest </code></pre> <p>We are told .. <strong><em>Define a few more test cases for both functions</em></strong> .</p> <p>I can't think of any more tests though.</p> <p>The question posed is:</p> <p><strong><em>Why can't you use roundToMillions() to round the population to millions of inhabitants?</em></strong></p> <p>I don't quite understand what could be wrong with the function. </p> <p>This course is free and so there is not really much help available.</p>
0
2016-10-15T12:47:17Z
40,059,307
<p>In terms of test cases, this loop will generate many test cases and the results speak for themselves:</p> <pre><code>for x in xrange(-2000000, 2000000, 250000): print roundToMillions(x), x &gt;&gt; -2.0 -2000000 &gt;&gt; -2.0 -1750000 &gt;&gt; -2.0 -1500000 &gt;&gt; -2.0 -1250000 &gt;&gt; -1.0 -1000000 &gt;&gt; -1.0 -750000 &gt;&gt; -1.0 -500000 &gt;&gt; -1.0 -250000 &gt;&gt; 0.0 0 &gt;&gt; 0.0 250000 &gt;&gt; 0.0 500000 &gt;&gt; 0.0 750000 &gt;&gt; 1.0 1000000 &gt;&gt; 1.0 1250000 &gt;&gt; 1.0 1500000 &gt;&gt; 1.0 1750000 </code></pre> <p>So obviously it's rounding down.</p> <p>This is due to integer division. removing the round shows this:</p> <pre><code>def roundToMillions (value): result = value / 1000000 return result print roundToMillions(999999) &gt;&gt; 0 </code></pre> <p>This is fixed by adding a .0 to the function:</p> <pre><code>def roundToMillions (value): result = round(value / 1000000.0) return result for x in xrange(0, 1000000, 250000): print roundToMillions(x), x &gt;&gt; 0.0 0 &gt;&gt; 0.0 250000 &gt;&gt; 1.0 500000 &gt;&gt; 1.0 750000 print roundToMillions(999999) &gt;&gt; 1.0 </code></pre> <p>For more on integer division have a look at </p> <pre><code>print (3/2) &gt;&gt; 1 print (3.0/2.0) &gt;&gt; 1.5 </code></pre>
0
2016-10-15T12:59:48Z
[ "python", "pandas" ]
Why do I get an TypeError: 'in <string>' requires string as left operand, not list error when running my program?
40,059,244
<p>When i run through my python code:</p> <pre><code>import time print("\n\n\t\tWelcome to the Automated Troubleshooting Program\n\n") time.sleep(1) name = input("Before we begin, what is your name?\nName: ") time.sleep(1) option_end = False while option_end == False: option = input("Would you like to quit or carry on?\nChoice: ") option = option.lower() if option == 'carry on': option_end = True question_end = False while question_end == False: question = input("\nWhat is wrong with your device?\nProblem: ") question = question.lower() words = question.split() print("") searchfile = open("Mobile Troubleshooter Problems.txt", "r") for line in searchfile: if words in line: print (line) question_end = True searchfile.close() if words not in line: print("Invalid input.\nPlease try again.\n") time.sleep(1) question_end = False searchfile.close() if option == 'quit': print("Shutting down in: 3") time.sleep(1) print(" 2") time.sleep(1) print(" 1") time.sleep(1) print("\n\n\t\t\t\t...SHUTTING DOWN...") time.sleep(1) quit() </code></pre> <p>I get this error:</p> <p>line 26, in if words in line: TypeError: 'in ' requires string as left operand, not list</p> <p>(When going through the code type: your name, 'carry on', 'device screen')</p> <p>Here is the data from the .txt notebook file:</p> <pre><code>screen: there is no display on the device screen - Solution: send to the supplier to get the screen fixed. screen: the device screen is cracked - Solution: send to the supplier to get the screen fixed. speakers: there is no sound on the device - Solution: send back to the supplier to get speakers fixed. camera: the camera is not working - Solution: send back to the supplier to get the camera fixed. software: the phone keeps on crashing / failing - Solution: send back to the supplier to get the software fixed. </code></pre>
-1
2016-10-15T12:51:58Z
40,059,367
<p>To start you have an indentation error on your first while loop.</p> <p>The problem is that you are trying to check if a list is in a string (doesn't work).</p> <p>The split in line 19 changes the variable words to a list.</p> <p>If you want to check if any of the words in question are in the line of search file you should try</p> <pre><code>if any(wd in line for wd in words): </code></pre>
0
2016-10-15T13:06:35Z
[ "python" ]
Python - recursively find lists in lists (n deep)
40,059,273
<p>I'm trying to use ipaddress (<a href="https://docs.python.org/3/library/ipaddress.html" rel="nofollow">https://docs.python.org/3/library/ipaddress.html</a>) to solve the following issue:</p> <p>I have a BGP aggregate-address of 10.76.32.0/20</p> <p>from which I would like to subtract all the network commands on the same router to figure out if the aggregate-address is larger than the defined networks and there is free network space left over.</p> <p>The networks in this case are:</p> <p>10.76.32.0/24 10.76.33.0/24 10.76.34.0/24 10.76.35.0/24 10.76.36.0/24 10.76.37.0/24 10.76.38.0/24 10.76.39.0/24 10.76.40.0/24 10.76.41.0/24 10.76.42.0/24 10.76.43.0/24 10.76.44.0/25 10.76.44.128/25 10.76.45.0/24 10.76.46.0/24 10.76.47.240/30 10.96.208.219/32</p> <p>Using ipaddress.address_exclude(network) I can subtract a network from the aggregate-address and the operation returns an iterable object.</p> <p>I could then make a for loop on this iterable object and see if it contains any of the other networks but in case it does, I will get yet another iterable object as the result. This process could hypothetically return lists within lists to an unspecified depth.</p> <p>My question would be if anyone knows of a way to find all elements in such a structure of lists within lists that go to an arbitrary depth.</p> <p>Hunor</p> <p>Edit: Thanks for the answer Андрей Беньковский. I didn't have time to check it out yet but I did manage to find a way to do it without using recursion with the .issubset method from netaddr:</p> <pre><code>def undeclared_in_aggregate(aggregate, network): remaining = [] composite = [] for a_cidr in aggregate: a_cidr = IPSet([a_cidr]) for n_cidr in network: n_cidr = IPSet([n_cidr]) if n_cidr.issubset(a_cidr): a_cidr.remove(n_cidr.iprange()) remaining = re.sub(r'IPSet\(\[|\]\)|\'', '', str(a_cidr)) remaining = remaining.split(',') if remaining == ['']: remaining = [] composite += remaining return composite </code></pre> <p>this would take the aggregate-address and networks in list format and return the difference as a new list (per each aggregate-address).</p> <p>for the example above: ['10.76.47.0/25', ' 10.76.47.128/26', ' 10.76.47.192/27', ' 10.76.47.224/28', ' 10.76.47.244/30', ' 10.76.47.248/29']</p>
0
2016-10-15T12:55:29Z
40,075,765
<p>You didn't indicate the version of python (2 or 3) you are using so I assumed it's python3 based on the fact that the link you posted is to the python3 documentation. You didn't post any code, but based on your description of the issue I assume you need something like this:</p> <pre><code>from ipaddress import ip_network, summarize_address_range from itertools import chain def exclude_multiple(super_network, networks): networks = sorted(networks, key=lambda n:n.network_address) starts = (n.broadcast_address + 1 for n in networks) starts = chain([super_network.network_address], starts) ends = (n.network_address - 1 for n in networks) ends = chain(ends, [super_network.broadcast_address]) return ((s, e) for s, e in zip(starts, ends) if s != e + 1) # s-1 != (e+1) - 1 networks = [ '10.76.32.0/24', '10.76.33.0/24', # more here ] networks = map(ip_network, networks) super_network = ip_network('10.76.32.0/20') free_ranges = exclude_multiple(super_network, networks) free_networks = (summarize_address_range(f, l) for f, l in free_ranges) free_networks = list(chain.from_iterable(free_networks)) </code></pre> <p>This code doesn't include range checking so if the <code>networks</code> overlap or go outside the <code>super_network</code> you'll get a no very useful error from <code>summarize_address_range</code> but the range checking can be added with just a few tweaks.</p>
0
2016-10-16T21:36:31Z
[ "python", "networking", "recursion" ]
Resolving Catastrophic Backtracking issue in RegEx
40,059,284
<p>I am using RegEx for finding URL substrings in strings. The RegEx I am using has been taken from tohster's answer on - <a href="http://stackoverflow.com/questions/520031/whats-the-cleanest-way-to-extract-urls-from-a-string-using-python/30408189#30408189">What&#39;s the cleanest way to extract URLs from a string using Python?</a></p> <p>The RE is -</p> <pre><code>r'^(?:(?:https?|ftp)://)(?:\S+(?::\S*)?@)?(?:(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:/[^\s]*)?$' </code></pre> <p>I have done some changes to it - </p> <blockquote> <ol> <li>In the IPv4 detection part, I changed the order of the IP range to be found. > Precisely, changed <code>[1-9]\d?|1\d\d|2[01]\d|22[0-3]</code> to <code>25[0-5]|2[0-4][0-9]|1[0-&gt; 9]{2}|[1-9][0-9]|[0-9]</code> at 2 instances.</li> <li>Made the https group - <code>(?:https?|ftp):\/\/)?(?:\S+(?::\S*)?@)</code> optional.</li> </ol> </blockquote> <p>The final version is -</p> <pre><code>(?:(?:https?|ftp):\/\/)?(?:\S+(?::\S*)?@)?(?:((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])|(?:(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:\/[^\s]*)? </code></pre> <p>The final RE I am using seems to be very promising and has improved significantly as per my requirements(as compared to the original one) and works in Python as well as Java Script, except for the fact that due to the changes I have done have caused the following examples to give <code>"catastrophic backtracking"</code> error -</p> <blockquote> <p>asasasasasac31.23.53.122asasassasd</p> <p>12312312312321.32.34.2312312312321</p> <p>12.3423423432.234123123.123</p> <p>31.134232131.231.34</p> </blockquote> <p>Can be tested at - <a href="https://regex101.com/r/i6jDei/1" rel="nofollow">https://regex101.com/r/i6jDei/1</a></p> <p>My contention is that the first example - <code>asasasasasac31.23.53.122asasassasd</code> should have some slick way to pass as the IP is surrounded by non-numeric chars.</p> <p>Also, is there a way to pass the first two of the above examples as valid IPv4 addresses?</p> <p>To resolve ambiguity, I would opt for the largest possible Address, i.e.,</p> <blockquote> <p>31.23.53.122</p> <p>21.32.34.231</p> </blockquote>
0
2016-10-15T12:56:37Z
40,060,148
<p>The issue of the catastrophic backtracking is caused by the pattern <code>(?:(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,}))</code> where <code>(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)</code> will jump through a lot of combinations, if the overall pattern can not be matched. As you can see the character classes are basically the same, so e.g. for <code>asasasasasac31</code> it can match like:</p> <pre><code>(asasasasasac31) (a)(sasasasasac31) (a)(s)(asasasasac31) (as)(asasasasac31) </code></pre> <p>This is not really the way it actually takes, just to show how many combinations exist.</p> <p>The mistake here seems to be the <code>-</code> being optional which I see no reason for. If we remove the -, we get it working for your samples (and reduce the number of steps for the already working samples). </p> <p>See the updated <a href="https://regex101.com/r/i6jDei/3" rel="nofollow">regex101-demo</a>, where I also added your samples that caused the catastrophic backtracking.</p> <p>The final pattern then is:</p> <pre><code>(?:(?:https?|ftp):\/\/)?(?:\S+(?::\S*)?@)?(?:((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])|(?:(?:[a-z\u00a1-\uffff0-9]+-)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]+-)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:\/[^\s]*)? </code></pre>
2
2016-10-15T14:20:07Z
[ "python", "regex", "url", "ip-address", "ipv4" ]
How to avoid a specific tag while extracting xpath
40,059,298
<p>By using xpath(.//div[@class="entry-content"]/div/p//text()') i am getting all the text1,text2,.....text6. How to take only "text3","text4","text5","text6"??</p> <pre><code>`&lt;div class="entry-content"&gt; &lt;div&gt; &lt;p&gt; &lt;st&gt;text1&lt;/st&gt; &lt;/p&gt; &lt;p&gt; &lt;st&gt;text2&lt;/st&gt; &lt;/p&gt; &lt;/div&gt; &lt;p&gt;"text3"&lt;/p&gt; &lt;div&gt; &lt;p&gt; &lt;st&gt;"text4"&lt;/st&gt; &lt;/p&gt; &lt;p&gt; &lt;st&gt;"text5"&lt;/st&gt; &lt;/p&gt; &lt;p&gt; &lt;st&gt;"text6"&lt;/st&gt; &lt;/p&gt; &lt;/div&gt; &lt;/div&gt;` </code></pre>
1
2016-10-15T12:59:05Z
40,060,862
<p>If you only want nodes within the second <code>div</code>, use the path</p> <pre><code>.//div[@class="entry-content"]/div[2]/p//text() </code></pre> <p>If want nodes in all <code>div</code>s except the first, write</p> <pre><code>.//div[@class="entry-content"]/div[position()&gt;1]/p//text() </code></pre> <p>If you want to select on some other basis, then explain what rules you want to apply. (Your question says "avoid a specific tag", but you are very <em>unspecific</em> about what tag you want to avoid).</p>
0
2016-10-15T15:27:23Z
[ "python", "python-2.7", "python-3.x", "xpath" ]
How to avoid a specific tag while extracting xpath
40,059,298
<p>By using xpath(.//div[@class="entry-content"]/div/p//text()') i am getting all the text1,text2,.....text6. How to take only "text3","text4","text5","text6"??</p> <pre><code>`&lt;div class="entry-content"&gt; &lt;div&gt; &lt;p&gt; &lt;st&gt;text1&lt;/st&gt; &lt;/p&gt; &lt;p&gt; &lt;st&gt;text2&lt;/st&gt; &lt;/p&gt; &lt;/div&gt; &lt;p&gt;"text3"&lt;/p&gt; &lt;div&gt; &lt;p&gt; &lt;st&gt;"text4"&lt;/st&gt; &lt;/p&gt; &lt;p&gt; &lt;st&gt;"text5"&lt;/st&gt; &lt;/p&gt; &lt;p&gt; &lt;st&gt;"text6"&lt;/st&gt; &lt;/p&gt; &lt;/div&gt; &lt;/div&gt;` </code></pre>
1
2016-10-15T12:59:05Z
40,069,929
<p>As per your clarification it seems that "p" are the nodes you want to avoid, in particular the first 2 of them. As they may appear at different depth level, one of the ways you achieve it is with this xpath expression, which is basically a variation of the solution provided by Michael Kay:</p> <pre><code>//div[@class="entry-content"]//descendant::p[position()&gt;2]//text() </code></pre>
0
2016-10-16T11:52:09Z
[ "python", "python-2.7", "python-3.x", "xpath" ]
Advanced array concatenation python
40,059,330
<p>Say I have four multi-dimensional arrays - </p> <pre><code>a = [["a","a","a"], ["a","a","a"], ["a","a","a"]] b = [["b","b","b"], ["b","b","b"], ["b","b","b"]] c = [["c","c","c"], ["c","c","c"], ["c","c","c"]] d = [["d","d","d"], ["d","d","d"], ["d","d","d"]] </code></pre> <p>and I want to combine them into a single array like</p> <pre><code>total = [["a","a","a","b","b","b"], ["a","a","a","b","b","b"], ["a","a","a","b","b","b"], ["c","c","c","d","d","d"], ["c","c","c","d","d","d"], ["c","c","c","d","d","d"]] </code></pre> <p>How would I do it?</p> <p><em>I am doing it for spelunky-style map generation</em></p>
2
2016-10-15T13:01:51Z
40,059,388
<p>Maybe like this:</p> <pre><code>top = list(x+y for x,y in zip(a,b)) bottom = list(x+y for x,y in zip(c,d)) total = top + bottom for r in total: print(r) </code></pre> <p>Output:</p> <pre><code>['a', 'a', 'a', 'b', 'b', 'b'] ['a', 'a', 'a', 'b', 'b', 'b'] ['a', 'a', 'a', 'b', 'b', 'b'] ['c', 'c', 'c', 'd', 'd', 'd'] ['c', 'c', 'c', 'd', 'd', 'd'] ['c', 'c', 'c', 'd', 'd', 'd'] </code></pre>
2
2016-10-15T13:08:29Z
[ "python", "arrays", "pygame", "concatenation" ]
Advanced array concatenation python
40,059,330
<p>Say I have four multi-dimensional arrays - </p> <pre><code>a = [["a","a","a"], ["a","a","a"], ["a","a","a"]] b = [["b","b","b"], ["b","b","b"], ["b","b","b"]] c = [["c","c","c"], ["c","c","c"], ["c","c","c"]] d = [["d","d","d"], ["d","d","d"], ["d","d","d"]] </code></pre> <p>and I want to combine them into a single array like</p> <pre><code>total = [["a","a","a","b","b","b"], ["a","a","a","b","b","b"], ["a","a","a","b","b","b"], ["c","c","c","d","d","d"], ["c","c","c","d","d","d"], ["c","c","c","d","d","d"]] </code></pre> <p>How would I do it?</p> <p><em>I am doing it for spelunky-style map generation</em></p>
2
2016-10-15T13:01:51Z
40,059,403
<p>You can do it with a one line instruction, that mix list comprehension, zip instructions, and list concatenation with <code>+</code></p> <pre><code>[aa+bb for aa,bb in zip(a,b)] + [cc+dd for cc,dd in zip(c,d)] </code></pre> <p>The whole code </p> <pre><code>a = [["a","a","a"], ["a","a","a"], ["a","a","a"]] b = [["b","b","b"], ["b","b","b"], ["b","b","b"]] c = [["c","c","c"], ["c","c","c"], ["c","c","c"]] d = [["d","d","d"], ["d","d","d"], ["d","d","d"]] result = [aa+bb for aa,bb in zip(a,b)] + [cc+dd for cc,dd in zip(c,d)] </code></pre>
2
2016-10-15T13:09:45Z
[ "python", "arrays", "pygame", "concatenation" ]
Advanced array concatenation python
40,059,330
<p>Say I have four multi-dimensional arrays - </p> <pre><code>a = [["a","a","a"], ["a","a","a"], ["a","a","a"]] b = [["b","b","b"], ["b","b","b"], ["b","b","b"]] c = [["c","c","c"], ["c","c","c"], ["c","c","c"]] d = [["d","d","d"], ["d","d","d"], ["d","d","d"]] </code></pre> <p>and I want to combine them into a single array like</p> <pre><code>total = [["a","a","a","b","b","b"], ["a","a","a","b","b","b"], ["a","a","a","b","b","b"], ["c","c","c","d","d","d"], ["c","c","c","d","d","d"], ["c","c","c","d","d","d"]] </code></pre> <p>How would I do it?</p> <p><em>I am doing it for spelunky-style map generation</em></p>
2
2016-10-15T13:01:51Z
40,059,522
<p>Since you are talking about arrays, using numpy arrays and <code>hstack()</code> and <code>vstack()</code>:</p> <pre><code>import numpy as np ab = np.hstack((np.array(a),np.array(b))) cd = np.hstack((np.array(c),np.array(d))) print np.vstack((ab,cd)) </code></pre> <p>Which leads you:</p> <pre><code>[['a' 'a' 'a' 'b' 'b' 'b'] ['a' 'a' 'a' 'b' 'b' 'b'] ['a' 'a' 'a' 'b' 'b' 'b'] ['c' 'c' 'c' 'd' 'd' 'd'] ['c' 'c' 'c' 'd' 'd' 'd'] ['c' 'c' 'c' 'd' 'd' 'd']] </code></pre> <p>Alternatively, using <code>concatenate()</code>:</p> <pre><code>ab = np.concatenate((np.array(a),np.array(b)),axis=1) cd = np.concatenate((np.array(c),np.array(d)),axis=1) print np.concatenate((ab,cd)) </code></pre>
0
2016-10-15T13:19:35Z
[ "python", "arrays", "pygame", "concatenation" ]
Advanced array concatenation python
40,059,330
<p>Say I have four multi-dimensional arrays - </p> <pre><code>a = [["a","a","a"], ["a","a","a"], ["a","a","a"]] b = [["b","b","b"], ["b","b","b"], ["b","b","b"]] c = [["c","c","c"], ["c","c","c"], ["c","c","c"]] d = [["d","d","d"], ["d","d","d"], ["d","d","d"]] </code></pre> <p>and I want to combine them into a single array like</p> <pre><code>total = [["a","a","a","b","b","b"], ["a","a","a","b","b","b"], ["a","a","a","b","b","b"], ["c","c","c","d","d","d"], ["c","c","c","d","d","d"], ["c","c","c","d","d","d"]] </code></pre> <p>How would I do it?</p> <p><em>I am doing it for spelunky-style map generation</em></p>
2
2016-10-15T13:01:51Z
40,059,601
<p>Assuming, that layout of your map is more complicated than 2x2 blocks:</p> <pre><code>from itertools import chain from pprint import pprint a = [["a","a","a"], ["a","a","a"], ["a","a","a"]] b = [["b","b","b"], ["b","b","b"], ["b","b","b"]] c = [["c","c","c"], ["c","c","c"], ["c","c","c"]] d = [["d","d","d"], ["d","d","d"], ["d","d","d"]] e = [["e","e","e"], ["e","e","e"], ["e","e","e"]] f = [["f","f","f"], ["f","f","f"], ["f","f","f"]] layouts = [ ((a, b), (c, d)), ((a, b, c), (d, e, f)), ((a, b), (c, d), (e, f)), ] for layout in layouts: total = [list(chain(*row)) for lrow in layout for row in zip(*lrow)] pprint(total) </code></pre> <p><strong>output:</strong></p> <pre><code>[['a', 'a', 'a', 'b', 'b', 'b'], ['a', 'a', 'a', 'b', 'b', 'b'], ['a', 'a', 'a', 'b', 'b', 'b'], ['c', 'c', 'c', 'd', 'd', 'd'], ['c', 'c', 'c', 'd', 'd', 'd'], ['c', 'c', 'c', 'd', 'd', 'd']] [['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c'], ['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c'], ['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c'], ['d', 'd', 'd', 'e', 'e', 'e', 'f', 'f', 'f'], ['d', 'd', 'd', 'e', 'e', 'e', 'f', 'f', 'f'], ['d', 'd', 'd', 'e', 'e', 'e', 'f', 'f', 'f']] [['a', 'a', 'a', 'b', 'b', 'b'], ['a', 'a', 'a', 'b', 'b', 'b'], ['a', 'a', 'a', 'b', 'b', 'b'], ['c', 'c', 'c', 'd', 'd', 'd'], ['c', 'c', 'c', 'd', 'd', 'd'], ['c', 'c', 'c', 'd', 'd', 'd'], ['e', 'e', 'e', 'f', 'f', 'f'], ['e', 'e', 'e', 'f', 'f', 'f'], ['e', 'e', 'e', 'f', 'f', 'f']] </code></pre>
2
2016-10-15T13:27:52Z
[ "python", "arrays", "pygame", "concatenation" ]
How to update the parent entity specific field using python in odoo 9
40,059,355
<p>I have a problem on updating the state of the parent table in hr.job table.</p> <p>I inherit 'hr.job' table and i want to update the 'state' field</p> <p>I have a table named: 'job_req_tbl' inherits 'hr_job'</p> <p>Both have same field named 'state'</p> <p>in my web_app screen there is a button named "Confirm" , and when the user click it I want 'hr_job' > 'state' value from 'open' to 'recruit'</p>
0
2016-10-15T13:04:33Z
40,060,019
<p>I have resolved with following code:</p> <pre><code>@api.multi def action_click(self): self.hr_job.state = 'recruit' </code></pre>
0
2016-10-15T14:08:24Z
[ "python", "openerp", "odoo-9", "odoo-view" ]
Theano learning AND gate
40,059,460
<p>I wrote a simple neural network to learn an AND gate. I'm trying to understand why my cost never decreases and the predictors are always 0.5:</p> <pre><code>import numpy as np import theano import theano.tensor as T inputs = [[0,0], [1,1], [0,1], [1,0]] outputs = [[0], [1], [0], [0]] x = theano.shared(value=np.asarray(inputs), name='x') y = theano.shared(value=np.asarray(outputs), name='y') alpha = 0.1 w_array = np.asarray(np.random.uniform(low=-1, high=1, size=(2, 1)), dtype=theano.config.floatX) w = theano.shared(value=w_array, name='w', borrow=True) output = T.nnet.sigmoid(T.dot(x, w)) cost = T.sum((y - output) ** 2) updates = [(w, w - alpha * T.grad(cost, w))] train = theano.function(inputs=[], outputs=[], updates=updates) test = theano.function(inputs=[], outputs=[output]) calc_cost = theano.function(inputs=[], outputs=[cost]) for i in range(60000): if (i+1) % 10000 == 0: print(i+1) print(calc_cost()) train() print(test()) </code></pre> <p>The output is always the same:</p> <pre><code>10000 [array(1.0)] 20000 [array(1.0)] 30000 [array(1.0)] 40000 [array(1.0)] 50000 [array(1.0)] 60000 [array(1.0)] [array([[ 0.5], [ 0.5], [ 0.5], [ 0.5]])] </code></pre> <p>It always seems to predict 0.5 regardless of the input because the cost is not deviating from 1 during learning</p> <p>If I switch the outputs to <code>[[0], [1], [1], [1]]</code> for learning an OR gate, I get the correct predictions, and correctly decreasing cost</p>
1
2016-10-15T13:15:19Z
40,062,160
<p>Your model is of form</p> <pre><code>&lt;w, x&gt; </code></pre> <p>thus it cannot build any separation which <strong>does not cross the origin</strong>. Such equation can only express lines going through point (0,0), and obviously line separating AND gate ((1, 1) from anything else) does not cross the origin. You have to add <strong>bias</strong> term, so your model is</p> <pre><code>&lt;w, x&gt; + b </code></pre>
1
2016-10-15T17:33:34Z
[ "python", "machine-learning", "neural-network", "theano" ]
I need to parse some text and integers from a file
40,059,555
<p>I'm having trouble with a problem I'm trying to do. My goal is to import a file that contains football teams names, and then the number of wins and losses, and then if a team's average is greater than .500, than I have to write that teams name, and average to a new file. And then I have to write the teams under .500 to a seperate file. so far I have my code so that it reads eachline of the file, but I can't figure out how to analyize each line of code. I'm really just looking for any advice I could get at this point, and it would be greatly appreciated.</p> <pre><code>scores = open("fbscores.txt",'r') eachline = scores.readline() while eachline != "": print(eachline) eachline = scores.readline() scores.close() </code></pre>
-1
2016-10-15T13:22:38Z
40,059,624
<p>You are most likely going to end up using the split method, which breaks a string apart into a list element each time it encounters a certain character. Read more here <a href="http://www.pythonforbeginners.com/dictionary/python-split" rel="nofollow">http://www.pythonforbeginners.com/dictionary/python-split</a>. </p>
0
2016-10-15T13:30:06Z
[ "python" ]
I need to parse some text and integers from a file
40,059,555
<p>I'm having trouble with a problem I'm trying to do. My goal is to import a file that contains football teams names, and then the number of wins and losses, and then if a team's average is greater than .500, than I have to write that teams name, and average to a new file. And then I have to write the teams under .500 to a seperate file. so far I have my code so that it reads eachline of the file, but I can't figure out how to analyize each line of code. I'm really just looking for any advice I could get at this point, and it would be greatly appreciated.</p> <pre><code>scores = open("fbscores.txt",'r') eachline = scores.readline() while eachline != "": print(eachline) eachline = scores.readline() scores.close() </code></pre>
-1
2016-10-15T13:22:38Z
40,059,631
<p>You could use a high level library to do so, like <a href="http://pandas.pydata.org" rel="nofollow">pandas</a>.</p> <p>It has many of the functionnalities you want!</p> <pre><code>import pandas as pd df = pd.read_csv('file.csv') print(df) </code></pre>
0
2016-10-15T13:30:36Z
[ "python" ]
I need to parse some text and integers from a file
40,059,555
<p>I'm having trouble with a problem I'm trying to do. My goal is to import a file that contains football teams names, and then the number of wins and losses, and then if a team's average is greater than .500, than I have to write that teams name, and average to a new file. And then I have to write the teams under .500 to a seperate file. so far I have my code so that it reads eachline of the file, but I can't figure out how to analyize each line of code. I'm really just looking for any advice I could get at this point, and it would be greatly appreciated.</p> <pre><code>scores = open("fbscores.txt",'r') eachline = scores.readline() while eachline != "": print(eachline) eachline = scores.readline() scores.close() </code></pre>
-1
2016-10-15T13:22:38Z
40,059,632
<p>Given an example line of the file like this:</p> <pre><code>Cowboys 4 1 </code></pre> <p>Then some code might look like this:</p> <pre><code>line = scores.readline().split() teamName = line[0] wins = int(line[1]) losses = int(line[2]) if wins &gt; losses: print(teamName + "'s record is over .500!") goodTeams.write(line) goodTeams.write() #make a new line else: print(teamName + "'s record is &lt;= .500.") badTeams.write(line) badTeams.write() </code></pre> <p>To find the average of a team with x wins and y losses, do:</p> <pre><code>"%0.3f" % (x/(x+y)) </code></pre> <p>Gives:</p> <pre><code>&gt;&gt;&gt; "%0.3f" % (4/(4+1)) '0.800' &gt;&gt;&gt; </code></pre>
0
2016-10-15T13:30:38Z
[ "python" ]
I need to parse some text and integers from a file
40,059,555
<p>I'm having trouble with a problem I'm trying to do. My goal is to import a file that contains football teams names, and then the number of wins and losses, and then if a team's average is greater than .500, than I have to write that teams name, and average to a new file. And then I have to write the teams under .500 to a seperate file. so far I have my code so that it reads eachline of the file, but I can't figure out how to analyize each line of code. I'm really just looking for any advice I could get at this point, and it would be greatly appreciated.</p> <pre><code>scores = open("fbscores.txt",'r') eachline = scores.readline() while eachline != "": print(eachline) eachline = scores.readline() scores.close() </code></pre>
-1
2016-10-15T13:22:38Z
40,059,646
<p>It's really helpful if you post some lines from your input. According to your description, I assuming each line in your input has the following layout:</p> <pre><code>[NAME] X Y </code></pre> <p>Where, <code>NAME</code> is the team name, <code>X</code> is the number of wins, <code>Y</code>, the number of loses. You can simply split the line by any delimiter (which is 'space' in this example case), </p> <pre><code>eachline = eachline.split() </code></pre> <p>If there was a comma separator, then you do <code>eachline = eachline.split(',')</code> and so on, you get the idea.</p> <p>Then eachline will store a list of the following structure <code>['NAME', X, Y]</code> Then you can access <code>X</code> and <code>Y</code> to average them using: <code>eachline[0]</code> and <code>eachline[1]</code> respectively.</p>
0
2016-10-15T13:32:50Z
[ "python" ]
pycrypto : No module named strxor
40,059,592
<p>I got this error : </p> <p>Traceback (most recent call last): File "test.py", line 8, in from Crypto.Cipher import PKCS1_OAEP File "C:\Users\Mokhles\Downloads\google-api-python-client-1.5.3\Crypto \Cipher\PKCS1_OAEP.py", line 57, in import Crypto.Signature.PKCS1_PSS File "C:\Users\Mokhles\Downloads\google-api-python-client-1.5.3\Crypto \Signature\PKCS1_PSS.py", line 74, in from Crypto.Util.strxor import strxor ImportError: No module named strxor</p> <p>any idea how to solve it?</p> <p>ENV: -windows 10 -python 2.7</p>
0
2016-10-15T13:26:33Z
40,059,658
<p>It looks like you're simply copied pyCrypto into your project. PyCrypto is library which depends on some native library/code (like libtomcrypt). You have to install it properly. You can do this for example through pip:</p> <pre><code>pip2 install pycrypto </code></pre> <p>or</p> <pre><code>pip3 install pycrypto </code></pre> <p>depending on which Python version you want to make it available.</p>
0
2016-10-15T13:34:48Z
[ "python", "pycrypto" ]
Issue with python class in Kodi, trying to write a UI to replace Kodi generic menu with PYXBMCT
40,059,597
<p>I'm quite new to python class's and have not really used them much so please feel free to point out any other errors except the one I point out. </p> <p>What I'm trying to achieve is a new <code>UI in Kodi</code> using the <code>pyxbmct</code> module. I'm sending through a list of things (still yet to work out how I'm going to sort the split to next process with the modes but that's the next task)</p> <p>My Lists are as such:</p> <pre><code>List = [['[COLOR darkgoldenrod][I]Search[/I][/COLOR]','',904,'http://icons.iconarchive.com/icons/icontexto/search/256/search-red-dark-icon.png','','',''], ['[COLOR darkgoldenrod][I]Menu Test[/I][/COLOR]','',905,'http://icons.iconarchive.com/icons/icontexto/search/256/search-red-dark-icon.png','','','']] process.Window_Menu_Class(List) </code></pre> <p>Then obviously being sent through to the Window_Menu_Class() to attempt to display the name(s) in a List and also display a icon to the right but alternating depending on where you are focused in the List. </p> <p>Code for Window_Menu_Class :-</p> <pre><code>import pyxbmct List = [] class Window_Menu_Class(): fanart = 'http://www.wall321.com/thumbnails/detail/20121108/creepy%20video%20games%20castles%20diablo%20tristram%20creep%20diablo%20iii%20sanctuary%201920x1080%20wallpaper_www.wall321.com_92.jpg' iconimage = ICON power = 'http://herovision.x10host.com/fb_replays/power.png' power_focus = 'http://herovision.x10host.com/fb_replays/power_focus.png' text = '0xffffffff' window_menu = pyxbmct.AddonDialogWindow('') Background=pyxbmct.Image(fanart) Icon=pyxbmct.Image('', aspectRatio=2) button = pyxbmct.Button('', noFocusTexture=power,focusTexture=power_focus) window_menu.setGeometry(1250, 650, 100, 50) nameList = pyxbmct.addonwindow.List(_space=11,_itemTextYOffset=0,textColor=text) window_menu.connect(button, window_menu.close) window_menu.connect(pyxbmct.ACTION_NAV_BACK, window_menu.close) window_menu.placeControl(Background, -5, 0, 110, 51) window_menu.placeControl(nameList, 65, 1, 50, 20) window_menu.placeControl(Icon, 30, 30, 60, 18) name_list = []; url_list = []; mode_list = []; iconimage_list = []; fanart_list = []; desc_list = []; extra_list = [] def __init__(self,List): self.Window_Menu(List) def Window_Menu(self,List): for item in List: name = item[0] url = item[1] mode = item[2] iconimage = item[3] fanart = item[4] desc = item[5] extra = item[6] if not name in self.name_list: self.nameList.addItem(name);self.name_list.append(name);self.url_list.append(url);self.mode_list.append(mode);self.iconimage_list.append(iconimage);self.fanart_list.append(fanart);self.desc_list.append(desc);self.extra_list.append(extra) self.create_window(name,url,mode,iconimage,fanart,desc,extra) self.window_menu.doModal() def create_window(self,name,url,mode,iconimage,fanart,desc,extra): self.window_menu.setFocus(self.nameList) self.window_menu.connectEventList( [pyxbmct.ACTION_MOVE_DOWN, pyxbmct.ACTION_MOVE_UP, pyxbmct.ACTION_MOUSE_MOVE], self.LIST_UPDATE(name,url,mode,iconimage,fanart,desc,extra)) def LIST_UPDATE(self,name,url,mode,iconimage,fanart,desc,extra): if self.window_menu.getFocus() == self.nameList: pos=self.nameList.getSelectedPosition() Iconimg=self.iconimage_list[pos] Fanart =self.fanart_list[pos] self.Icon.setImage(Iconimg) self.Background.setImage(Fanart) </code></pre> <p>but I receive the error - </p> <p>File "C:\Users*\AppData\Roaming\Kodi\addons\plugin.video.sanctuary\lib\process.py", line 74, in LIST_UPDATE if self.window_menu.getFocus() == self.nameList: RuntimeError: Non-Existent Control 0</p> <p>If I hash out the <code>if self.window_menu.getFocus() == self.nameList:</code> then it works but, it doesn't alter the image in the list when you move on to the next item, I have a working version but it was all done in one .py file and no need for class at all, however now I am trying to separate the code into different .py files i needed to create a class to contain all the info and give a starting point. Hope this is enough information and appreciate any feedback.</p>
0
2016-10-15T13:27:32Z
40,068,095
<p>Your problem does not have a simple answer because you are doing it wrong at both Python level and PyXBMCt level (I'm the author of PyXBMCt, BTW).</p> <p>First, I strongly recommend you to learn Python classes: how they are defined, how they are initialized, how they are used.</p> <p>When you get that in order, then I strongly recommend to read PyXBMCt documentation which is now hosted here: <a href="http://romanvm.github.io/script.module.pyxbmct/" rel="nofollow">http://romanvm.github.io/script.module.pyxbmct/</a> Look into the examples, including the example plugin, that show how to use PyXBMCt. For example, what is this <code>window_menu.placeControl(Background, -5, 0, 110, 51)</code>? PyXBMCt does not use pixels, it places controls in a grid with rows and columns and you need to set up the grid first.</p> <p>Anyway, I recommend to start with Python stuff first.</p>
0
2016-10-16T07:47:07Z
[ "python", "class", "kodi" ]
how to create empty numpy array to store different kinds of data
40,059,606
<p>I am trying to start with an empty numpy array. As the code progresses the first column should be filled with <code>datetime.datetime</code>, the second column should be filled with <code>str</code>, the third columns with <code>float</code>, and fourth column with <code>int</code>.</p> <p>I tried the following:</p> <pre><code>A = np.empty([10, 4]) A[0][0] = datetime.datetime(2016, 10, 1, 1, 0) </code></pre> <p>I get the error:</p> <pre><code>TypeError: float() argument must be a string or a number </code></pre>
0
2016-10-15T13:28:26Z
40,059,669
<p>You can use <code>dtype=object</code>.</p> <pre><code>A = np.empty([10, 4], dtype=object) A[0][0] = datetime.datetime(2016, 10, 1, 1, 0) </code></pre> <p>It is also possible to use structured arrays, but then you have a fixed length for string objects. If you need arbitrary big objects you have to use <code>dtype=object</code>. But this often contradicts the purpose of arrays.</p>
1
2016-10-15T13:35:46Z
[ "python", "numpy" ]
how to create empty numpy array to store different kinds of data
40,059,606
<p>I am trying to start with an empty numpy array. As the code progresses the first column should be filled with <code>datetime.datetime</code>, the second column should be filled with <code>str</code>, the third columns with <code>float</code>, and fourth column with <code>int</code>.</p> <p>I tried the following:</p> <pre><code>A = np.empty([10, 4]) A[0][0] = datetime.datetime(2016, 10, 1, 1, 0) </code></pre> <p>I get the error:</p> <pre><code>TypeError: float() argument must be a string or a number </code></pre>
0
2016-10-15T13:28:26Z
40,063,004
<p>A structured array approach:</p> <p>define a dtype according to your column specs:</p> <pre><code>In [460]: dt=np.dtype('O,U10,f,i') In [461]: from datetime import datetime </code></pre> <p>Initalize an empty array, with 3 elements (not 3x4)</p> <pre><code>In [462]: A = np.empty((3,), dtype=dt) In [463]: A Out[463]: array([(None, '', 0.0, 0), (None, '', 0.0, 0), (None, '', 0.0, 0)], dtype=[('f0', 'O'), ('f1', '&lt;U10'), ('f2', '&lt;f4'), ('f3', '&lt;i4')]) </code></pre> <p>fill in some values - by field name (not column number)</p> <pre><code>In [464]: A['f1']=['one','two','three'] In [465]: A['f0'][0]=datetime(2016, 10, 1, 1, 0) In [467]: A['f2']=np.arange(3) In [468]: A Out[468]: array([(datetime.datetime(2016, 10, 1, 1, 0), 'one', 0.0, 0), (None, 'two', 1.0, 0), (None, 'three', 2.0, 0)], dtype=[('f0', 'O'), ('f1', '&lt;U10'), ('f2', '&lt;f4'), ('f3', '&lt;i4')]) </code></pre> <p>View on element of this array:</p> <pre><code>In [469]: A[0] Out[469]: (datetime.datetime(2016, 10, 1, 1, 0), 'one', 0.0, 0) </code></pre> <p>I chose to make the 1st field <code>object</code> dtype, so it can hold a <code>datetime</code> object - which isn't a number or string.</p> <p><code>np.datetime64</code> stores a date as a float, and provides a lot of functionality that <code>datetime</code> objects don't:</p> <pre><code>In [484]: dt1=np.dtype('datetime64[s],U10,f,i') In [485]: A1 = np.empty((3,), dtype=dt1) In [486]: A1['f0']=datetime(2016, 10, 1, 1, 0) In [487]: A1['f3']=np.arange(3) In [488]: A1 Out[488]: array([(datetime.datetime(2016, 10, 1, 1, 0), '', 0.0, 0), (datetime.datetime(2016, 10, 1, 1, 0), '', 0.0, 1), (datetime.datetime(2016, 10, 1, 1, 0), '', 0.0, 2)], dtype=[('f0', '&lt;M8[s]'), ('f1', '&lt;U10'), ('f2', '&lt;f4'), ('f3', '&lt;i4')]) </code></pre> <p>A third approach is to make the whole array object dtype. That's effectively a glorified list. Many operations resort to plain iteration, or just aren't implemented. It's more general but you loose a lot of the power of normal numeric arrays.</p>
1
2016-10-15T18:57:30Z
[ "python", "numpy" ]
Match path but not os.path
40,059,607
<p>I want to match the string <code>path</code> but not the string <code>os.path</code>. How do I go about that ? Tried <a href="http://stackoverflow.com/questions/2953039/regular-expression-for-a-string-containing-one-word-but-not-another"><code>(?!(os\.path))\bpath\b</code></a> but I still get all <code>os.path</code>S</p>
0
2016-10-15T13:28:28Z
40,059,729
<p>You can use a look-behind based regex, like</p> <pre><code>(?&lt;!os\.)\bpath\b </code></pre> <p>This basically matches the exact word <code>path</code> and ensures that it is not preceded by <code>os.</code> If you want to avoid similar constructs, like <code>sys.path</code> or <code>xx.path</code> you could use <code>(?&lt;!\w\.)</code> as look-behind instead.</p> <p>See the <a href="https://regex101.com/r/vkvKO2/1" rel="nofollow">regex101 demo</a>.</p>
1
2016-10-15T13:41:03Z
[ "python", "regex", "python-2.7" ]
Match path but not os.path
40,059,607
<p>I want to match the string <code>path</code> but not the string <code>os.path</code>. How do I go about that ? Tried <a href="http://stackoverflow.com/questions/2953039/regular-expression-for-a-string-containing-one-word-but-not-another"><code>(?!(os\.path))\bpath\b</code></a> but I still get all <code>os.path</code>S</p>
0
2016-10-15T13:28:28Z
40,059,838
<p>If you want to skip any <code>path</code> starting with <code>.</code> try</p> <p><code>(?&lt;!\.)path</code></p> <p>This will skip <code>sys.path</code> or <code>os.path</code> but will match <code>path</code>.</p> <p>e.g. if test strings is <code>if path and not os.path.sep in path</code>,</p> <p>match will be:</p> <p>if <code>path</code> and not os.path.sep in <code>path</code></p> <p>See demo at <a href="https://regex101.com/r/5WM8A1/1" rel="nofollow">regex101</a></p>
0
2016-10-15T13:49:45Z
[ "python", "regex", "python-2.7" ]
'module' object has no attribute 'corrplot'
40,059,642
<pre><code>import seaborn as sns import matplotlib.pyplot as plt sns.corrplot(rets,annot=False,diag_names=False) </code></pre> <p>I get this error after I call the function above...don't know whats going on</p> <pre><code>AttributeError Traceback (most recent call last) &lt;ipython-input-32-33914bef0513&gt; in &lt;module&gt;() ----&gt; 1 sns.corrplot(rets,annot=False,diag_names=False) AttributeError: 'module' object has no attribute 'corrplot' </code></pre>
0
2016-10-15T13:32:30Z
40,059,701
<p>The <code>corrplot</code> function was deprecated in seaborn version v0.6: <a href="https://seaborn.github.io/whatsnew.html#other-additions-and-changes" rel="nofollow">https://seaborn.github.io/whatsnew.html#other-additions-and-changes</a></p> <p>Note that the function actually still exists in the seaborn codebase, but you have to directly import it from <code>seaborn.linearmodels</code> and you will get a warning that it is subject to removal in a future release.</p>
1
2016-10-15T13:38:43Z
[ "python", "seaborn" ]
How can I select and order items based on a subquery?
40,059,682
<p>I have the following models in Django:</p> <pre><code>class Author(models.Model): name = models.CharField(max_length=100) age = models.IntegerField() country = models.ForeignKey(Country) class Book(models.Model): name = models.CharField(max_length=300) pages = models.IntegerField() price = models.DecimalField(max_digits=10, decimal_places=2) rating = models.FloatField() authors = models.ForeignKey(Author) pubdate = models.DateField() </code></pre> <p>How can I get a queryset of Authors sorted by the first time they published a book?</p> <p>In SQL, I could do this using:</p> <pre><code>SELECT * FROM ( SELECT author_id , MIN(pubdate) as date FROM books GROUP BY author_id HAVING MIN(pubdate)) AS first_published JOIN author ON author.id = first_published.author_id LIMIT 15 OFFSET 15 ORDER BY first_published.author_id </code></pre> <p>It's been a while with Django and I haven't been able to figure out how to do this.</p> <hr> <p>Now this is just nasty:</p> <pre><code>from django.db.models.sql.compiler import SQLCompiler _quote_name_unless_alias = SQLCompiler.quote_name_unless_alias SQLCompiler.quote_name_unless_alias = lambda self,name: name if name.startswith('(') else _quote_name_unless_alias(self,name) subquery = "(SELECT author_id, MIN(pubdate) as first_release_date FROM app_books GROUP BY author_id HAVING MIN(pubdate)) AS releases" condition = "releases.author_id = app_authors.id" order = '-releases.first_release_date' Author.objects.get_queryset().extra(tables=[subquery], where=[condition]).order_by(order) </code></pre>
0
2016-10-15T13:36:55Z
40,060,051
<p>Try this</p> <pre><code>Author.objects.all().annotate(s=Min('book__pubdate')).order_by('s') </code></pre> <p>When if some author dont have books</p> <pre><code>Author.objects.exclude(book__pubdate__isnull=True).annotate(s=Min('book__pubdate')).order_by('s') </code></pre>
1
2016-10-15T14:11:10Z
[ "python", "sql", "django", "django-models", "django-orm" ]
Using Dictionary with list manipulation
40,059,862
<p>How do you use dictionary to find the index in the elements of the list however it should return the index of the same element.</p>
0
2016-10-15T13:52:53Z
40,059,899
<p>This will work :</p> <pre><code> text = "I like cheese bcoz cheese in great" hash = {} words = text.split(" ") for i in range(1:len(words)): word = words[i] if word not in hash.keys(): hash[word] = i for word in words: print hash[word] </code></pre>
0
2016-10-15T13:55:54Z
[ "python" ]
Using Dictionary with list manipulation
40,059,862
<p>How do you use dictionary to find the index in the elements of the list however it should return the index of the same element.</p>
0
2016-10-15T13:52:53Z
40,059,919
<p>Try this:</p> <pre><code>l = "I like cheese because cheese is great".split() d = {} count = 0 for word in l: if word not in d.keys(): count += 1 d[i] = count for word in l: print(d[word], end=",") print() </code></pre>
0
2016-10-15T13:58:05Z
[ "python" ]
Using Dictionary with list manipulation
40,059,862
<p>How do you use dictionary to find the index in the elements of the list however it should return the index of the same element.</p>
0
2016-10-15T13:52:53Z
40,060,088
<p>This is an alternative:</p> <pre><code>text = "I like cheese because cheese is great" d = {v:k for k,v in enumerate(text.split(), 1)} print(d) </code></pre>
0
2016-10-15T14:14:54Z
[ "python" ]
Import settings from the file
40,059,890
<p>I would like to import settings from a yaml file, but make them available as regular variables in the current context.</p> <p>for example I may have a file:</p> <pre><code>param1: 12345 param2: test11 param3: a: 4 b: 7 c: 9 </code></pre> <p>And I would like to have variables <code>param1</code>, <code>param2</code>, <code>param3</code> in my code.</p> <p>I may want to use this from any function and do not want to have them available globally.</p> <p>I have heard about <code>locals()</code> and <code>globals()</code> functuons, but did not get how to use them for this.</p>
4
2016-10-15T13:55:06Z
40,059,917
<p>You can use <code>locals()['newvarname'] = 12345</code> to create a new variable. And you can just read your file and fill in this structure as you'd like.</p> <p>You may write a function to call it and import settings:</p> <pre><code>import sys import yaml def get_settings(filename): flocals = sys._getframe().f_back.f_locals # get locals() from caller with open(filename, 'r') as ysfile: ydata = yaml.load(ysfile.read()) for pname in ydata: # assume the yaml file contains dict flocals[pname] = ydata[pname] # merge caller's locals with new vars </code></pre>
0
2016-10-15T13:57:40Z
[ "python", "yaml" ]
Import settings from the file
40,059,890
<p>I would like to import settings from a yaml file, but make them available as regular variables in the current context.</p> <p>for example I may have a file:</p> <pre><code>param1: 12345 param2: test11 param3: a: 4 b: 7 c: 9 </code></pre> <p>And I would like to have variables <code>param1</code>, <code>param2</code>, <code>param3</code> in my code.</p> <p>I may want to use this from any function and do not want to have them available globally.</p> <p>I have heard about <code>locals()</code> and <code>globals()</code> functuons, but did not get how to use them for this.</p>
4
2016-10-15T13:55:06Z
40,060,005
<p>Even though the trick is great in @baldr's answer, I suggest moving the variable assignments out of the function for better readability. Having a function change its caller's context seems very hard to remember and maintain. So, </p> <pre><code>import yaml def get_settings(filename): with open(filename, 'r') as yf: return yaml.load(yf.read()) def somewhere(): locals().update(get_settings('foo.yaml')) print(param1) </code></pre> <p>Even then I would strongly suggest simply using the dictionary. Otherwise, you risk very strange bugs. For instance, what if your yaml file contains a <code>open</code> or a <code>print</code> key? They will override python's functions, so the <code>print(param1)</code> in the example will raise a <code>TypeError</code> exception.</p>
1
2016-10-15T14:07:13Z
[ "python", "yaml" ]
Changing path for running Python code via Java
40,059,893
<p>I implemented Python app, and Java app. Let's assume that my Python app is returned True as a result.</p> <p>I would like to run Python app via Java app, receive the results from Python app into my Java app and make additional calculations in my Java app.</p> <p>I use Process in Java for this mission. In my example the Python app is running with config.ini file as a parameter.</p> <pre><code>String path = "C:\\Python_Project\\run_app.py configuration\\config.ini"; Process p = Runtime.getRuntime().exec("python " + path); </code></pre> <p>It is not working. The Java app is not failed by I do not receive anything interesting from Python app. </p> <p>I decided to run it via Command Prompt and found that the run is failed because in one of my internal files I used import like this: from inner_module import Object1</p> <p>Maybe is this the problem? I should run it from Python app directory? But how?</p> <p>I have two questions:</p> <ol> <li><p>Is it a way to change the path for running my python app? I run the Java app from my Java app directory and I have to run the Python app inside the Python app directory?How can I change the perspective? </p></li> <li><p>Is the use of Process and exec is good? Should I use something else? How I can use the Process for getting the True value Python app sent?</p></li> </ol>
0
2016-10-15T13:55:19Z
40,063,861
<p>You can try <a href="https://docs.oracle.com/javase/7/docs/api/java/lang/ProcessBuilder.html" rel="nofollow">ProcessBuilder</a> which allows you to set the working directory. Something like:</p> <pre><code>ProcessBuilder pb = new ProcessBuilder(program, argument); pb.directory(new File("path/to/python/directory")); Process process = pb.start(); </code></pre> <p>You can obtain the script's output by reading from process.getInputStream()</p> <pre><code>BufferedReader reader = new BufferedReader( new InputStreamReader(process.getIntputStream())); String output; while((output=reader.readLine()) != null) System.out.println(output); </code></pre>
0
2016-10-15T20:26:18Z
[ "java", "python" ]
Django - Delay in creating database entry
40,059,955
<p>I have a Django app where I create a db entry in the view. I then want to perform background processing on the new entry. Instead of sending the created object to the task, I send the object's id then the background task can fetch the db object as explained <a href="http://stackoverflow.com/questions/15079176/should-django-model-object-instances-be-passed-to-celery">here</a>. Below is my code:</p> <pre><code># In tasks.py @shared_task def my_task(model_id): my_model = MyModel.objects.get(pk=model_id) # Do stuff with my_model # In views.py: def some_view(request): if request.method == 'POST' and request.is_ajax(): instance = MyModel.objects.create(**kwargs) tasks.my_task.delay(instance.id) .... </code></pre> <p>However, when I try to get the object in the background task, I get <em>matching query does not exist</em> error. If I add <code>sleep(1)</code> before getting the object, it works as excepted. I do not understand why I'm getting this error, since the object should be in the DB? Does anybody know how to solve this? I don't really want to add a sleep command everywhere.</p> <p>I'm using Postgres as my DB.</p>
0
2016-10-15T14:02:16Z
40,060,305
<p>Try this</p> <pre><code>from django.db import transaction with transaction.atomic(): instance = MyModel.objects.create(**kwargs) tasks.my_task.delay(instance.id) </code></pre>
2
2016-10-15T14:33:25Z
[ "python", "django", "postgresql" ]
Mean tensor product
40,059,979
<p>I have another question which is related to my last problem( <a href="http://stackoverflow.com/questions/40044714/python-tensor-product">Python tensor product</a>). There I found a mistake in my calculation. With np.tensordot I am calculating the following equation: <a href="https://i.stack.imgur.com/pykbw.png" rel="nofollow"><img src="https://i.stack.imgur.com/pykbw.png" alt="enter image description here"></a> &lt;..> should display the average. In python code it does look like this (ewp is a vector and re a tensor): </p> <pre><code>q1 = numpy.tensordot(re, ewp, axes=(1, 0)) q2 = numpy.tensordot(q1, ewp, axes=(1, 0)) serc = q2 ** 2 </code></pre> <p>or</p> <pre><code>serc = numpy.einsum('im, m -&gt; i', numpy.einsum('ilm, l -&gt; im', numpy.einsum('iklm, k -&gt; ilm', numpy.einsum('ijklm, j -&gt; iklm', numpy.einsum('ijk, ilm -&gt; ijklm', re, re), ewp), ewp), ewp), ewp) </code></pre> <p>Now in both python codes I neglect, that all possibilities are multiplied. But of course <code>w_j</code> and <code>w_k</code> are not independent for <code>j=k</code>. In the case, that only j and k are the same we get <code>&lt; w_j*w_j*w_l*w_m&gt; = &lt;w_j&gt;*&lt;w_l&gt;*&lt;w_m&gt;</code>. For <code>j=k=l</code> we get: <code>&lt; w_j*w_j*w_j*w_m&gt; = &lt;w_j&gt;*&lt;w_m&gt;</code>. For <code>j=k=l=m</code>: <code>&lt; w_j*w_j*w_j*w_j&gt; = &lt;w_j&gt;</code>. Only if all variable are different, independence is true and we get: <code>&lt; w_i*w_j*w_l*w_m&gt; = &lt;w_i&gt;*&lt;w_j&gt;*&lt;w_l&gt;*&lt;w_m&gt;</code>. Now this is what the code does for all possibilities. I hope this makes my problem understandable. Now my question is how can I represent this in my code? </p> <p>Edit: An idea that I have is to first create a 4dim. tensor which represents <code>&lt;w_j w_k w_l w_m&gt;</code>:</p> <pre><code>wtensor = numpy.einsum('jkl, m -&gt; jklm', numpy.einsum('jk, l -&gt; jkl', numpy.einsum('j, k -&gt; jk', ewp, ewp), ewp), ewp) </code></pre> <p>Then I need to change the values which are not idependent. I assume they should be on a diagonal? But I really don't know so much about tensor calculus, so at this point I am struggling. After manipulating the w tensor I would get the result by performing:</p> <pre><code>serc = numpy.einsum('ijklm, jklm -&gt; i', numpy.einsum('ijk, ilm -&gt; ijklm', re, re), wtensor) </code></pre> <p>Edit2: In another post I asked precisely how I can manipulate the 4dim so that it does fit here. Divakar had a really nice solution which can be seen here: <a href="http://stackoverflow.com/questions/40063034/fill-a-multidimensional-array-efficiently-that-have-many-if-else-statements">Fill a multidimensional array efficiently that have many if else statements</a></p> <pre><code>from itertools import product n_dims = 4 # Number of dims # Create 2D array of all possible combinations of X's as rows idx = np.sort(np.array(list(product(np.arange(gn), repeat=n_dims))),axis=1) # Get all X's indexed values from ewp array vals = ewp[idx] # Set the duplicates along each row as 1s. With the np.prod coming up next, #these 1s would not affect the result, which is the expected pattern here. vals[:,1:][idx[:,1:] == idx[:,:-1]] = 1 # Perform product along each row and reshape into multi-dim array out = vals.prod(1).reshape([gn]*n_dims) </code></pre> <p>The array which I am getting here is <code>wtensor</code> which I now can use in the code above:</p> <pre><code>serc = numpy.einsum('ijklm, jklm -&gt; i', numpy.einsum('ijk, ilm -&gt; ijklm', re, re), wtensor) </code></pre> <p>This gives me finally the result which I wanted and basically answers the question. Although there is one problem. The lenght of ewp which then also defines the size of the tensors shouldn't be larger then 6. Otherwise the code will use a lot of memory. My intention was to use it until a size of 8, so that is unfortunately now my next problem. </p>
1
2016-10-15T14:04:55Z
40,069,485
<p>Well you can do that efficiently with a combination of <code>np.tensordot</code> and <code>np.einsum</code>, like so -</p> <pre><code>serc = np.einsum('ilm,ilm-&gt;i',re,np.tensordot(re,wtensor,axes=[(1,2),(0,1)])) </code></pre>
1
2016-10-16T10:57:53Z
[ "python", "numpy", "numpy-einsum" ]