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
listlengths
1
5
Retrieve yum repos and save as list in json format
38,748,692
<p>I am new to the site and have just started with Python. I am trying to think how to begin working on this problem...basically I need Python to retrieve a list of all yum repos in /etc/yum.repos.d and then save the list in a json format such as below:</p> <pre><code>{ "[repo_name]" : { "name" : "repo_name", "baseurl" : "http://example.com", "enabled" : "1", "gpgcheck" : "0" } "[next_repo]... } </code></pre> <p>I managed to get something working, but it doesn't really do what it was intended to do. Here is the code I have:</p> <pre><code>#!/usr/bin/python import json mylist = [] lines = open('/etc/yum.repos.d/repo_name.repo').read().split('\n') for line in lines: if line.strip() != '': if '[' in line: mylist.append("{") repo_name = line.translate(None,'[]') mylist.append(repo_name + ':') mylist.append("{") elif 'gpgcheck' in line: left, right = line.split('=') mylist.append(left + ':' + right) mylist.append("}") else: left, right = line.split('=') mylist.append(left + ':' + right) out_file = open('test.json','w') out_file.write(json.dumps(mylist)) out_file.close() </code></pre> <p>And here is what it returns:</p> <pre><code>["{", "repo_name:", "{", "name:repo_name", "baseurl:http://www.example.com", "enabled:1", "gpgcheck:0", "}"] </code></pre> <p>I haven't coded in for multiple repos yet, since I just wanted to get one working first. Am I approaching this correctly or is there a better way? OS is RHEL and python version is 2.6.6. Any help is greatly appreciated!</p>
0
2016-08-03T16:09:09Z
38,750,213
<p>This a example file structure</p> <pre><code>[examplerepo] name=Example Repository baseurl=http://mirror.cisp.com/CentOS/6/os/i386/ enabled=1 gpgcheck=1 gpgkey=http://mirror.cisp.com/CentOS/6/os/i386/RPM-GPG-KEY-CentOS-6 </code></pre> <p>And this is a code I used</p> <pre><code>#!/usr/bin/python import json test_dict = dict() lines = open('test', 'r').read().split('\n') current_repo = None for line in lines: if line.strip() != '': if '[' in line: current_repo = line test_dict[current_repo] = dict() else: k, v = line.split("=") test_dict[current_repo][k] = v out_file = open('test.json', 'w') out_file.write(json.dumps(test_dict)) out_file.close() </code></pre> <p>I think that using dictionaries is more natural way to do this.</p>
0
2016-08-03T17:32:06Z
[ "python" ]
Convert RGB to HSV using [0, 255] range
38,748,737
<p>I have an RGB image that I want to convert to the HSV colorspace. The RGB values in the image array have a range of 0 to 255. However, almost all of the colorspace conversion functions out there require the data to have a range of 0 to 1. </p> <p>Is there anyway to get around this (short of writing my own conversion function)? If not, what is the fastest way to change the data range from 0, 255 to 0, 1 (the array dimensions vary but are typically [1000, 1000, 3]) </p>
-1
2016-08-03T16:10:48Z
38,748,994
<p>You can use <code>preprocessing.MinMaxScaler()</code> from <code>scikit-learn</code>. </p> <p>Here is link for more <a href="http://scikit-learn.org/stable/modules/preprocessing.html" rel="nofollow">information</a> and examples. </p>
1
2016-08-03T16:23:47Z
[ "python", "image", "rgb", "python-3.5", "hsv" ]
Nesting classes 3 levels deep within Python - Is it bad practice?
38,748,749
<p>I'm working on a Python script at work that is used to interact with XLS/XLSX/CSV spreadsheets. There are three main classes which are nested inside one another (<strong>not</strong> extending one another, the classes are literally inside the other class)</p> <p>The three primary classes are explained below:</p> <ol> <li>The primary <code>Workbook</code> class, which is a factory method for the XLS/XLSX/CSV classes. This is accessible externally</li> <li>The private <code>__Worksheet</code> class within the <code>Workbook</code> class, which is used to open a specific spreadsheet or worksheet within the file itself. This is accessible only via the <code>Workbook.worksheet()</code> method</li> <li>The private <code>__Cell</code> class within the <code>__Worksheet</code> class, which interacts with the cells themselves. This shouldn't be accessible externally, rather only accessible via the <code>__Worksheet</code> class</li> </ol> <p>Heres a simplified version of the class structures thus far:</p> <pre class="lang-py prettyprint-override"><code>class Workbook( object ): def __init__( self, file_name ): self.__file_name = file_name def worksheet( self, name ): return self.__Worksheet( self, name ) class __Worksheet(): def __init__( self, workbook, worksheet ): self.__workbook = workbook def cell( self, cell_id, data = None ): return self.__Cell( cell_id, data ) class __Cell(): def __init__( self, cell, data = None ): self.__cell = cell self.__data = data def setVal( self, data ): self.__data = data def __str__( self ): return self.__data workbook = Workbook( 'test-file.csv' ) worksheet = workbook.worksheet( 'First Worksheet' ) cell_A1 = worksheet.cell('A1', 'Foo...') print("Before - Cell A1: %s" % cell_A1) # =&gt; Before - Cell A1: Foo... cell_A1.setVal('Bar...') print("After - Cell A1: %s" % cell_A1) # =&gt; Before - After - Cell A1: Bar... </code></pre> <p>So the question I have is - Is it considered bad practice to have a class within a class, within a class? </p> <p>I'm somewhat new to Python, my experience is mostly PHP/JS/Perl. It doesn't seem too uncommon in Python to have a class within a class, but for some reason, nesting a class 3 levels deep just seems wrong. If it is, and there's a better way to do it, then that would be great. </p> <p>I know the alternative is to <em>not</em> nest the classes, and just check if an instance of <code>Workbook</code> is given to <code>Worksheet</code> as a parameter. Then create a method in <code>Workbook</code> which just returns an instance if <code>Worksheet</code>, while handing <code>self</code> as one of the parameters used to initiate it.</p> <p>Example:</p> <pre class="lang-py prettyprint-override"><code>class Workbook( object ): def __init__( self, file_name ): self.__file_name = file_name def worksheet( self, name ): return self.Worksheet( self, name ) class Worksheet( object ): def __init__( self, workbook, worksheet = 0 ): if not isinstance( workbook, Workbook ): raise Exception( 'Expected the workbook to be an instance of the Workbook class' ) self.__workbook = workbook def cell( self, cell_id, data = None ): return self.Cell( cell_id, data ) class Cell( object ): def __init__( self, worksheet, cell, data = None ): if not isinstance( worksheet, Worksheet ): raise Exception( 'Expected the worksheet to be an instance of the Worksheet class' ) self.__cell = cell self.__data = data def setVal( self, data ): self.__data = data def __str__( self ): return self.__data # Example Usage One workbook = Workbook( 'test-file.xls' ) worksheet = workbook.worksheet( 'First Worksheet' ) cell_A1 = worksheet.cell('A1', 'Foo...') print("Before - Cell A1: %s" % cell_A1) # =&gt; Before - Cell A1: Foo... cell_A1.setVal('Bar...') print("After - Cell A1: %s" % cell_A1) # =&gt; Before - After - Cell A1: Bar... # Example Usage Two workbook = Workbook( 'test-file.xlsx' ) worksheet = Worksheet( workbook, 'First Worksheet' ) cell_A1 = Cell( worksheet, 'A1', 'Foo...') print("Before - Cell A1: %s" % cell_A1) # =&gt; Before - Cell A1: Foo... cell_A1.setVal('Bar...') print("After - Cell A1: %s" % cell_A1) # =&gt; Before - After - Cell A1: Bar... # Failed Example worksheet = Worksheet( 'Not worksheet', 1 ) # =&gt; Exception, as expected </code></pre> <p>However, this alternative means that the <code>Worksheet</code> and <code>Cell</code> classes are accessible externally and can be initiated manually... but I guess thats not a terrible thing.</p> <p>Let me know what you think the best route is! One of the comments on this post provides a link to <a href="http://stackoverflow.com/questions/719705/what-is-the-purpose-of-pythons-inner-classes">another SO post</a>, in which a user posts 3 advantages of nesting classes, the first of which is:</p> <blockquote> <p>Logical grouping of classes: If a class is useful to only one other class then it is logical to embed it in that class and keep the two together. Nesting such "helper classes" makes their package more streamlined.</p> </blockquote> <p>Which is exactly what I was thinking. I just thought it was somewhat awkward nesting them to 3 layers, as I've only done 2 before.</p>
-1
2016-08-03T16:11:34Z
38,748,975
<p>Turning your question around: is there any advantage in writing the classes as nested? Unlike functions, classes don't use "lexical scoping" (<em>i.e.</em> unlike functions, a name that can't be resolved from the current class's namespace will not be resolved from surrounding classes). This is why you have to refer to the <code>__Worksheet</code> class relative to an instance of <code>Workbook</code>.</p> <p>This in turn means that there is no perceptible advantage to the nesting that you have employed, though it will work. Most experienced Python programmers would probably write your example without using nesting. This simplifies the code (because the class names are all global to the containing module).</p> <p>Note that this is quite different from declaring a class inside a function body. In that case the code of the class can refer to variables from the function's namespace, and Python goes to great lengths to ensure that those references are still available to the class even after the function call has terminated and the local namespace associated with the call has been destroyed.</p>
3
2016-08-03T16:22:50Z
[ "python", "class", "oop", "subclass" ]
Nesting classes 3 levels deep within Python - Is it bad practice?
38,748,749
<p>I'm working on a Python script at work that is used to interact with XLS/XLSX/CSV spreadsheets. There are three main classes which are nested inside one another (<strong>not</strong> extending one another, the classes are literally inside the other class)</p> <p>The three primary classes are explained below:</p> <ol> <li>The primary <code>Workbook</code> class, which is a factory method for the XLS/XLSX/CSV classes. This is accessible externally</li> <li>The private <code>__Worksheet</code> class within the <code>Workbook</code> class, which is used to open a specific spreadsheet or worksheet within the file itself. This is accessible only via the <code>Workbook.worksheet()</code> method</li> <li>The private <code>__Cell</code> class within the <code>__Worksheet</code> class, which interacts with the cells themselves. This shouldn't be accessible externally, rather only accessible via the <code>__Worksheet</code> class</li> </ol> <p>Heres a simplified version of the class structures thus far:</p> <pre class="lang-py prettyprint-override"><code>class Workbook( object ): def __init__( self, file_name ): self.__file_name = file_name def worksheet( self, name ): return self.__Worksheet( self, name ) class __Worksheet(): def __init__( self, workbook, worksheet ): self.__workbook = workbook def cell( self, cell_id, data = None ): return self.__Cell( cell_id, data ) class __Cell(): def __init__( self, cell, data = None ): self.__cell = cell self.__data = data def setVal( self, data ): self.__data = data def __str__( self ): return self.__data workbook = Workbook( 'test-file.csv' ) worksheet = workbook.worksheet( 'First Worksheet' ) cell_A1 = worksheet.cell('A1', 'Foo...') print("Before - Cell A1: %s" % cell_A1) # =&gt; Before - Cell A1: Foo... cell_A1.setVal('Bar...') print("After - Cell A1: %s" % cell_A1) # =&gt; Before - After - Cell A1: Bar... </code></pre> <p>So the question I have is - Is it considered bad practice to have a class within a class, within a class? </p> <p>I'm somewhat new to Python, my experience is mostly PHP/JS/Perl. It doesn't seem too uncommon in Python to have a class within a class, but for some reason, nesting a class 3 levels deep just seems wrong. If it is, and there's a better way to do it, then that would be great. </p> <p>I know the alternative is to <em>not</em> nest the classes, and just check if an instance of <code>Workbook</code> is given to <code>Worksheet</code> as a parameter. Then create a method in <code>Workbook</code> which just returns an instance if <code>Worksheet</code>, while handing <code>self</code> as one of the parameters used to initiate it.</p> <p>Example:</p> <pre class="lang-py prettyprint-override"><code>class Workbook( object ): def __init__( self, file_name ): self.__file_name = file_name def worksheet( self, name ): return self.Worksheet( self, name ) class Worksheet( object ): def __init__( self, workbook, worksheet = 0 ): if not isinstance( workbook, Workbook ): raise Exception( 'Expected the workbook to be an instance of the Workbook class' ) self.__workbook = workbook def cell( self, cell_id, data = None ): return self.Cell( cell_id, data ) class Cell( object ): def __init__( self, worksheet, cell, data = None ): if not isinstance( worksheet, Worksheet ): raise Exception( 'Expected the worksheet to be an instance of the Worksheet class' ) self.__cell = cell self.__data = data def setVal( self, data ): self.__data = data def __str__( self ): return self.__data # Example Usage One workbook = Workbook( 'test-file.xls' ) worksheet = workbook.worksheet( 'First Worksheet' ) cell_A1 = worksheet.cell('A1', 'Foo...') print("Before - Cell A1: %s" % cell_A1) # =&gt; Before - Cell A1: Foo... cell_A1.setVal('Bar...') print("After - Cell A1: %s" % cell_A1) # =&gt; Before - After - Cell A1: Bar... # Example Usage Two workbook = Workbook( 'test-file.xlsx' ) worksheet = Worksheet( workbook, 'First Worksheet' ) cell_A1 = Cell( worksheet, 'A1', 'Foo...') print("Before - Cell A1: %s" % cell_A1) # =&gt; Before - Cell A1: Foo... cell_A1.setVal('Bar...') print("After - Cell A1: %s" % cell_A1) # =&gt; Before - After - Cell A1: Bar... # Failed Example worksheet = Worksheet( 'Not worksheet', 1 ) # =&gt; Exception, as expected </code></pre> <p>However, this alternative means that the <code>Worksheet</code> and <code>Cell</code> classes are accessible externally and can be initiated manually... but I guess thats not a terrible thing.</p> <p>Let me know what you think the best route is! One of the comments on this post provides a link to <a href="http://stackoverflow.com/questions/719705/what-is-the-purpose-of-pythons-inner-classes">another SO post</a>, in which a user posts 3 advantages of nesting classes, the first of which is:</p> <blockquote> <p>Logical grouping of classes: If a class is useful to only one other class then it is logical to embed it in that class and keep the two together. Nesting such "helper classes" makes their package more streamlined.</p> </blockquote> <p>Which is exactly what I was thinking. I just thought it was somewhat awkward nesting them to 3 layers, as I've only done 2 before.</p>
-1
2016-08-03T16:11:34Z
38,767,304
<p>Setting aside some of the questions raised elsewhere, like whether you need all these classes, I'm going to say no: it's better not to nest these classes. It's better to merely document how they are intended to be used. Consider alternate names that make the classes themselves less attractive, for example WorksheetReference and CellReference. Throw in a few docstrings, even if they just say things like:</p> <blockquote> <p>WorksheetReference is not meant to be instantiated directly. You should access it through the worksheet() method of a Workbook.</p> </blockquote> <p>The rest of this answer will examine why.</p> <p><strong>What are the costs and benefits of nesting?</strong></p> <p>Nesting the classes in your case really only provides additional nesting. This makes it harder to talk about the classes that are nested: it's not a <code>Worksheet</code>, it's a <code>Workbook.__Worksheet</code> (really it's a <code>Workbook._Workbook__Worksheet</code>, but that's even more cumbersome to talk about). Since it's harder to talk about, it's harder to document the interface so someone knows how to use what comes back from a call to <code>myworkbook.worksheet</code>. Would your docs say "returns an object with a cells method" or "returns a Workbook.__Worksheet object" or take a different approach entirely?</p> <p>None of this nesting prevents someone from trying to instantiate the class by poking around. Thus if you are truly concerned with preventing "misuse", you would still need to check the values passed to the worksheet's <code>__init__</code> function (more on this later).</p> <p><strong>Why do you care about enforcing your usage pattern?</strong></p> <p>One of python's principles is that of "<a href="https://mail.python.org/pipermail/tutor/2003-October/025932.html" rel="nofollow">consenting adults</a>". Namely we're better off showing and documenting the right way to use something, and trusting that people won't subvert it without good reason. If there's no benefit to creating a Worksheet without a Workbook, or a Cell without a Worksheet, then nobody will bother.</p> <p>Another principle is that of <a href="http://stackoverflow.com/questions/4205130/what-is-duck-typing">duck typing</a>. This is largely the idea that it's beneficial to allow programming to loosely specified interfaces. If someone wants to make a class that implements enough of the methods of Workbook, it's often good enough to be used wherever a Workbook instance could be used. Even if it does something very different internally. Combined with consenting adults, this suggests it can be beneficial to let someone try to do this. Both nesting and type-based verification in the <code>__init__</code> method fight against this.</p> <p><strong>Attempting to prevent misuse</strong></p> <p>As I just covered, I don't generally recommend doing this at all. However if you do, you should do it well. The proposed check in your alternate <code>__init__</code> functions is extra troublesome, as it encourages a bad practice. Since it throws an exception of type <code>Exception</code>, the only way to catch it is to catch <em>all</em> exceptions. Instead, since you are verifying the type of an argument, you should consider throwing a more specific exception like <code>TypeError</code>, or perhaps (in a larger body of code) even a custom subclass thereof.</p> <p><strong>Additional tweaks to the approach</strong></p> <p>I agree with a comment that asked why <code>Worksheet</code> and <code>Cells</code> exist at all. As is, there's very little benefit to having the helper class; it could make sense for the helper classes to be implementation details, or possibly omitted entirely. To make it simpler to document such an implementation detail, you may want to consider implementing one or both of them via <code>__getitem__</code> and/or <code>__setitem__</code>, enabling code that looks like this:</p> <pre><code>worksheet = workbook['First Worksheet'] worksheet['A1'] = 'Foo...' </code></pre> <p>I'm making the assumption that in your real code, they will have a lot more functionality than the methods you've already shown. You may still want to consider <code>__getitem__</code> and/or <code>__setitem__</code> accessors, but there will be sufficient other reason to have exposed and documented classes.</p> <p>As part of the additional functionality, it may be helpful to cleanly separate the methods that access existing sheets and cells from those that can create them.</p> <p><strong>When might it be right to nest?</strong></p> <p>This particular example doesn't seem to match this case, but sometimes it makes sense to group things by similar interfaces. Say you might have multiple subclasses of Workbook that need to instantiate different subclasses of Worksheet that in turn might need to instantiate different subclasses of Cell. It can be useful to leverage the class inheritance machinery to store that in the class.</p> <p>Note that even this scenario does not require the class itself be nested, however; it would be sufficient to include lines like this:</p> <pre><code>class Workbook: # : : : worksheet_type = Worksheet # : : : def worksheet(self, name): return self.worksheet_type(self, name) class WorkbookVariant(Workbook): # : : : worksheet_type = WorkbookVariant </code></pre>
0
2016-08-04T12:25:49Z
[ "python", "class", "oop", "subclass" ]
Removing header from column
38,748,752
<p>I am trying to do something similar to awk in Python to retrieve a specific column but need to remove the column header. Is there a quick simple way to remove the header from a column after using split? Below is my sample code.</p> <pre><code>du = '''Filesystem Size Used Avail Use% Mounted on /dev/sda3 30G 4.0G 26G 14% / devtmpfs 907M 0 907M 0% /dev tmpfs 921M 152K 921M 1% /dev/shm tmpfs 921M 8.5M 912M 1% /run tmpfs 921M 0 921M 0% /sys/fs/cgroup /dev/sda1 509M 291M 219M 58% /boot Users 239G 164G 76G 69% /media/sf_Users tmpfs 185M 12K 185M 1% /run/user/1002 tmpfs 185M 0 185M 0% /run/user/0''' for line in du.splitlines(): fields = line.split() f4 = (fields[4].strip('%')) print(f4) </code></pre> <p>Current Output:</p> <pre><code>Use 14 0 1 1 0 58 69 1 0 </code></pre> <p>Desired Output:</p> <pre><code>14 0 1 1 0 58 69 1 0 </code></pre>
0
2016-08-03T16:11:42Z
38,748,831
<p>You can do this:</p> <pre><code>for line in du.splitlines()[1:]: fields = line.split() f4 = (fields[4].strip('%')) print(f4) # 14 # 0 # 1 # 1 # 0 # 58 # 69 # 1 # 0 </code></pre>
1
2016-08-03T16:15:43Z
[ "python", "multiple-columns" ]
Replacing previous text printed in shell - Windows
38,748,756
<p>I have been researching this question, and it seems that it is possible, but not possible on Windows.</p> <p>I am trying to achieve a loading bar that will print 'Loading', then 'Loading.', 'Loading..'... etc.</p> <p>This code seems to work on Linux but not Windows(Python 3.5):</p> <pre><code>x = 0 for x in range (0,5): #x = x + 1 b = "Loading" + "." * x print (b, end="\r") time.sleep(1) </code></pre> <p>How do I combat this problem?</p>
0
2016-08-03T16:11:54Z
38,748,943
<p>The problem is buffering: everything appears at once when the script ends. You can <a href="https://docs.python.org/3/library/functions.html#print" rel="nofollow">force Python >3.3 to flush after each print output</a>:</p> <pre><code>import time print("Loading", end="", flush=True) for x in range(0,5): print(".", end="", flush=True) time.sleep(.2) </code></pre> <p>Of course a loading bar may look cool, but a fake one that just wastes time sleeping is not going to make the user happy. If your program really is doing business, have a look at <a href="http://docs.python.org/3/library/threading.html" rel="nofollow">threading</a> or <a href="https://docs.python.org/3/library/subprocess.html" rel="nofollow">subprocess</a>.</p> <p><hr> Your original idea works for me (Python 3.4 on Win7 64 bit), too:</p> <pre><code>import time for x in range(0,5): print("Loading" + "."*x, end="\r", flush=True) time.sleep(.2) </code></pre>
2
2016-08-03T16:21:18Z
[ "python", "windows-console" ]
Get object with specific hour in django
38,748,899
<p>I have model like this:</p> <pre><code>class Order(models.Model): dateTime = models.DateTimeField() </code></pre> <p>and I want to get object with specific hour how can I do that? the code below doesn't work:</p> <pre><code>o=Order.objects.get(dateTime.hour=12) </code></pre> <p>and has this problem: <code>keyword can't be an expression</code></p> <p>now.. How should I give the order object with specific time?</p>
0
2016-08-03T16:18:39Z
38,749,013
<p><a href="https://docs.djangoproject.com/en/1.9/ref/models/querysets/#hour" rel="nofollow">https://docs.djangoproject.com/en/1.9/ref/models/querysets/#hour</a></p> <pre><code>o = Order.objects.filter(dateTime__hour=12) </code></pre>
0
2016-08-03T16:24:48Z
[ "python", "django" ]
Get object with specific hour in django
38,748,899
<p>I have model like this:</p> <pre><code>class Order(models.Model): dateTime = models.DateTimeField() </code></pre> <p>and I want to get object with specific hour how can I do that? the code below doesn't work:</p> <pre><code>o=Order.objects.get(dateTime.hour=12) </code></pre> <p>and has this problem: <code>keyword can't be an expression</code></p> <p>now.. How should I give the order object with specific time?</p>
0
2016-08-03T16:18:39Z
38,749,125
<p>The following will give you all the objects having <code>hour</code> value as 12.</p> <pre><code>o = Order.objects.filter(dateTime__hour=12) </code></pre> <p>which can be used in place of </p> <pre><code>o = Order.objects.get(dateTime__hour=12)` </code></pre> <p>to get that one object, in case you have unique <code>hour</code> values for objects.</p> <p>But if already know that you have unique value of <code>hour</code> then you should use the later.</p>
1
2016-08-03T16:31:03Z
[ "python", "django" ]
looping through dictionary built from csv and write certain key values to file
38,748,931
<p>I am trying to open a file and read it into a dictionary. I've done this successfully, but I need to write the 'values' to variable and then take the variable and write it to another file in a certain location. Or is there a way to not putting them all into a variable. </p> <p>The 'person1' in the write section is what I need to do, but for the multiple names in the file. </p> <p>I am a noob so I apologize if I am confusing. </p> <p>Link to data file <a href="http://i.imgur.com/OcZ1tlK.jpg" rel="nofollow">DataFileLayout</a></p> <pre><code>`import csv with open('registrant_data.csv') as csvFile: readCSV = list(csv.DictReader(csvFile)) for row in readCSV: person1 = row['firstname'] + ' ' + row['lastname'] # HTML Top of page with open('nametags8gen.html', 'w+') as myWriteFile: myWriteFile.write('&lt;!DOCTYPE html&gt; \n' '&lt;html&gt;\n' '&lt;head&gt;\n' '&lt;title&gt;natetag8&lt;/title&gt;\n' '&lt;link href="styles/nametags8.css" type="text/css" rel="stylesheet" /&gt;\n' '&lt;/head&gt;\n' '&lt;body&gt;\n' '&lt;header&gt;\n' '&lt;/header&gt;\n' '&lt;main class="mainContainer"&gt;\n' '&lt;div class"textBoxContainer"&gt;\n' '&lt;div class="textContainer"&gt;\n' '&lt;span class="font22"&gt;' + person1 +'&lt;/span&gt;\n' '&lt;span class="font12"&gt;Smith&lt;/span&gt;\n' '&lt;span class="font14"&gt;Web Developer&lt;/span&gt;\n' '&lt;span class="font12"&gt;Regis University&lt;/span&gt;\n' '&lt;span class="font12"&gt;Denver, CO&lt;/span&gt;\n' '&lt;/div&gt;\n') csvFile.close()` </code></pre>
1
2016-08-03T16:20:34Z
38,749,207
<p>I'm not sure what your desired output is. What about this? In this code, I first write the beginning of the html file, then I loop through the csv file and add a few spans for each row of the file.</p> <pre><code>import csv with open('registrant_data.csv') as csvFile: readCSV = list(csv.DictReader(csvFile)) with open('nametags8gen.html', 'w+') as myWriteFile: myWriteFile.write('&lt;!DOCTYPE html&gt; \n' '&lt;html&gt;\n' '&lt;head&gt;\n' '&lt;title&gt;natetag8&lt;/title&gt;\n' '&lt;link href="styles/nametags8.css" type="text/css" rel="stylesheet" /&gt;\n' '&lt;/head&gt;\n' '&lt;body&gt;\n' '&lt;header&gt;\n' '&lt;/header&gt;\n' '&lt;main class="mainContainer"&gt;\n' '&lt;div class"textBoxContainer"&gt;\n' '&lt;div class="textContainer"&gt;\n') for row in readCSV: myWriteFile.write('&lt;span class="font22"&gt;' + row['firstname'] +'&lt;/span&gt;\n' '&lt;span class="font12"&gt;' + row['lastname'] +'&lt;/span&gt;\n' # here add other info for each person myWriteFile.write('&lt;/div&gt;\n' '&lt;/body&gt;\n') </code></pre>
0
2016-08-03T16:36:10Z
[ "python", "csv", "dictionary" ]
Errors Following Michael Halls-Moore Algorithmic Trading
38,749,037
<p>I am following Michael Halls-Moore Algorithmic Trading book and having some problems with the code. When I paste the code into python I get a load of errors.</p> <p>Am I missing something here because its exactly the same as what is written in the book?</p> <pre><code>from __future__ import print_function from numpy import cumsum, log, polyfit, sqrt, std, subtract from numpy.random import randn def hurst(ts): """Returns the Hurst Exponent of the time series vector ts""" # Create the range of lag values lags = range(2, 100) # Calculate the array of the variances of the lagged differences tau = [sqrt(std(subtract(ts[lag:], ts[:-lag]))) for lag in lags] # Use a linear fit to estimate the Hurst Exponent poly = polyfit(log(lags), log(tau), 1) # Return the Hurst exponent from the polyfit output return poly[0]*2.0 # Create a Geometric Brownian Motion, Mean-Reverting and Trending Series gbm = log(cumsum(randn(100000))+1000) mr = log(randn(100000)+1000) tr = log(cumsum(randn(100000)+1)+1000) # Output the Hurst Exponent for each of the above series # and the price of Amazon (the Adjusted Close price) for # the ADF test given above in the article print("Hurst(GBM): %s" % hurst(gbm)) print("Hurst(MR): %s" % hurst(mr)) print("Hurst(TR): %s" % hurst(tr)) # Assuming you have run the above code to obtain 'amzn'! print("Hurst(AMZN): %s" % hurst(amzn['Adj Close'])) </code></pre> <p>The errors below</p> <pre><code>james@ubuntu:~$ python Python 2.7.12 (default, Jul 1 2016, 15:12:24) [GCC 5.4.0 20160609] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; from __future__ import print_function &gt;&gt;&gt; &gt;&gt;&gt; from numpy import cumsum, log, polyfit, sqrt, std, subtract &gt;&gt;&gt; from numpy.random import randn &gt;&gt;&gt; &gt;&gt;&gt; &gt;&gt;&gt; def hurst(ts): ... """Returns the Hurst Exponent of the time series vector ts""" ... # Create the range of lag values ... &gt;&gt;&gt; lags = range(2, 100) File "&lt;stdin&gt;", line 1 lags = range(2, 100) ^ IndentationError: unexpected indent &gt;&gt;&gt; &gt;&gt;&gt; # Calculate the array of the variances of the lagged differences ... &gt;&gt;&gt; tau = [sqrt(std(subtract(ts[lag:], ts[:-lag]))) for lag in lags] File "&lt;stdin&gt;", line 1 tau = [sqrt(std(subtract(ts[lag:], ts[:-lag]))) for lag in lags] ^ IndentationError: unexpected indent &gt;&gt;&gt; &gt;&gt;&gt; # Use a linear fit to estimate the Hurst Exponent ... &gt;&gt;&gt; poly = polyfit(log(lags), log(tau), 1) File "&lt;stdin&gt;", line 1 poly = polyfit(log(lags), log(tau), 1) ^ IndentationError: unexpected indent &gt;&gt;&gt; &gt;&gt;&gt; # Return the Hurst exponent from the polyfit output ... &gt;&gt;&gt; return poly[0]*2.0 File "&lt;stdin&gt;", line 1 return poly[0]*2.0 ^ IndentationError: unexpected indent &gt;&gt;&gt; &gt;&gt;&gt; # Create a Gometric Brownian Motion, Mean-Reverting and Trending Series ... gbm = log(cumsum(randn(100000))+1000) &gt;&gt;&gt; mr = log(randn(100000)+1000) &gt;&gt;&gt; tr = log(cumsum(randn(100000)+1)+1000) &gt;&gt;&gt; &gt;&gt;&gt; # Output the Hurst Exponent for each of the above series ... # and the price of Amazon (the Adjusted Close price) for ... # the ADF test given above in the article ... print("Hurst(GBM): %s" % hurst(gbm)) Hurst(GBM): None &gt;&gt;&gt; print("Hurst(MR): %s" % hurst(mr)) Hurst(MR): None &gt;&gt;&gt; print("Hurst(TR): %s" % hurst(tr)) Hurst(TR): None &gt;&gt;&gt; &gt;&gt;&gt; # Assuming you have run the above code to obtain 'amzn'! ... print("Hurst(AMZN): %s" % hurst(amzn['Adj Close'])) Hurst(AMZN): None </code></pre>
0
2016-08-03T16:26:32Z
38,749,856
<p>Looks like you're pasting the code into a python interactive window. When you use the interactive window to write a block of indented code (like when defining a function or starting a for loop), pressing enter twice ends the code block section (this is why you get the error after a blank line when the code is supposed to be in an indented code block). In your code, you can either remove all the blank lines (except for blank lines at the end of a block of code; those are necessary to end the code block) and paste it into an interactive window, or you can copy the code into a text file, save the file with .py file extension, and run the script from the command prompt/powershell/terminal using the command <code>python your_script.py</code>. </p> <p>Alternatively, use a python IDE (instead of interactive window or from the command line) like pycharm (<a href="https://www.jetbrains.com/pycharm/" rel="nofollow">https://www.jetbrains.com/pycharm/</a>). </p>
2
2016-08-03T17:12:24Z
[ "python", "python-2.7", "numpy", "quantitative-finance" ]
Azure WebJob in Python: How to access azure python package?
38,749,082
<p>I have a simple Azure WebJob written in Python that utilizes the azure python package (which is located in a venv within my solution). The job executes as expected on my local machine, but when I deploy it to the Azure WebJob instance, I get the following error:</p> <p>ImportError: No module named azure.storage.table</p> <p>The actual .py is as follows:</p> <pre><code>from azure.storage.table import TableService # get table service table_service = TableService(account_name='myacct', account_key='mykey') # delete table table_service.delete_table('MyTable') </code></pre> <p>How do I access the azure package from the WebJob instance, why doesn't MS make this package universally accessible to all Python WebJob instances?</p>
1
2016-08-03T16:29:41Z
38,749,600
<p>The only solution I found currently is to push yourself the packages. This might help you:</p> <p><a href="http://nicholasjackson.github.io/azure/python/python-packages-and-azure-webjobs/" rel="nofollow">http://nicholasjackson.github.io/azure/python/python-packages-and-azure-webjobs/</a></p>
0
2016-08-03T16:57:21Z
[ "python", "azure", "azure-webjobs", "azure-table-storage" ]
Azure WebJob in Python: How to access azure python package?
38,749,082
<p>I have a simple Azure WebJob written in Python that utilizes the azure python package (which is located in a venv within my solution). The job executes as expected on my local machine, but when I deploy it to the Azure WebJob instance, I get the following error:</p> <p>ImportError: No module named azure.storage.table</p> <p>The actual .py is as follows:</p> <pre><code>from azure.storage.table import TableService # get table service table_service = TableService(account_name='myacct', account_key='mykey') # delete table table_service.delete_table('MyTable') </code></pre> <p>How do I access the azure package from the WebJob instance, why doesn't MS make this package universally accessible to all Python WebJob instances?</p>
1
2016-08-03T16:29:41Z
38,757,917
<p>By default, if you leverage <code>venv</code> in your python application on Azure Web apps, after you deploying your web app to Azure, the <code>venv</code> folder will locate in <code>D:\home\site\wwwroot\env\</code>. And also the python libraries will lie at <code>D:\home\site\wwwroot\env\Lib\site-packages</code>. You can install the python libs in your web app and leverage this absolute address in your python web job scripts, to load the libs in your python web application.</p> <p>Please try the following test script in WebJobs:</p> <pre><code>import sys sitepackage = "D:\home\site\wwwroot\env\Lib\site-packages" sys.path.append(sitepackage) try: from azure.storage.table import TableService print "successfully load lib" except ImportError, e: print "cannot load lib" </code></pre>
2
2016-08-04T03:14:27Z
[ "python", "azure", "azure-webjobs", "azure-table-storage" ]
sizeof(string) not equal to string length
38,749,094
<p>I used to think that each character is one byte (at least that is the case in c/c++) so the size of string should be equal to <code>len(string)</code> bytes. However, a simple experiment tells me that it is not the case in python:</p> <pre><code>import string, sys, random # abstracted code, removed unnecessary parts def loadKeyLength(db,key,N): val = key[:5] + ''.join(random.choice(string.ascii_letters + string.digits) for _ in xrange(N-5)) print sys.getsizeof(val), len(val),val def loadKeysSize(s): r=0 key=str(s).zfill(5)+str(r).zfill(5) loadKeyLength(None,key,s) for i in range(80,120,3): loadKeysSize(i) </code></pre> <p>output on Ubuntu 14.04:</p> <pre><code>117 80 000802qdxV2TY3qjGpe6F35hLczQNE2h7bWRWpHEMxqcyrb01sI2A6gcTLKLxdQSFjGMFtWPZJDOtKe4 120 83 00083oX6FouwlAyUkmZZCLWuIWnDMAKZDlNvO4ElHTK4x6vjka42APnwOcEMFHDLXbTZg9CUpd5ALqveowX 123 86 000860z1yhl3i1mKYFMhY4D2kWKA6Bvpfw91VeI7gXyP52PrVbLoP95ykgkz47k3KhCgmgrHq3CBCEdV14aiOa 126 89 00089xfcmZyf8RrftFbxvx9qvJUd8bvG5FKH2Ydz7aN5EsnaBpQkvrTLIsAKNRADeF1M74Ghvk1opzRs28IokPVhS 129 92 00092COlhIGMXrQ4Zl7e6GPlVz43BVWLbnvC3ymtoZ6Itus8KWuM1I31xGPU5Y4vggpcq2g4c6uSvnmUjsAgpYkNoX1u 132 95 00095IrjvnSVC8ECKf2cNUsBkzrSfuTNobIUmAD9BktiMfQSoCBLkwPOa2QmovhnUEpYyAsCKdM2haVqb53PggDviQHseex 135 98 00098DsLvbvWmqgyuWsnQd0DillNmd3LyTSJ98XjKUDhbqBSxhVRoXyv0IkOjWAbZIEb5lmrnISWS28WS4OpisoJYPCIfnB4bw 138 101 00101JNfUNutpjBFhFlhyNhFae2gulYTIfBpfoBbnLl881LPeZNGQkwYF49pbDEvnqYkPSleFUrZ1tEfO4AokI7ka3Gcn8KkTmWWg 141 104 00104lbmN2zeZeUMS6xGQfjtImCkwQwmewbXxsxj0NGETdBGwAfnhBmXOSew8LMdULQYCEA3Nz8ny6OlGfOUP3zjf5lZXlNC8Cn89Il4 144 107 00107UwQCaa4szAYj9if1oIPleauAvyWVkyDzbtZSt0SiKfJgNG7avZLe4TSTWXuEZBOUICfTAjIzVlShwXJ54Oz14rZlBrQL0w05FJsckY 147 110 00110lNZA1HsGmdFZke0Up1PwxPtpt2RFDM9EdOljQ6K3oao44Q6CNsBZHxo56n63Lny5l6k5ny7rhgWtkEGoJS7JbeNBg9ACXApfz4seWiZrX 150 113 00113KJ1sSGNZfZx2xl0MBXY0yf6ybPNjpmYBYiHi0ZsBb9GFuE9hIQgR0TssgbdE9sqq1m90YlS1ZWHSwwElaCkNOT05GbbIt3AfZAzzlpul5jEJ 153 116 001167jYYE6oyKM7qKQdzjpV1xUVUb85hpHpliNZRyiX7r6vJJ4n2FSe9tLUJ4W0ecUEALEemAZ0mUSkSROPl3AdQJ9AFdUAWvT5v4WTbNUZlFk2x0JX 156 119 00119ehpukL2CAOfCDbdtvuEvROVZJUvg044u8YS3d81SQ1FQqZDoVe55F8zCi7ikH1rEk2MWGUQLrmdJkMDKCXrtoeuZBDpo7pJOcmLRYZMLcLiC37iWXx </code></pre> <p>On Windows10:</p> <pre><code>101 80 00080Ra86ljAznn9AM17OtGUuFmxdYd7lU1hkInjZoPQJ4C2g3itkqn7wV0thhxPgpxrDimJwUElXzL2 104 83 00083nxTNohavc5sQfvlmnPnGOQNpzn2PKQJTYeDq4I9lMkuMKAxOhdOm1l3KAxmyCNOhlCKla9KMp8XYit 107 86 00086NBNeIqBFwWPbGzvtEihHvFnO3XyfPUEL0izlzF45P0NdfNTCyCDHvO6xa6BX4TyybChCEllhPOFXWpWd4 110 89 00089PmSiJYRGmI2AlXkbFUwcO1Ipr0bFvCmA2Se1A9JGMRTcg7617mXmG7fNCmDZWWFwI5DgTNHtqRDvTzrrmf08 113 92 00092DbsiuxTEZJT8DznuF3mtpdRP4LP4Nboj8tpCbgZkfeeP925U8N7v34qQpT69bw26Lfwp1jJXhkcb1o0wGUsgSIt 116 95 000958GexIZILU3le53WUGzTC6sRLK3vQVCsNI1yOuFt1HdW6QHZm05n5XGGMsluSamrKINAoBPxuQ5yrYSQHE7BlrWI6Jl 119 98 00098suYJVfpHKDkjHmnXwevRUOskhnCfF5Zp2jcN4avlg7ZN9g98G3vFeMpoXrulM7g5VfOQKI7UudzNfqkGDSaNfSuDvfyEE 122 101 00101doDJHZQEJre8aDWDGIPeKzN2aFXKZxYH9w6o9ZxgAXXozc75KMMwQ23YN0N27IMdAY5Oe9WLQSUgIf6AkfSNjWTFOODBvXeg 125 104 00104lhRSLYEXD1waMMkSVKct8jnb8M97rRQl582dlnzRr8hGM00jJLxrhHVvq1Kbu59dtcCSb4vm0KzbXKGiIdarDakNVLuCWYA9Mrh 128 107 00107y11AyDhwM8BZzT73VhkYu9U4ogvbw10ZPmnA824MzAznGbhLbHPDJjnl2NfquwH9XEOTx4vJjz74HC7I8GceZsCTlIQE4tQtWEtmig 131 110 00110GD8f97kpuRShkyrXYI40UvWlWOvskqRrDbUNjR2x6cZcg4NywVe1UAecrehoTJU5WUqZvvxseD16fYFvzaTKv7Jdwn1yQOazXSKheHORZ 134 113 001130coEBOEdkY1raJ65VK77UPU7eRraN2dz9mibcbu4khQwFQWf9WVBPUwTjlddveJKGLKS4gtNLWNeN4U720DW8XmHdpqhkXxqGBouZ2ARYfU6 137 116 001164x8ALzFvQKijeOIcDz6DCBnqzcMPQiR7rLaMBNuNFBYULSJ2xWIcGdyHHZw2lqW817fYo56Yg5hibAO7NzOyehOyxxUA865lQUjiP8LwmffCdnO 140 119 00119Sak3ByDRCFDMYpzpNEIKU5yNEWbWdL0popfhspb8cjE9sEBpMNxyGj5wjofhdois8DYQUTumJ3Xy7nzR04xGCG3mNQkVzKw1d97XP5RwN99Yac6I5F </code></pre> <p>So what does this mean? What can I do if I want to generate a random string of specific size in bytes? Why is there a difference in size on two different platforms (some python internals I am sure) ?</p> <p><strong>Note:</strong> My main purpose is to generate random strings whose size follows a specific distribution for a memory research problem but that is irrelevant here.</p>
0
2016-08-03T16:30:05Z
38,749,126
<p>Python string objects contain <em>more information</em> than just the characters. They contain a reference count, a reference to the type definition, the length of the string, the cached hash and the interning state. See the <a href="https://hg.python.org/cpython/file/v2.7.11/Include/stringobject.h#l27" rel="nofollow"><code>PyStringObject</code> struct</a>, as well as the <a href="https://hg.python.org/cpython/file/v2.7.11/Include/object.h#l77" rel="nofollow"><code>PyObject_VAR_HEAD</code> struct</a> referenced.</p> <p>As a result, an empty string has a memory size too:</p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; sys.getsizeof('') 37 </code></pre> <p>This size is platform dependent, because pointers and C integers have different sizes on different platforms. <code>37</code> is the size of a Python 2 <code>str</code> object on Mac OS X.</p> <p>For <code>unicode</code> objects the picture is even more distorted; Python 2 can use either 2 or 4 bytes <em>per codepoint</em>, depending on a compilation-time choice. The most recent Python 3 versions use a <strong>variable</strong> number of bytes for Unicode text, between 1 and 4 bytes per codepoint depending on the highest codepoint requirements in the text.</p> <p>As such, it is <em>normal</em> for <code>sys.getsizeof()</code> to return a different, higher value. <code>sys.getsizeof()</code> is <strong>not</strong> a function to get a string length. Use <code>len()</code> for that.</p> <p>If you are want to know how much memory <em>other</em> software uses for a string, you <em>definitely</em> can't use the <code>sys.sizeof()</code> value; other software will make different choices about how to store text, and will have different overheads. The <code>len()</code> value of the <em>encoded</em> text may be a starting point, but you'll have to check with the documentation or developers for that other piece of software to see what they can tell you how much memory is required for a given piece of text.</p>
5
2016-08-03T16:31:10Z
[ "python", "string", "python-2.7", "sizeof" ]
Fine-tuning a deep neural network in Tensorflow
38,749,120
<p>I want to partially fine-tune a pre-trained deep neural network in Tensorflow (as in, load weights for all layers but only update weights on higher level layers). </p> <p>Is there any method in Tensorflow that allows the selection of variables that should be changed and those that should be kept the same?</p> <p>Thank you in advance!</p>
0
2016-08-03T16:30:57Z
38,749,587
<p>When you create an optimizer (e.g. <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/train.html#AdagradOptimizer" rel="nofollow"><code>tf.train.AdagradOptimizer</code></a>) to train your model, you can pass an explicit <code>var_list=[...]</code> argument to the <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/train.html#Optimizer.minimize" rel="nofollow"><code>Optimizer.minimize()</code></a> method. (If you don't specify this list, it will default to containing all of the variables in <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/state_ops.html#trainable_variables" rel="nofollow"><code>tf.trainable_variables()</code></a>.)</p> <p>For example, depending on your model, you might be able to use the names of your variables to define the list of variables to be optimized:</p> <pre><code># Assuming all variables to be fine-tuned have a name that starts with # "layer17/". opt_vars = [v for v in tf.trainable_variables() if v.name.startswith("layer17/")] train_op = optimizer.minimize(loss, var_list=opt_vars) </code></pre>
2
2016-08-03T16:56:56Z
[ "python", "machine-learning", "computer-vision", "tensorflow", "deep-learning" ]
Select a valid choice..That choice is not one of the available choices
38,749,132
<p>Here is my models and form in Django postgres database.When I try to create the mapspot object I get a error "Select a valid choice" even though its just a relational object.</p> <p>models.py</p> <pre><code>from django.db import models from django.utils.translation import ugettext_lazy as _ from django.contrib.postgres.fields import ArrayField class Map(models.Model): name = models.CharField(max_length=128) class MapSpot(models.Model): map = models.ForeignKey('polls.Map', related_name='polls') position = ArrayField(models.IntegerField(), size=2) position1 = models.IntegerField(default=0) class Meta: unique_together = (('map', 'position')) </code></pre> <p>forms.py</p> <pre><code>from django.forms import ModelForm from .models import Map, MapSpot class MapForm(ModelForm): class Meta: model = Map fields = ['name'] class MapSpotForm(ModelForm): class Meta: model = MapSpot fields = ['map','position'] &gt;&gt;&gt; form = MapForm({'name':'US'}) &gt;&gt;&gt; form.is_valid() True &gt;&gt;&gt; form.save() &lt;Map: Map object&gt; &gt;&gt;&gt; for each in Map.objects.all(): ... print(each.id, each.name) ... 1 Germantown 2 US &gt;&gt;&gt; spotform =MapSpotForm({'map':Map.objects.get(id=2),'position':'10,20'}) &gt;&gt;&gt; spotform.is_valid() False &gt;&gt;&gt; spotform.errors {'map': ['Select a valid choice. That choice is not one of the available choices.']} </code></pre>
0
2016-08-03T16:31:27Z
38,750,731
<p>Default form field for <code>ForeignKey</code> is <code>ModelChoiceField</code>. <code>ModelChoiceField</code> "validates that given id exists in the queryset". Try next:</p> <pre><code>spotform = MapSpotForm({'map': Map.objects.get(id=2).id, 'position': '10,20'}) </code></pre> <ul> <li><a href="https://docs.djangoproject.com/en/1.10/topics/forms/modelforms/#field-types" rel="nofollow"><code>ModelForm</code> field types</a></li> <li><a href="https://docs.djangoproject.com/en/1.10/ref/forms/fields/#modelchoicefield" rel="nofollow"><code>ModelChoiceField</code></a></li> </ul>
1
2016-08-03T18:04:11Z
[ "python", "django", "postgresql" ]
How to make a matrix out of existing xyz data
38,749,140
<p>I want to use matplotlib.pyplot.pcolormesh to plot a depth plot.</p> <p>What I have is a xyz file Three columns i.e. x(lat), y(lon), z(dep). </p> <p>All columns are of equal length</p> <p>pcolormesh require matrices as input. So using numpy.meshgrid I can transform the x and y into matrices:</p> <pre><code>xx,yy = numpy.meshgrid(x_data,y_data) </code></pre> <p>This works great...However, I don't know how to create Matrix of my depth (z) data... How do I create a matrix for my z_data that corresponds to my x_data and y_data matrices? </p>
0
2016-08-03T16:31:44Z
38,751,293
<p>Depending on whether you're generating <code>z</code> or not, you have at least two different options.</p> <p>If you're generating <code>z</code> (e.g. you know the formula for it) it's very easy (see <code>method_1()</code> below).</p> <p>If you just have just a list of (<code>x</code>,<code>y</code>,<code>z</code>) tuples, it's harder (see <code>method_2()</code> below, and maybe <code>method_3()</code>).</p> <p><strong>Constants</strong></p> <pre><code># min_? is minimum bound, max_? is maximum bound, # dim_? is the granularity in that direction min_x, max_x, dim_x = (-10, 10, 100) min_y, max_y, dim_y = (-10, 10, 100) </code></pre> <p><strong>Method 1: Generating <code>z</code></strong></p> <pre><code># Method 1: # This works if you are generating z, given (x,y) def method_1(): x = np.linspace(min_x, max_x, dim_x) y = np.linspace(min_y, max_y, dim_y) X,Y = np.meshgrid(x,y) def z_function(x,y): return math.sqrt(x**2 + y**2) z = np.array([z_function(x,y) for (x,y) in zip(np.ravel(X), np.ravel(Y))]) Z = z.reshape(X.shape) plt.pcolormesh(X,Y,Z) plt.show() </code></pre> <p>Which generates the following graph:</p> <p><a href="http://i.stack.imgur.com/QP5iC.png" rel="nofollow"><img src="http://i.stack.imgur.com/QP5iC.png" alt="method_1"></a></p> <p>This is relatively easy, since you can generate <code>z</code> at whatever points you want.</p> <p>If you don't have that ability, and are given a fixed <code>(x,y,z)</code>. You could do the following. First, I define a function that generates fake data:</p> <pre><code>def gen_fake_data(): # First we generate the (x,y,z) tuples to imitate "real" data # Half of this will be in the + direction, half will be in the - dir. xy_max_error = 0.2 # Generate the "real" x,y vectors x = np.linspace(min_x, max_x, dim_x) y = np.linspace(min_y, max_y, dim_y) # Apply an error to x,y x_err = (np.random.rand(*x.shape) - 0.5) * xy_max_error y_err = (np.random.rand(*y.shape) - 0.5) * xy_max_error x *= (1 + x_err) y *= (1 + y_err) # Generate fake z rows = [] for ix in x: for iy in y: z = math.sqrt(ix**2 + iy**2) rows.append([ix,iy,z]) mat = np.array(rows) return mat </code></pre> <p>Here, the returned matrix looks like:</p> <pre><code>mat = [[x_0, y_0, z_0], [x_1, y_1, z_1], [x_2, y_2, z_2], ... [x_n, y_n, z_n]] </code></pre> <p><strong>Method 2: Interpolating given <code>z</code> points over a regular grid</strong></p> <pre><code># Method 2: # This works if you have (x,y,z) tuples that you're *not* generating, and (x,y) points # may not fall evenly on a grid. def method_2(): mat = gen_fake_data() x = np.linspace(min_x, max_x, dim_x) y = np.linspace(min_y, max_y, dim_y) X,Y = np.meshgrid(x, y) # Interpolate (x,y,z) points [mat] over a normal (x,y) grid [X,Y] # Depending on your "error", you may be able to use other methods Z = interpolate.griddata((mat[:,0], mat[:,1]), mat[:,2], (X,Y), method='nearest') plt.pcolormesh(X,Y,Z) plt.show() </code></pre> <p>This method produces the following graphs:</p> <p><em>error = 0.2</em> <a href="http://i.stack.imgur.com/7s2wv.png" rel="nofollow"><img src="http://i.stack.imgur.com/7s2wv.png" alt="method_2(err=0.2)"></a></p> <p><em>error = 0.8</em> <a href="http://i.stack.imgur.com/PPYiM.png" rel="nofollow"><img src="http://i.stack.imgur.com/PPYiM.png" alt="method_2(err=0.8"></a></p> <p><strong>Method 3: No Interpolation (constraints on sampled data)</strong></p> <p>There's a third option, depending on how your <code>(x,y,z)</code> is set up. This option requires two things:</p> <ol> <li>The number of different x sample positions equals the number of different y sample positions.</li> <li>For every possible unique (x,y) pair, there is a corresponding (x,y,z) in your data.</li> </ol> <p>From this, it follows that the number of <code>(x,y,z)</code> pairs must be equal to the square of the number of unique x points (where the number of unique x positions equals the number of unique y positions).</p> <p>In general, with sampled data, this <em>will not</em> be true. But if it is, you can avoid having to interpolate:</p> <pre><code>def method_3(): mat = gen_fake_data() x = np.unique(mat[:,0]) y = np.unique(mat[:,1]) X,Y = np.meshgrid(x, y) # I'm fairly sure there's a more efficient way of doing this... def get_z(mat, x, y): ind = (mat[:,(0,1)] == (x,y)).all(axis=1) row = mat[ind,:] return row[0,2] z = np.array([get_z(mat,x,y) for (x,y) in zip(np.ravel(X), np.ravel(Y))]) Z = z.reshape(X.shape) plt.pcolormesh(X,Y,Z) plt.xlim(min(x), max(x)) plt.ylim(min(y), max(y)) plt.show() </code></pre> <p><em>error = 0.2</em> <a href="http://i.stack.imgur.com/od8Ph.png" rel="nofollow"><img src="http://i.stack.imgur.com/od8Ph.png" alt="method_3(err=0.2)"></a></p> <p><em>error = 0.8</em> <a href="http://i.stack.imgur.com/Lj7tg.png" rel="nofollow"><img src="http://i.stack.imgur.com/Lj7tg.png" alt="method_3(err=0.8)"></a></p>
1
2016-08-03T18:38:22Z
[ "python", "numpy", "matrix", "matplotlib", "coordinates" ]
django deploy - ubuntu 14.04 and apache2
38,749,160
<p><a href="https://www.sitepoint.com/deploying-a-django-app-with-mod_wsgi-on-ubuntu-14-04/" rel="nofollow">https://www.sitepoint.com/deploying-a-django-app-with-mod_wsgi-on-ubuntu-14-04/</a></p> <p>and</p> <p><a href="https://www.youtube.com/watch?v=hBMVVruB9Vs" rel="nofollow">https://www.youtube.com/watch?v=hBMVVruB9Vs</a></p> <p>This was the first time I deploy a website.And these are the tutorials I followed. </p> <p>Now I can access to the server(by typing 10.231.XX.XX) from other machine and see the Apache2 Ubuntu Default Page.</p> <p>Then I tried to access my django project. I run: </p> <blockquote> <p>python manage.py runserver 8000 Validating models...</p> <p>0 errors found August 03, 2016 - 09:44:20 Django version 1.6.1, using settings 'settings' Starting development server at <a href="http://127.0.0.1:8000/" rel="nofollow">http://127.0.0.1:8000/</a> Quit the server with CONTROL-C.</p> </blockquote> <p>Then I type 10.231.XX.XX:8000 to try to acess the django page. But I failed. It said: </p> <blockquote> <p>This site can’t be reached</p> <p>10.231.XX.XX refused to connect. Search Google for 231 8000 ERR_CONNECTION_REFUSED</p> </blockquote> <p>I have tried every thing I can but still can't figure why. (as followed the website <a href="https://www.sitepoint.com/deploying-a-django-app-with-mod_wsgi-on-ubuntu-14-04/" rel="nofollow">https://www.sitepoint.com/deploying-a-django-app-with-mod_wsgi-on-ubuntu-14-04/</a>) I have apache folder in mysite folder, and in override.py:</p> <pre><code>from mysite.settings import * DEBUG = True ALLOWED_HOSTS = ['10.231.XX.XX'] </code></pre> <p>in wsgi.py:</p> <pre><code>import os, sys # Calculate the path based on the location of the WSGI script. apache_configuration= os.path.dirname(__file__) project = os.path.dirname(apache_configuration) workspace = os.path.dirname(project) sys.path.append(workspace) sys.path.append(project) # Add the path to 3rd party django application and to django itself. sys.path.append('/home/zhaojf1') os.environ['DJANGO_SETTINGS_MODULE'] = '10.231.52.XX.apache.override' import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler() </code></pre> <p>and __init__py is empty.</p> <p>in /etc/apache2/sites-enabled/000-default.conf :</p> <pre><code>&lt;VirtualHost *:80&gt; # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last resort host regardless. # However, you must set it for any further virtual host explicitly. #ServerName www.example.com ServerAdmin webmaster@localhost DocumentRoot /var/www/html # Available loglevels: trace8, ..., trace1, debug, info, notice, warn, # error, crit, alert, emerg. # It is also possible to configure the loglevel for particular # modules, e.g. #LogLevel info ssl:warn ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined # For most configuration files from conf-available/, which are # enabled or disabled at a global level, it is possible to # include a line for only one particular virtual host. For example the # following line enables the CGI configuration for this host only # after it has been globally disabled with "a2disconf". WSGIScriptAlias /msa.html /home/zhaojf1/Web-Interaction/apache/wsgi.py &lt;Directory "/home/zhaojf1/Web-Interaction-APP"&gt; &lt;Files wsgi.py&gt; Require all granted &lt;/Files&gt; &lt;/Directory&gt; </code></pre> <p></p> <p>I have also restart apache after I do everything.</p> <p>Thanks for help</p>
0
2016-08-03T16:32:52Z
38,755,726
<p>The connection refused error is likely going to come down to Apache being incorrectly configured for the <code>VirtualHost</code> or you accessing wrong port. You also have other basic mistakes in your <code>wsgi.py</code> file as well.</p> <p>Starting with the <code>wsgi.py</code> file, the <code>DJANGO_SETTINGS_MODULE</code> value is wrong:</p> <pre><code>os.environ['DJANGO_SETTINGS_MODULE'] = '10.231.52.XX.apache.override' </code></pre> <p>The value is meant to be a Python module path. Having the IP address in there looks very wrong and is unlikely to yield what you need.</p> <p>Next is changes to <code>sys.path</code>. The location of your project and activation of any Python virtual environment is better done through options for mod_wsgi in the Apache configuration file.</p> <p>That you are adding a home directory into the path is also a flag to potential other issues you may encounter. Specifically, the user that Apache runs as often cannot read into home directories as the home directories are not readable/accessible to others. You may need to move the project out of your home directory.</p> <p>As to the Apache configuration, your <code>VirtualHost</code> lacks a <code>ServerName</code> directive. If this was an additional <code>VirtualHost</code> you added and not the default (first one appearing in Apache configuration when parsed), it will be ignored, with all requests going to the first <code>VirtualHost</code>. You do show this as in the default site file, so may be you are okay.</p> <p>Even so, that <code>VirtualHost</code> is set up to listed on port 80. You are trying to connect to port 8000, so there wouldn't be anything listening.</p> <p>Next issue is the <code>WSGIScriptAlias</code> line.</p> <pre><code>WSGIScriptAlias /msa.html /home/zhaojf1/Web-Interaction/apache/wsgi.py </code></pre> <p>It is strange to have <code>msg.html</code> as the mount point as that makes it appear as if you are accessing a single HTML page, but you have it mapped to a whole Django project. If you were accessing the root of the host, it also wouldn't map through to the Django application as you have it mounted at a sub URL. Thus perhaps need to use:</p> <pre><code>WSGIScriptAlias / /home/zhaojf1/Web-Interaction/apache/wsgi.py </code></pre> <p>Next problem is that the directory specified in <code>Directory</code> directive doesn't match where you said the <code>wsgi.py</code> file existed in the <code>WSGIScriptAlias</code>. They should match. So maybe you meant:</p> <pre><code>&lt;Directory /home/zhaojf1/Web-Interaction/apache&gt; </code></pre> <p>Even then that doesn't look right as where is the <code>apache</code> directory coming from. That last directory in the path should normally be the name of the Django project.</p> <p>One final thing, you may need to change <code>ALLOWED_HOSTS</code> as well. If you find you start getting bad request errors it probably doesn't match properly. Change it to <code>['*']</code> to see if that helps.</p> <p>So lots of little things wrong.</p> <p>Suggestions are:</p> <ul> <li>Make sure you read the official Django documentation for setting up mod_wsgi. See <a href="https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/modwsgi/" rel="nofollow">https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/modwsgi/</a></li> <li>If you are only wanting to do development at this point, use mod_wsgi-express instead. See <a href="http://blog.dscpl.com.au/2015/04/using-modwsgi-express-with-django.html" rel="nofollow">http://blog.dscpl.com.au/2015/04/using-modwsgi-express-with-django.html</a> and <a href="http://blog.dscpl.com.au/2015/04/integrating-modwsgi-express-as-django.html" rel="nofollow">http://blog.dscpl.com.au/2015/04/integrating-modwsgi-express-as-django.html</a></li> </ul>
0
2016-08-04T00:32:31Z
[ "python", "django", "apache", "ubuntu", "mod-wsgi" ]
Spark DataFrame mapPartitions
38,749,179
<p>I need to proceed distributed calculation on Spark DataFrame invoking some arbitrary (not SQL) logic on chunks of DataFrame. I did:</p> <pre><code>def some_func(df_chunk): pan_df = df_chunk.toPandas() #whatever logic here df = sqlContext.read.parquet(...) result = df.mapPartitions(some_func) </code></pre> <p>Unfortunatelly it leads to:</p> <blockquote> <p>AttributeError: 'itertools.chain' object has no attribute 'toPandas'</p> </blockquote> <p>I expected to have spark DataFrame object within each map invocation, instead I got 'itertools.chain'. Why? And how to overcome this?</p>
1
2016-08-03T16:34:03Z
38,749,349
<p>Try this:</p> <pre><code>&gt;&gt;&gt; columns = df.columns &gt;&gt;&gt; df.rdd.mapPartitions(lambda iter: [pd.DataFrame(list(iter), columns=columns)]) </code></pre>
1
2016-08-03T16:44:07Z
[ "python", "apache-spark", "pyspark", "apache-spark-sql" ]
represent a django model which combines data from 2 other models
38,749,188
<p><strong>Background</strong>:</p> <p>I scrape data from 2 sources for upcoming properties for sale, lets call one <code>SaleAnnouncement</code>, and the other <code>SellerMaintainedData</code>. They share many of the same field names (although some data can only be found in one and not the other). If an item is coming up for sale, there is guaranteed to be a <code>SaleAnnouncement</code>, but not necessarily <code>SellerMaintainedData</code>. In fact only about 10% of the "sellers" maintain there own site with relevant data. However those that do, always have more information and that data is more up to date than the data in the announcement. Also, the "announcement" is free form text which needs to go through several processing steps before the relevant data is extracted and as such, the model has some fields to store data in intermediate steps of processing (part of the reason I opted for 2 models as opposed to combining them into 1), while the "seller" data is scraped in a neat tabular format.</p> <p><strong>Problem</strong>:</p> <p>I would ultimately like to combine them into one <code>SaleItem</code> and have implemented a model which is related to the previous 2 models and relies heavily on properties to prioritize which model the data comes from. Something like:</p> <pre><code>@property def sale_datetime(self): if self.sellermaintaineddata and self.sellermaintaineddata.sale_datetime: return self.trusteeinfo.sale_datetime else: return self.latest_announcement and self.latest_announcement.sale_datetime </code></pre> <p>However I obviously won't be able to query those fields, which would be my end goal when listing upcoming sales. I have been suggested a solution which involves creating a custom manager which overrides the filter/exclude methods, which sounds promising but I would have to duplicate all the property field logic in the model manager. </p> <p><strong>Summary (for clarity)</strong></p> <p>I have:</p> <pre><code>class SourceA(Model): sale_datetime = ... address = ... parcel_number = ... # other attrs... class SourceB(Model): sale_datetime = ... address = ... # no parcel number here # other attrs... </code></pre> <p>I want:</p> <pre><code>class Combined(Model): sale_datetime = # from sourceB if sourceB else from sourceA ... </code></pre> <p>I want a unified model where common fields between <code>SourceA</code> and <code>SourceB</code> are prioritized so that if <code>SourceB</code> exists it derives the value of that field from <code>SourceB</code> or else it comes from <code>SourceA</code>. I would also like to query those fields so maybe using properties is not the best way...</p> <p><strong>Question</strong></p> <p>Is there a better way, should I consider restructuring my models (possibly combining those 2), or is the custom manager solution the way to go?</p>
0
2016-08-03T16:34:55Z
38,749,622
<p>I would suggest another solution. What about using inheritance? You could create base class that would be abstract (<a href="https://docs.djangoproject.com/en/1.9/topics/db/models/#abstract-base-classes" rel="nofollow">https://docs.djangoproject.com/en/1.9/topics/db/models/#abstract-base-classes</a>). You can put all common fields there and then create separate model for SaleAnnouncement and SellerMaintainedData. Since both of them will inherit from your base model, you'll have to define fields only specific for the certain model.</p>
0
2016-08-03T16:58:36Z
[ "python", "django", "django-models" ]
Python Multiprocessing: Topping off multiprocessing queue before becoming empty
38,749,215
<p>I'm trying to make a multiprocessing Queue in Python 2.7 that fills up to it's maxsize with processes, and then while there are more processes to be done that haven't yet been put into the Queue, will refill the Queue when any of the current procs finish. I'm trying to maximize performance so size of the Queue is numCores on the PC so each core is always doing work (ideally CPU will be at 100% use the whole time). I'm also trying to avoid context switching which is why I only want this many in the Queue at any time.</p> <p>Example would be, say there are 50 tasks to be done, the CPU has 4 cores, so the Queue will be maxsize 4. We start by filling Queue with 4 processes, and immediately upon any of those 4 finishing (at which time there will be 3 in the Queue), a new proc is generated and sent to the queue. It continues doing this until all 50 tasks have been generated and completed.</p> <p>This task is proving to be difficult since I'm new to multiprocessing, and also it seems the join() function will not work for me since that forces a blocking statement until ALL of the procs in the Queue have completed, which is NOT what I want.</p> <p>Here is my code right now:</p> <pre><code>def queuePut(q, thread): q.put(thread) def launchThreads(threadList, performanceTestList, resultsPath, cofluentExeName): numThreads = len(threadList) threadsLeft = numThreads print "numThreads: " + str(numThreads) cpuCount = multiprocessing.cpu_count() q = multiprocessing.Queue(maxsize=cpuCount) count = 0 while count != numThreads: while not q.full(): thread = threadList[numThreads - threadsLeft] p = multiprocessing.Process(target=queuePut, args=(q,thread)) print "Starting thread " + str(numThreads - threadsLeft) p.start() threadsLeft-=1 count +=1 if(threadsLeft == 0): threadsLeft+=1 break </code></pre> <p>Here is where it gets called in code:</p> <pre><code>for i in testNames: p = multiprocessing.Process(target=worker,args=(i,paths[0],cofluentExeName,)) jobs.append(p) launchThreads(jobs, testNames, testDirectory, cofluentExeName) </code></pre> <p>The procs seem to get created and put into the queue, for an example where there are 12 tasks and 40 cores, the output is as follows, proceeded by the error below:</p> <pre><code>numThreads: 12 Starting thread 0 Starting thread 1 Starting thread 2 Starting thread 3 Starting thread 4 Starting thread 5 Starting thread 6 Starting thread 7 Starting thread 8 Starting thread 9 Starting thread 10 Starting thread 11 File "C:\Python27\lib\multiprocessing\queues.py", line 262, in _feed send(obj) File "C:\Python27\lib\multiprocessing\process.py", line 290, in __reduce__ 'Pickling an AuthenticationString object is ' TypeError: Pickling an AuthenticationString object is disallowed for security re asons Traceback (most recent call last): File "C:\Python27\lib\multiprocessing\queues.py", line 262, in _feed send(obj) File "C:\Python27\lib\multiprocessing\process.py", line 290, in __reduce__ 'Pickling an AuthenticationString object is ' TTypeError: Pickling an AuthenticationString object is disallowed for security r easons raceback (most recent call last): File "C:\Python27\lib\multiprocessing\queues.py", line 262, in _feed send(obj) File "C:\Python27\lib\multiprocessing\process.py", line 290, in __reduce__ 'Pickling an AuthenticationString object is ' TTypeError: Pickling an AuthenticationString object is disallowed for security r easons raceback (most recent call last): File "C:\Python27\lib\multiprocessing\queues.py", line 262, in _feed send(obj) File "C:\Python27\lib\multiprocessing\process.py", line 290, in __reduce__ 'Pickling an AuthenticationString object is ' TypeError: Pickling an AuthenticationString object is disallowed for security re asons </code></pre>
1
2016-08-03T16:36:35Z
38,750,207
<p>Why don't you use a multiprocessing Pool to accomplish this? </p> <pre><code>import multiprocessing pool = multiprocessing.Pool() pool.map(your_function, dataset) ##dataset is a list; could be other iterable object pool.close() pool.join() </code></pre> <p>The <code>multiprocessing.Pool()</code> can have the argument <code>processes=#</code> where you specify the # of jobs you want to start. If you don't specify this parameter, it will start as many jobs as you have cores (so if you have 4 cores, 4 jobs). When one job finishes it'll automatically start the next one; you don't have to manage that. </p> <p>Multiprocessing: <a href="https://docs.python.org/2/library/multiprocessing.html" rel="nofollow">https://docs.python.org/2/library/multiprocessing.html</a></p>
2
2016-08-03T17:31:47Z
[ "python", "queue", "multiprocessing" ]
Change django admin template for a calendar
38,749,296
<p>I have some models, one of them it's about gym sessions, </p> <pre><code>class Gym_Class(models.Model): name = models.CharField(max_length=200) icon = models.ImageField() instructor = models.ForeignKey(Instructor, related_name="instructor") program = models.ForeignKey(Program) short_review = models.TextField() long_review = models.TextField() date = models.DateField(default=datetime.now) def __unicode__(self): return self.name </code></pre> <p>I was wondering if I can override the listing template in the admin (localhost:8000/admin/gym_class/) to show the sessions in a calendar format based on each instance's date field <strong>just for this model</strong>, the other ones I would like to see them in a regular list format. The whole idea is that when someone wants to edit some info about the gym_class instances they will see a calendar instead of searching for the class in a big list.</p>
2
2016-08-03T16:40:46Z
38,749,777
<p>The admin template files are located in the contrib/admin/templates/admin directory.</p> <p>In order to override Gym_Class, create an admin directory in your project’s templates directory. Inside admin directory, create sub-directories named [your app name]. Inside this directory create a directory names Gym_Class. </p> <p>Next copy contrib/admin/templates/admin/change_list.html to the directory that you just created. </p> <p>Now start editing the file like normal HTML, setup calendar and other stuff you want to do. </p> <p><a href="https://docs.djangoproject.com/en/dev/ref/contrib/admin/#overriding-admin-templates" rel="nofollow">docss</a></p>
0
2016-08-03T17:07:59Z
[ "python", "django", "calendar", "django-templates", "django-admin" ]
Change django admin template for a calendar
38,749,296
<p>I have some models, one of them it's about gym sessions, </p> <pre><code>class Gym_Class(models.Model): name = models.CharField(max_length=200) icon = models.ImageField() instructor = models.ForeignKey(Instructor, related_name="instructor") program = models.ForeignKey(Program) short_review = models.TextField() long_review = models.TextField() date = models.DateField(default=datetime.now) def __unicode__(self): return self.name </code></pre> <p>I was wondering if I can override the listing template in the admin (localhost:8000/admin/gym_class/) to show the sessions in a calendar format based on each instance's date field <strong>just for this model</strong>, the other ones I would like to see them in a regular list format. The whole idea is that when someone wants to edit some info about the gym_class instances they will see a calendar instead of searching for the class in a big list.</p>
2
2016-08-03T16:40:46Z
38,750,066
<p>You can change the display of the django admin by <a href="https://docs.djangoproject.com/en/1.9/ref/contrib/admin/#overriding-admin-templates" rel="nofollow">overriding the admin templates</a>.</p> <p>The template you're specifically looking to override is named <code>change_list.html</code>. This file can be found in django's package directory with the path:</p> <p><strong><code>django/contrib/admin/templates/admin/change_list.html</code></strong></p> <p>You can copy the django template from its local python package directory, or <a href="https://github.com/django/django/blob/1.9.9/django/contrib/admin/templates/admin/change_list.html" rel="nofollow">download it from django's Github repository</a> into one of your application's template directories, placing it in</p> <p><strong><code>&lt;template-path&gt;/admin/gym_class/change_list.html</code></strong></p> <p><em><code>&lt;template-path&gt;</code> is wherever you put templates in your project</em></p> <p>With the template, you can customize it as you wish without it modifying the change list layout for your other apps.</p>
0
2016-08-03T17:23:48Z
[ "python", "django", "calendar", "django-templates", "django-admin" ]
LabelEncoder order of fit for a Pandas df
38,749,305
<p>I am fitting a scikit-learn <a href="http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.LabelEncoder.html#sklearn-preprocessing-labelencoder" rel="nofollow">LabelEncoder</a> on a column in a pandas <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html" rel="nofollow">df</a>. </p> <p>How is the order, in which the encountered strings are mapped to the integers, determined? Is it deterministic?</p> <p>More importantly, can I specify this order?</p> <pre><code>import pandas as pd from sklearn import preprocessing df = pd.DataFrame(data=["first", "second", "third", "fourth"], columns=['x']) le = preprocessing.LabelEncoder() le.fit(df['x']) print list(le.classes_) ### this prints ['first', 'fourth', 'second', 'third'] encoded = le.transform(["first", "second", "third", "fourth"]) print encoded ### this prints [0 2 3 1] </code></pre> <p>I would expect <code>le.classes_</code> to be <code>["first", "second", "third", "fourth"]</code> and then <code>encoded</code> to be <code>[0 1 2 3</code>], since this is the order in which the strings appear in the column. Can this be done?</p>
2
2016-08-03T16:41:21Z
38,749,529
<p>It's done in sort order. In the case of strings, it is done in alphabetic order. There's no documentation for this, but looking at the source code for <a href="https://github.com/scikit-learn/scikit-learn/blob/51a765a/sklearn/preprocessing/label.py#L130" rel="nofollow">LabelEncoder.transform</a> we can see the work is mostly delegated to the function <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.setdiff1d.html" rel="nofollow">numpy.setdiff1d</a>, with the following documentation:</p> <blockquote> <p>Find the set difference of two arrays.</p> <p>Return the <strong>sorted</strong>, unique values in ar1 that are not in ar2.</p> </blockquote> <p>(Emphasis mine).</p> <p>Note that since this is not documented, it is probably implementation defined and can be changed between versions. It could be that just the version I looked use the sort order, and other versions of scikit-learn may change this behavior (by not using numpy.setdiff1d).</p>
1
2016-08-03T16:53:48Z
[ "python", "pandas", "scikit-learn" ]
Python: No Module named Zlib, Mac OS X El Capitan 10.11.6
38,749,403
<p>I'm trying to convert my python command line application to an app with py2app. Everytime I try to import zlib or try to install setuptools , I get an error : no module named zlib.</p> <p>Python was installed with brew. I searched every corner of the internet and stack overflow, I have reinstalled python with brew , I have installed all Xcode CLI related stuff with :</p> <pre><code>xcode-select --install </code></pre> <p>I also ran :</p> <pre><code>ls /usr/include/zlib.h </code></pre> <p>and I can see that zlib is there where it is supposed to be.</p> <p>Reinstalled with:</p> <pre><code>brew reinstall python </code></pre> <p>Unfortunately that didn't work for me. I can't get what is wrong.</p> <p>Any ideas?</p>
1
2016-08-03T16:47:37Z
38,750,903
<p>Finally found the answer.</p> <p>After using:</p> <pre><code>brew doctor </code></pre> <p>I found out that I had more config scripts in my path, according to brew doctor.</p> <p>So I did:</p> <pre><code>sudo rm -rf /Library/Frameworks/Python.framework/ </code></pre> <p>next :</p> <pre><code>brew prune </code></pre> <p>and finally:</p> <pre><code>brew install python </code></pre> <p>also had some linking problems so I ran:</p> <pre><code> brew link python3 </code></pre>
1
2016-08-03T18:14:33Z
[ "python", "osx", "homebrew", "zlib" ]
Python Get Returned Object From Called Module
38,749,431
<p>Given this module (sample.py):</p> <pre><code>def calculation(x): r = x + 1 return r </code></pre> <p>In my main .py file in Spyder, I'm calling it like this:</p> <pre><code>import sample b = sample.calculation(2) </code></pre> <p>My (dumb) question is: how to I access r, as defined in the sample module, for other calculations in the main .py file from which I'm calling sample?</p> <p>I want to continue by doing something like:</p> <pre><code>a = r/2 </code></pre> <p>in the main .py file after calling </p> <pre><code>sample.calculation(2) </code></pre> <p>Update:</p> <p>I would assume b would result in the number 3. But what if the module returns 2 different numbers (objects)? How do I access them individually?</p>
-1
2016-08-03T16:49:27Z
38,749,592
<blockquote> <p>My (dumb) question is: how to I access r, as defined in the sample module, for other calculations in the main .py file from which I'm calling sample?</p> </blockquote> <p>You use that <code>b</code> variable you assigned the value to.</p> <blockquote> <p>But what if the module returns 2 different numbers (objects)? How do I access them individually?</p> </blockquote> <p>If you mean the function does this:</p> <pre><code>def return_two_things(): return 1, 2 </code></pre> <p>then you assign them to two variables:</p> <pre><code>a, b = module.return_two_things() </code></pre> <p>If you mean the function does this:</p> <pre><code>def wrong_way(): return 1 return 2 </code></pre> <p>then your function is wrong, and you have misunderstood how <code>return</code> statements work. A function ends as soon as it executes a <code>return</code>; it does not continue on to return more things.</p>
1
2016-08-03T16:57:08Z
[ "python", "object", "module", "spyder" ]
Python Get Returned Object From Called Module
38,749,431
<p>Given this module (sample.py):</p> <pre><code>def calculation(x): r = x + 1 return r </code></pre> <p>In my main .py file in Spyder, I'm calling it like this:</p> <pre><code>import sample b = sample.calculation(2) </code></pre> <p>My (dumb) question is: how to I access r, as defined in the sample module, for other calculations in the main .py file from which I'm calling sample?</p> <p>I want to continue by doing something like:</p> <pre><code>a = r/2 </code></pre> <p>in the main .py file after calling </p> <pre><code>sample.calculation(2) </code></pre> <p>Update:</p> <p>I would assume b would result in the number 3. But what if the module returns 2 different numbers (objects)? How do I access them individually?</p>
-1
2016-08-03T16:49:27Z
38,749,677
<p>Accessing another module's variable is possible by making it global. But it is not a good practice and often avoided. You can do this instead</p> <pre><code>import sample r = sample.calculation(2) </code></pre> <p>This way, you can use the same variable name 'r' but it is now a local variable. </p> <p>For your second question about returning multiple objects from a module, you can do this</p> <pre><code>def module1(x): return x+1,x+2 a,b = module1(5) #a has 5+1 = 6 #b has 5+2 = 7 </code></pre>
1
2016-08-03T17:01:28Z
[ "python", "object", "module", "spyder" ]
How to list all unused elastic IPs and release them using boto3
38,749,484
<p>I am using boto3, I need to list all elastic IPs, find the ones that are not associated with any instance and release them.</p> <p>What I am doing is:</p> <pre><code>import boto3 ec2 = boto3.resource('ec2') </code></pre> <p>Then I could list all volumes as this:</p> <pre><code>for volume in ec2.volumes.all(): </code></pre> <p>Or all instances like this:</p> <pre><code>for instance in ec2.instances.all(): </code></pre> <p>But I don't know how to list all elastic IPs.</p> <p>The boto3 documentation lists the object ClassicAddress which is what I need to have in order to release the IP.</p> <p><a href="http://boto3.readthedocs.io/en/latest/reference/services/ec2.html#classicaddress" rel="nofollow">http://boto3.readthedocs.io/en/latest/reference/services/ec2.html#classicaddress</a></p> <p>However, I don't know how to get a collection of all the ClassicAddresses</p>
1
2016-08-03T16:51:57Z
38,752,197
<p>I got it working with this code:</p> <pre><code>def elastic_ips_cleanup(): """ Cleanup elastic IPs that are not being used """ client = boto3.client('ec2') addresses_dict = client.describe_addresses() for eip_dict in addresses_dict['Addresses']: if "InstanceId" not in eip_dict: print (eip_dict['PublicIp'] + " doesn't have any instances associated, releasing") client.release_address(AllocationId=eip_dict['AllocationId']) </code></pre>
0
2016-08-03T19:33:28Z
[ "python", "amazon-web-services", "amazon-ec2", "boto", "boto3" ]
Python: draw scatter with marker size coming from a dictionary?
38,749,490
<p>Say I have a regular grid of <code>nxn</code> points, and a dictionary telling me how many times something happens in each one of the points:</p> <pre><code>d={ (0, 0): 1114, (0, 1): 270, (3, 2): 217, (5, 6): 189, (10, 10): 164} </code></pre> <p>I want to plot a scatter of these points, the size of the markers being assigned by the corresponding value of the dict. <strong>How can I do this?</strong></p> <p>I know I can draw a scatter like this, but how to structure <code>s</code>, the list of sizes?</p> <pre><code>#Import section #defining d xticks = [0,1,2,3,4,5,6,7,8,9,10] yticks = [0,1,2,3,4,5,6,7,8,9,10] plt.xticks(xticks) plt.yticks(yticks) plt.xlabel("x") plt.ylabel("y",rotation=0) plt.title('my map') s=[] #How to structure this? plt.scatter(x, y,color='yellow',s=s) plt.show() </code></pre>
0
2016-08-03T16:52:23Z
38,749,704
<p><code>X</code> <code>Y</code> and <code>S</code> are all parallel lists, so for every <code>x[n]</code> will corrospond to <code>y[n]</code> and <code>s[n]</code>. You can just iterate over the dictionary and append to all three lists simultaneously:</p> <pre><code>x_arr,y_arr,s_arr = [], [], [] for (x,y),s in d.items(): x_arr.append(x) y_arr.append(y) s_arr.append(s) plt.scatter(x_arr, y_arr,color='yellow',s=s_arr) </code></pre> <p>There are probably more efficient ways of accomplishing this but this demonstrates how the input should be structured.</p>
2
2016-08-03T17:03:14Z
[ "python", "dictionary", "matplotlib", "scatter-plot" ]
Global Python package
38,749,534
<p>so I have this package. In the cmd I go to <code>hp@HP-PC C:\Users\hp\Documents\scripts</code>:</p> <pre><code>hp@HP-PC C:\Users\hp\Documents\scripts &gt; python Python 3.5.2 |Anaconda 4.1.1 (64-bit)| (default, Jul 5 2016, 11:41:13) [MSC v.1900 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import toolzz.printer as t &gt;&gt;&gt; t.printz() 5 </code></pre> <p>Everything is working fine but I want to have a directory in which I could add my scripts and be able to open my cmd->python->import my package and do whatever I am going to do and not get this instead:</p> <pre><code>hp@HP-PC C:\Users\hp &gt; python Python 3.5.2 |Anaconda 4.1.1 (64-bit)| (default, Jul 5 2016, 11:41:13) [MSC v.1900 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import toolzz Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ImportError: No module named 'toolzz' &gt;&gt;&gt; </code></pre> <p>PS: keep in mind I have added the directory <code>scripts</code> to the path and I have global bat files which work</p>
-2
2016-08-03T16:53:53Z
38,749,710
<p>Run</p> <pre><code>python -m site </code></pre> <p>It'll list 2 important pieces of information:</p> <ul> <li>The Python module search path, <code>sys.path</code></li> <li>The location for the <code>USER_SITE</code> directory, and wether or not this exists.</li> </ul> <p>Python looks for modules along those locations. Put your module in a <code>sys.path</code> location (in one that ends in <code>site-packages</code> preferably), or make sure you created the <code>USER_SITE</code> directory and put your code in there.</p> <p>And you can always extend the path by setting the <a href="https://docs.python.org/3/using/cmdline.html#envvar-PYTHONPATH" rel="nofollow"><code>PYTHONPATH</code> environment variable</a>.</p>
1
2016-08-03T17:03:42Z
[ "python" ]
Python 3 - Tkinter button commands
38,749,620
<p>I am new to Tkinter and Python as well. I have three buttons with commands in my Tkinter frame. Button 1 calls open_csv_dialog(), opens a file dialog box to select a .csv file and returns the path. Button 2 calls save_destination_folder(), opens a file dialog box to open the preferred directory and return the path. </p> <p>My problem is with Button 3. It calls modify_word_doc() which needs the filepaths returned from button 1 and button 2.</p> <p>I have tried;</p> <pre><code>button3 = ttk.Button(root, text="Run", command=lambda: modify_word_doc(open_csv_dialog, save_destination_folder)).pack() </code></pre> <p>but that obviously just prompts the file dialog box to open again for both the open_csv_dialog() and save_destination_folder() function which is undesired. I would like to just use the file path that was already returned from these two functions and pass it into modify_word_doc without being prompted by another file dialog box. I have also tried to use <code>partial</code> but I'm either using it wrong or it still has the same undesired consequences.</p> <p>I have read the Tkinter docs about commands and searched SO for a possible answer, so apologies if this has been answered before and I failed to find it.</p> <pre><code>import tkinter as tk from tkinter import filedialog from tkinter import ttk import os import csv import docx from functools import partial root = tk.Tk() def open_csv_dialog(): file_path = filedialog.askopenfilename(filetypes=(("Database files", "*.csv"),("All files", "*.*"))) return file_path def save_destination_folder(): file_path = filedialog.askdirectory() return file_path def modify_word_doc(data, location): #data = open_csv_dialog() #location = save_destination_folder() #long code. takes .csv file path opens, reads and modifies word doc with #the contents of the .csv, then saves the new word doc to the requested #file path returned from save_destination_folder(). label = ttk.Label(root, text="Step 1 - Choose CSV File.", font=LARGE_FONT) label.pack(pady=10, padx=10) button = ttk.Button(root, text="Choose CSV", command= open_csv_dialog).pack() label = ttk.Label(root, text="Step 2 - Choose destination folder for your letters.", font=LARGE_FONT) label.pack(pady=10, padx=10) button2 = ttk.Button(root, text="Choose Folder", command=save_destination_folder).pack() label = ttk.Label(root, text="Step 3 - Select Run.", font=LARGE_FONT) label.pack(pady=10, padx=10) button3 = ttk.Button(root, text="Run", command=lambda: modify_word_doc(open_csv_dialog, save_destination_folder)).pack() root.mainloop() </code></pre>
1
2016-08-03T16:58:30Z
38,750,155
<p>This was probably just an error typing the question.... but for completeness on this line</p> <pre><code>button3 = ttk.Button(root, text="Run", command=lambda: modify_word_doc(open_csv_dialog, save_destination_folder).pack() </code></pre> <p>You're missing the closing parenthesis for <code>ttk.Button(*)*.pack()</code></p> <p>It should be (syntactically):</p> <pre><code> button3 = ttk.Button(root, text="Run", command=lambda: modify_word_doc(open_csv_dialog, save_destination_folder)).pack() </code></pre> <p>Also, using <code>.pack()</code> returns <code>None</code> so setting a variable to a widget + geometry manager method just sets that variable to nothing, instead of a reference to the widget object.</p> <p>So, if you actually need a reference to this widget you should actually do:</p> <pre><code> button3 = ttk.Button(*) button3.pack() </code></pre> <p>If you don't need a reference then just don't assign anything and save yourself some typing, since it's redundant.</p> <p>For the actual question:</p> <p>If I understand your question, you have two buttons which set the file path of the .csv and the destination folder. However, since both your functions use the dialog you are being prompted again even though the may have already been chosen.</p> <p>You could use globals and various other ways to do this, I'll set an attribute on the base root window since i think this is easiest here...</p> <p>In the below code what I did was simply set an attribute on the <code>root</code> window if the <code>file_path</code> has been selected. You can check this with an <code>if</code> statement.</p> <p>Then on either I call <code>check_state</code> to see if the root window has both of these attributes <code>getattr(object, string, default)</code> will return the attribute or the default if the attribute does not exists. So, by setting the file_path to the string, or None if the location was re-selected the state will always be updated correctly.</p> <p>You can clean this up some more. You could actually make both of those one function etc if you really wanted to.</p> <pre><code>import tkinter as tk from tkinter import filedialog, ttk def check_state(): if getattr(root, 'csv_path', False) and getattr(root, 'dest_path', False): button3['state'] = 'normal' else: button3['state'] = 'disabled' def open_csv_dialog(): file_path = filedialog.askopenfilename( filetypes=(("Database files", "*.csv"), ("All files", "*.*"))) if file_path: root.csv_path = file_path else: root.csv_path = None check_state() def save_destination_folder(): file_path = filedialog.askdirectory() if file_path: root.dest_path = file_path else: root.dest_path = None check_state() def modify_word_doc(): print(root.csv_path, root.dest_path) root = tk.Tk() ttk.Label(root, text="Step 1 - Choose CSV File.",).pack(pady=10, padx=10) ttk.Button(root, text="Choose CSV", command= open_csv_dialog).pack() ttk.Label(root, text="Step 2 - Choose destination folder for your letters.").pack(pady=10, padx=10) ttk.Button(root, text="Choose Folder", command=save_destination_folder).pack() ttk.Label(root, text="Step 3 - Select Run.").pack(pady=10, padx=10) #We need a reference to the widget here, for the state func... button3 = ttk.Button(root, text="Run", state='disabled', command=modify_word_doc) button3.pack() root.mainloop() </code></pre>
1
2016-08-03T17:28:46Z
[ "python", "tkinter" ]
operations with elements in list of list in python
38,749,675
<p>This is my list:</p> <pre><code>volume = [['1.986', '3000'], ['1.987', '2000'], ['1.986', '700'],['1.987', '4000']] </code></pre> <p>How can I get the sum of volume[1] when volume[0] is the same price?</p> <pre><code>results = [['1.986', '3700'], ['1.987', '6000']] </code></pre>
-4
2016-08-03T17:01:21Z
38,749,795
<p>Dictionaries would be a good data structure to use here. The default dict holds unique strings as the keys and assumes empty values are 0 because I set it to be based off of int. </p> <pre><code>from collections import defaultdict d = defaultdict(int) for v in volume: d[v[0]] += int(v[1]) print d </code></pre> <p>If you need a list afterwards you can use a list comprehension:</p> <p><code>list_version = [[key, value] for key,value in d]</code></p>
2
2016-08-03T17:09:07Z
[ "python", "list" ]
Clean unicode before adding to Dictionary
38,749,676
<p>When parsing a page, I am pulling:</p> <pre><code>'label_value': [u'\n\t\t\t\t\t\t\t\t\t\tabc123\n\t\t\t\t\t\t\t\t\t']} </code></pre> <p>My goal is to just pull the relevant "abc123" from that xpath when it writes to the CSV. Currently, due to the "\n\t" in the string, it isn't writing anything. Looking around, I found several methods how to accomplish this, but I have been unable to properly place it within my own code and have it execute properly.</p> <p>I've been playing with regex and .translate() to remove the instances of \n\t and clean up the code to cleanly add it to a csv. I didn't have much success with regex since these are pullings as lists, so I ceded to using .translate().</p> <p>Below, I added my code for defining the xpaths and the actual page parsing. There is a step between that kicks off the spider and parses an initial page, but I didn't find that relevant to this question so omitted it from the code.</p> <p>Of the sections below, where would I want to add this code? Would it be when I define the label_value's xpath, in the initial spider, or when I'm actually extracting it to my ResultsDict?</p> <pre><code>label_value = './/*[@class="lorem-ipsum"] </code></pre> <p>instead use... </p> <pre><code>label_value = './/*[@class="lorem-ipsum"].translate(None, '\t\n ') </code></pre> <p>or...</p> <pre><code>def parsepage(self, response) time.sleep(2) self.driver.get(response.url) selectable_page = Selector(text=self.driver.page_source) ResultsDict = scraperpageitems() ResultsDict['label_value'] = selectable_page.xpath(label_value).extract() </code></pre> <p>instead use...</p> <pre><code> ResultsDict['label_value'] = selectable_page.xpath(label_value).extract().translate(None, '\t\n ') </code></pre>
3
2016-08-03T17:01:25Z
38,751,148
<p>Aren't you simply looking for <code>strip()</code> ?<br> Consider this example (see it <a href="http://ideone.com/CuRgKP" rel="nofollow"><strong>working on ideone.com</strong></a>)</p> <pre><code>label_value = ''' abc123 ''' print(label_value) print(label_value.strip()) </code></pre> <p><hr> For the records, this did the trick:</p> <pre><code>[x.strip() for x in selectable_page.xpath(label_value).extract()] </code></pre>
2
2016-08-03T18:30:07Z
[ "python", "regex", "xpath" ]
Clean unicode before adding to Dictionary
38,749,676
<p>When parsing a page, I am pulling:</p> <pre><code>'label_value': [u'\n\t\t\t\t\t\t\t\t\t\tabc123\n\t\t\t\t\t\t\t\t\t']} </code></pre> <p>My goal is to just pull the relevant "abc123" from that xpath when it writes to the CSV. Currently, due to the "\n\t" in the string, it isn't writing anything. Looking around, I found several methods how to accomplish this, but I have been unable to properly place it within my own code and have it execute properly.</p> <p>I've been playing with regex and .translate() to remove the instances of \n\t and clean up the code to cleanly add it to a csv. I didn't have much success with regex since these are pullings as lists, so I ceded to using .translate().</p> <p>Below, I added my code for defining the xpaths and the actual page parsing. There is a step between that kicks off the spider and parses an initial page, but I didn't find that relevant to this question so omitted it from the code.</p> <p>Of the sections below, where would I want to add this code? Would it be when I define the label_value's xpath, in the initial spider, or when I'm actually extracting it to my ResultsDict?</p> <pre><code>label_value = './/*[@class="lorem-ipsum"] </code></pre> <p>instead use... </p> <pre><code>label_value = './/*[@class="lorem-ipsum"].translate(None, '\t\n ') </code></pre> <p>or...</p> <pre><code>def parsepage(self, response) time.sleep(2) self.driver.get(response.url) selectable_page = Selector(text=self.driver.page_source) ResultsDict = scraperpageitems() ResultsDict['label_value'] = selectable_page.xpath(label_value).extract() </code></pre> <p>instead use...</p> <pre><code> ResultsDict['label_value'] = selectable_page.xpath(label_value).extract().translate(None, '\t\n ') </code></pre>
3
2016-08-03T17:01:25Z
38,751,151
<p>Probably the best way is to trim the whitespaces. </p> <p>Something like do a global<br> Find <code>^\s+|\s+$</code><br> and replace with nothing. </p> <p>You mentioned stripping Unicode.<br> If you want to strip Unicode as well, use <code>^\s+|[\x{100}-\x{10ffff}]+|\s+$</code><br> Not sure what Python uses for <em>Unicode</em> in classes, use whatever form<br> they make available <code>\uXXXX</code> or <code>\UXXXXXX</code> and braces <code>{}</code> as needed. </p>
0
2016-08-03T18:30:16Z
[ "python", "regex", "xpath" ]
Clean unicode before adding to Dictionary
38,749,676
<p>When parsing a page, I am pulling:</p> <pre><code>'label_value': [u'\n\t\t\t\t\t\t\t\t\t\tabc123\n\t\t\t\t\t\t\t\t\t']} </code></pre> <p>My goal is to just pull the relevant "abc123" from that xpath when it writes to the CSV. Currently, due to the "\n\t" in the string, it isn't writing anything. Looking around, I found several methods how to accomplish this, but I have been unable to properly place it within my own code and have it execute properly.</p> <p>I've been playing with regex and .translate() to remove the instances of \n\t and clean up the code to cleanly add it to a csv. I didn't have much success with regex since these are pullings as lists, so I ceded to using .translate().</p> <p>Below, I added my code for defining the xpaths and the actual page parsing. There is a step between that kicks off the spider and parses an initial page, but I didn't find that relevant to this question so omitted it from the code.</p> <p>Of the sections below, where would I want to add this code? Would it be when I define the label_value's xpath, in the initial spider, or when I'm actually extracting it to my ResultsDict?</p> <pre><code>label_value = './/*[@class="lorem-ipsum"] </code></pre> <p>instead use... </p> <pre><code>label_value = './/*[@class="lorem-ipsum"].translate(None, '\t\n ') </code></pre> <p>or...</p> <pre><code>def parsepage(self, response) time.sleep(2) self.driver.get(response.url) selectable_page = Selector(text=self.driver.page_source) ResultsDict = scraperpageitems() ResultsDict['label_value'] = selectable_page.xpath(label_value).extract() </code></pre> <p>instead use...</p> <pre><code> ResultsDict['label_value'] = selectable_page.xpath(label_value).extract().translate(None, '\t\n ') </code></pre>
3
2016-08-03T17:01:25Z
38,753,900
<p>I credit @Martjin for this solution... (I take credit for the comment)</p> <pre><code>#UNICODE is a pain in my ass! below is a function to strip-out and replace with a space. def remove_non_ascii(text): return ''.join([i if ord(i) &lt; 128 else ' ' for i in text]) </code></pre>
0
2016-08-03T21:25:01Z
[ "python", "regex", "xpath" ]
python no such element: unable to locate element {"method": "id","selector":"email"}
38,749,756
<p>having trouble with my python code. i keep getting python no such element: unable to locate element {"method": "id","selector":"email"}</p> <pre><code> self.driver.get(redirecturl) email = "testmail02015@gmail.com" Password = "Passw0rd123" emailFieldID = "email" passwordFieldID = "password" loginButtonXpath = "//button[@value='btnLogin']" self.driver.find_element_by_id(emailFieldID).send_keys(email) self.driver.find_element_by_id(passwordFieldID).send_keys(Password) self.driver.find_element_by_xpath(loginButtonXpath).click() </code></pre>
-3
2016-08-03T17:06:48Z
38,750,001
<p>Usually the problem is that <code>find_element</code> runs too quickly before page fully loaded. So try to wait for elements to appear (in the example it waits for maximum of 10 seconds; less if element appears earlier):</p> <pre><code>... emailFieldID = "email" ... WebDriverWait(browser, 10).until(EC.presence_of_element_located(browser.find_element_by_id(emailFieldID))) self.driver.find_element_by_id(emailFieldID).send_keys(email) </code></pre> <p>After that you can use <code>find_element</code> as usual.</p>
3
2016-08-03T17:19:50Z
[ "python", "selenium-webdriver" ]
sympy array of expressions to numpy array
38,749,771
<p>I got a sympy array</p> <pre><code>sympyarray = Matrix([[2/(dx**2*(exp(I*theta) + 1)), -2*exp(-I*theta)/dx**2, 2*exp(-I*theta)/(dx**2*(exp(I*theta) + 1))]]) </code></pre> <p>and want to transform it into a numpy array</p> <pre><code>numpyarray=np.array([2/(dx**2*(np.exp(1j*theta) + 1)), -2*np.exp(-1j*theta)/dx**2, 2*np.exp(-1j*theta)/(dx**2*(np.exp(1j*theta) + 1))]) </code></pre> <p>and wonder if there are any good way to do this? </p> <p>My method has until now been the following:</p> <ol> <li>convert the complex " I " in sympyarray to "1j" using sympy.subs</li> <li><p>convert the sympy array into numpy array using</p> <p>numpyarray = sympyarray.tolist()</p></li> <li>inserting "np." before all the exp(1j*theta) in the printed numpyarray, since the .tolist() dont change the sympy exponential into a numpy exponential. </li> </ol> <p>It surely must be an easier way? </p> <p>Note: To my knowlage, lambdify is not the answer here. As I read the documentation, lambdify converts a sympy expression into a function that need numerical input? Or am I way off?</p>
1
2016-08-03T17:07:45Z
38,775,519
<p>Use <code>lambdify</code>:</p> <pre><code>In [10]: expr = Matrix([[2/(dx**2*(exp(I*theta) + 1)), -2*exp(-I*theta)/dx**2, 2*exp(-I*theta)/(dx**2*(exp(I*theta) + 1))]]) In [12]: f = lambdify([dx, theta], expr, 'numpy') In [15]: f(np.array([1], dtype=complex), np.array([np.pi], dtype=complex)) Out[15]: array([[[ 0. -1.63312394e+16j], [ 2. +2.44929360e-16j], [-2. +1.63312394e+16j]]]) </code></pre>
1
2016-08-04T19:10:54Z
[ "python", "arrays", "numpy", "sympy" ]
Pandas - DataFrame reindex function returns a warning
38,749,887
<p>Whats wrong with the code?: Its returning a warning :</p> <blockquote> <p>Warning (from warnings module): File "C:\Python27\lib\site-packages\numpy\core\numeric.py", line 2515 return bool(asarray(a1 == a2).all()) FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison</p> </blockquote> <pre><code>import pandas as pd import numpy as np Data1 = {'State':['Ohio','Ohio','Ohio','Nevada','Nevada'],'Year':[2000,2001,2002,2001,2002],'POP':[1.5,1.7,3.6,2.4,2.9]} Frame4 =pd.DataFrame(Data1) print('\n') print Frame4 Frame5 = Frame4.reindex(['a','b','c','d','e']) print Frame5 my o/p POP State Year 0 1.5 Ohio 2000 1 1.7 Ohio 2001 2 3.6 Ohio 2002 3 2.4 Nevada 2001 4 2.9 Nevada 2002 Warning (from warnings module): File "C:\Python27\lib\site-packages\numpy\core\numeric.py", line 2515 return bool(asarray(a1 == a2).all()) FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison POP State Year a NaN NaN NaN b NaN NaN NaN c NaN NaN NaN d NaN NaN NaN e NaN NaN NaN </code></pre>
2
2016-08-03T17:13:58Z
38,751,503
<p>You must use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.rename.html" rel="nofollow"><code>rename</code></a> instead of <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reindex.html" rel="nofollow"><code>reindex</code></a> as you are trying to change the <em>names</em> of the index axis.</p> <pre><code>Frame5 = Frame4.rename({0:'a', 1:'b', 2:'c', 3:'d', 4:'e'}) print(Frame5) POP State Year a 1.5 Ohio 2000 b 1.7 Ohio 2001 c 3.6 Ohio 2002 d 2.4 Nevada 2001 e 2.9 Nevada 2002 </code></pre> <p>The purpose of applying <code>reindex</code> is to align the indices of the dataframe in the new index selection logic.</p> <p>By default, values in the new index that do not have corresponding records in the dataframe are assigned <code>NaN</code>.</p> <p>Hence, when you specified the new index logic as <code>list('abcde')</code>, it checked all the index values but couldn't find a match as the prior indices had been in <code>range(0,4)</code>. So, it returned <code>Nans</code>instead.</p>
0
2016-08-03T18:51:12Z
[ "python", "pandas", "dataframe" ]
Pandas - DataFrame reindex function returns a warning
38,749,887
<p>Whats wrong with the code?: Its returning a warning :</p> <blockquote> <p>Warning (from warnings module): File "C:\Python27\lib\site-packages\numpy\core\numeric.py", line 2515 return bool(asarray(a1 == a2).all()) FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison</p> </blockquote> <pre><code>import pandas as pd import numpy as np Data1 = {'State':['Ohio','Ohio','Ohio','Nevada','Nevada'],'Year':[2000,2001,2002,2001,2002],'POP':[1.5,1.7,3.6,2.4,2.9]} Frame4 =pd.DataFrame(Data1) print('\n') print Frame4 Frame5 = Frame4.reindex(['a','b','c','d','e']) print Frame5 my o/p POP State Year 0 1.5 Ohio 2000 1 1.7 Ohio 2001 2 3.6 Ohio 2002 3 2.4 Nevada 2001 4 2.9 Nevada 2002 Warning (from warnings module): File "C:\Python27\lib\site-packages\numpy\core\numeric.py", line 2515 return bool(asarray(a1 == a2).all()) FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison POP State Year a NaN NaN NaN b NaN NaN NaN c NaN NaN NaN d NaN NaN NaN e NaN NaN NaN </code></pre>
2
2016-08-03T17:13:58Z
38,751,823
<p>Try this: </p> <pre><code>Frame4 =pd.DataFrame(Data1) print('\n') print Frame4 Frame4.index = ['a','b','c','d','e'] print Frame4 POP State Year 0 1.5 Ohio 2000 1 1.7 Ohio 2001 2 3.6 Ohio 2002 3 2.4 Nevada 2001 4 2.9 Nevada 2002 POP State Year a 1.5 Ohio 2000 b 1.7 Ohio 2001 c 3.6 Ohio 2002 d 2.4 Nevada 2001 e 2.9 Nevada 2002 </code></pre>
0
2016-08-03T19:09:43Z
[ "python", "pandas", "dataframe" ]
Python-get string between to characters
38,749,896
<p>I need to one give me the string between <code>~</code> and <code>^</code>.<br> I have a string like this:</p> <pre><code>~~~~ ABC ^ DEF ^ HGK &gt; LMN ^ </code></pre> <p>I need to get the string between them with python.<br> I've tried this:</p> <pre><code>import re target = ' ~~~~ ABC ^ DEF ^ HGK &gt; LMN ^ ' matchObj = re.findall(r'~(.*?)\^', target) print matchObj </code></pre> <p>But the result is:</p> <pre><code>['~~~ ABC '] </code></pre> <p>What I expect is:</p> <pre><code>[ABC , DEF , HGK , LMN ] </code></pre> <p>or </p> <pre><code>[^ABC , ^DEF , ^HGK , LMN ] </code></pre>
-2
2016-08-03T17:14:24Z
38,750,004
<p>I'm not sure exactly what result is desired, but perhaps this?</p> <pre><code>&gt;&gt;&gt; matchObj = re.findall(r'~+(.*?)\^', target) &gt;&gt;&gt; print(matchObj) [' ABC '] </code></pre>
0
2016-08-03T17:19:53Z
[ "python" ]
Python-get string between to characters
38,749,896
<p>I need to one give me the string between <code>~</code> and <code>^</code>.<br> I have a string like this:</p> <pre><code>~~~~ ABC ^ DEF ^ HGK &gt; LMN ^ </code></pre> <p>I need to get the string between them with python.<br> I've tried this:</p> <pre><code>import re target = ' ~~~~ ABC ^ DEF ^ HGK &gt; LMN ^ ' matchObj = re.findall(r'~(.*?)\^', target) print matchObj </code></pre> <p>But the result is:</p> <pre><code>['~~~ ABC '] </code></pre> <p>What I expect is:</p> <pre><code>[ABC , DEF , HGK , LMN ] </code></pre> <p>or </p> <pre><code>[^ABC , ^DEF , ^HGK , LMN ] </code></pre>
-2
2016-08-03T17:14:24Z
38,750,011
<p>Without regex:</p> <pre><code>&gt;&gt;&gt; "".join([x for x in target if x.isalpha() or x == ' ']).split() ['ABC', 'DEF', 'HGK', 'LMN'] </code></pre> <p>This takes space and alpha characters and creates a new string then splits it into words in a list</p> <p>Here is my exact code from python 3 command line:</p> <pre><code>&gt;&gt;&gt; target = ' ~~~~ ABC ^ DEF ^ HGK &gt; LMN ^ ' &gt;&gt;&gt; xx = "".join([x for x in target if x.isalpha() or x == ' ']).split() &gt;&gt;&gt; xx ['ABC', 'DEF', 'HGK', 'LMN'] &gt;&gt;&gt; </code></pre>
0
2016-08-03T17:20:15Z
[ "python" ]
Python-get string between to characters
38,749,896
<p>I need to one give me the string between <code>~</code> and <code>^</code>.<br> I have a string like this:</p> <pre><code>~~~~ ABC ^ DEF ^ HGK &gt; LMN ^ </code></pre> <p>I need to get the string between them with python.<br> I've tried this:</p> <pre><code>import re target = ' ~~~~ ABC ^ DEF ^ HGK &gt; LMN ^ ' matchObj = re.findall(r'~(.*?)\^', target) print matchObj </code></pre> <p>But the result is:</p> <pre><code>['~~~ ABC '] </code></pre> <p>What I expect is:</p> <pre><code>[ABC , DEF , HGK , LMN ] </code></pre> <p>or </p> <pre><code>[^ABC , ^DEF , ^HGK , LMN ] </code></pre>
-2
2016-08-03T17:14:24Z
38,750,046
<p>Your idea of using a lazy quantifier is good, but that still doesn't necessarily give you the shortest possible match - only the shortest match from the current position of the regex engine. If you want to disallow the start/end separators from being part of the match, you need to explicitly exclude them from the list of valid characters. A negated <a href="http://www.regular-expressions.info/charclass.html" rel="nofollow">character class</a> comes in handy here.</p> <pre><code>target = ' ~~~~ ABC ^ DEF ^ HGK &gt; LMN ^ ' matches = re.findall(r'~([^~^]*)\^', target) print matches </code></pre>
0
2016-08-03T17:22:22Z
[ "python" ]
Python-get string between to characters
38,749,896
<p>I need to one give me the string between <code>~</code> and <code>^</code>.<br> I have a string like this:</p> <pre><code>~~~~ ABC ^ DEF ^ HGK &gt; LMN ^ </code></pre> <p>I need to get the string between them with python.<br> I've tried this:</p> <pre><code>import re target = ' ~~~~ ABC ^ DEF ^ HGK &gt; LMN ^ ' matchObj = re.findall(r'~(.*?)\^', target) print matchObj </code></pre> <p>But the result is:</p> <pre><code>['~~~ ABC '] </code></pre> <p>What I expect is:</p> <pre><code>[ABC , DEF , HGK , LMN ] </code></pre> <p>or </p> <pre><code>[^ABC , ^DEF , ^HGK , LMN ] </code></pre>
-2
2016-08-03T17:14:24Z
38,752,819
<p>here is my solution:</p> <p>your input:</p> <pre><code>In [12]: target = ' ~~~~ ABC ^ DEF ^ HGK &gt; LMN ^ ' </code></pre> <p>replace all the symbols or delimiters with <code>' '</code> and split the result</p> <pre><code>In [13]: b = re.sub(r'[^\w]', ' ', target).split() In [14]: b Out[14]: ['ABC', 'DEF', 'HGK', 'LMN'] </code></pre>
0
2016-08-03T20:14:27Z
[ "python" ]
Can't get data from Django View into template
38,749,924
<p>I'm trying to send some data for rendering a table in a template. The data is not a <code>QuerySet</code> or anything, it's a custom list of tuples that I get from a Django Rest Framework endpoint.</p> <p>I have the following view:</p> <pre><code>class GetPointsView(FormView): form_class = forms.GetPointsForm template_name = 'get_points.html' success_url = reverse_lazy('get_points') def post(self, request, *args, **kwargs): form_class = self.get_form_class() form = self.get_form(form_class) var = request.POST['var_field'] if form.is_valid(): # Call another view to get the data, based on 'var'. response = MyView().get(request, var) # The template never handles this data. data = json.loads(response.data) # And even this doesn't work... # data = [('foo', 'bar'), ('baz', 'guido')] return HttpResponseRedirect( self.get_success_url(), {'mydata': data} ) else: return self.form_invalid(form) </code></pre> <p>And the following template:</p> <pre><code>{% extends 'base.html' %} {% load bootstrap3 %} {% load crispy_forms_tags %} {% block content %} {% crispy form %} {% if mydata %} &lt;hr&gt; &lt;table&gt; &lt;tr&gt; &lt;th&gt;Col A&lt;/th&gt; &lt;th&gt;Col B&lt;/th&gt; &lt;/tr&gt; {% for cola, colb in mydata %} &lt;tr&gt; &lt;td&gt;{{ cola }}&lt;/td&gt; &lt;td&gt;{{ colb }}&lt;/td&gt; &lt;/tr&gt; {% endfor %} &lt;/table&gt; {% endif %} {% endblock %} </code></pre> <p><code>{% if mydata %}}</code> appears never to be true. The fact that <code>data = [('foo', 'bar'), ('baz', 'guido')]</code> does not even work, suggests I'm missing something here.</p> <p>Am I doing something wrong with the format of the data, or how I'm sending it to the template?</p> <hr> <p><strong>Edit with answer</strong></p> <p>So, although I tried Django's <code>render</code> shortcut before, I was only able to get it working now. This is what solved my problem:</p> <pre><code>return render(self.request, self.template_name, {'form': form, 'mydata': data}) </code></pre>
0
2016-08-03T17:15:44Z
38,750,244
<p>The key in your rendering context is 'mydata', so you should use <code>{% if mydata %}</code>. Also you have an extra <code>}</code> at the end of that line.</p>
0
2016-08-03T17:33:32Z
[ "python", "django", "django-templates" ]
Inserting data into XML file with python
38,749,937
<p>I'm working with specific sets of data that I want to insert into an existing file in a fixed section. I want to alter the XML file from looking like this:</p> <pre><code>&lt;SBEDataUploadFile&gt; &lt;ApplicationData&gt; &lt;firmware&gt; &lt;SoftwareVersion&gt;1.0&lt;/SoftwareVersion&gt; &lt;BuildDate&gt;Dec 1 2012 10:43:42&lt;/BuildDate&gt; &lt;/firmware&gt; &lt;/ApplicationData&gt; &lt;/SBEDataUploadFile&gt; </code></pre> <p>to look like this:</p> <pre><code>&lt;SBEDataUploadFile&gt; &lt;![CDATA[ ** Location 001 ** Latitude In 18.33885 ** Longitude In 64.97647 ** Time In 11:55 ** Depth (ft) 10 ** Line Out (ft) 5 ** Time Out 11:56 ** Latitude Out 18.33885 ** Longitude Out 64.97647 ** Notes ]]&gt; &lt;ApplicationData&gt; &lt;firmware&gt; &lt;SoftwareVersion&gt;1.0&lt;/SoftwareVersion&gt; &lt;BuildDate&gt;Dec 1 2012 10:43:42&lt;/BuildDate&gt; &lt;/firmware&gt; &lt;/ApplicationData&gt; &lt;/SBEDataUploadFile&gt; </code></pre> <p>I tried this with <code>xml.etree.ElementTree</code>, but my result is that it appends the comment to the bottom after the <code>&lt;/ApplicantionData&gt;</code>. Here's my current code:</p> <pre><code>import xml.etree.ElementTree as ET #variables location = "BPT" latitude_in = 0 longitude_in = 0 time_in = 0 depth = 0 line_out = 0 time_out = 0 latitude_out = 0 longitude_out = 0 notes = "" #formatting and converting all variables to string toString = "&lt;![CDATA["+"\n"+"** Location "+location+"\n"+"** Latitude In "\ +str(latitude_in)+"\n"+"** Longitude In "+str(longitude_in)+"\n"+\ "** Time In "+str(time_in)+"\n"+"** Depth (ft) "+str(depth)+"\n"+"** Line Out (ft) "\ +str(line_out)+"\n"+"** Time Out "+str(time_out)+"\n"+"** Latitude Out "\ +str(latitude_out)+"\n"+"** Longitude Out "+str(longitude_out)+"\n"+"** Notes "+notes+"\n"+"]]&gt;" xml_filepath = xmlfilepath.xml xml_tree = ET.parse(xml_filepath) xml_root = xml_tree.getroot() ET.SubElement(xml_root, toString) print ET.tostring(xml_root) </code></pre> <p>and these are my current results:</p> <pre><code>&lt;SBEDataUploadFile&gt; &lt;ApplicationData&gt; &lt;firmware&gt; &lt;SoftwareVersion&gt;1.0&lt;/SoftwareVersion&gt; &lt;BuildDate&gt;Dec 1 2012 10:43:42&lt;/BuildDate&gt; &lt;/firmware&gt; &lt;/ApplicationData&gt; &lt;&lt;![CDATA[ ** Location BPT ** Latitude In 0 ** Longitude In 0 ** Time In 0 ** Depth (ft) 0 ** Line Out (ft) 0 ** Time Out 0 ** Latitude Out 0 ** Longitude Out 0 ** Notes ]]&gt; /&gt;&lt;/SBEDataUploadFile&gt; </code></pre> <p>I want this to be able to make it look like my desired results and get rid of that extra <code>/&gt;</code> right before the <code>&lt;/SBEDataUploadFile&gt;</code>.</p>
0
2016-08-03T17:16:27Z
38,750,196
<p>You don't need a <code>SubElement</code>. Just set the text node on the root element:</p> <pre><code>xml_root.text = toString </code></pre>
0
2016-08-03T17:31:18Z
[ "python", "xml", "parsing", "insert", "elementtree" ]
Calling a python script from a Java jar file
38,749,991
<p>I am working on a project using Java and Python using Java for the GUI and Python for the backend. The Java program calls a Python script when a button is pressed using the following code:</p> <pre><code>Runtime r = Runtime.getRuntime(); String pyScript = "resources/script.py"; String scriptPath = getClass().getResource(pyScript).toExternalForm(); // Strip "file/" from path scriptPath = scriptPath.substring(scriptPath.indexOf("/") + 1); Process p = r.exec("python " + scriptPath) </code></pre> <p>The python script is located in a folder called resources in the src folder of the Java project. This code works when I run my program in my IDE (IntelliJ) however when I create a .jar file and attempt to run the script nothing occurs. I can confirm that the program does still find the script within the .jar file. How can I get the script to run?</p>
0
2016-08-03T17:19:12Z
38,759,120
<p>In this solution, we run the script if the file exists. The script could be on a full or relative path. The script is not in the jar file.</p> <blockquote> <p>TestPython.java</p> </blockquote> <pre><code>import java.lang.*; import java.io.*; public class TestPython { public static void main(String[] args) { System.out.println("I will run a Python script!"); Runtime r = Runtime.getRuntime(); String pyScript = "py/test.py"; File f = new File(pyScript); if (f.exists() &amp;&amp; !f.isDirectory()) { try { Process p = r.exec("python " + pyScript); BufferedReader in = new BufferedReader( new InputStreamReader(p.getInputStream())); String line = null; while ((line = in .readLine()) != null) { System.out.println(line); } System.out.println("Python script ran!!"); } catch (Exception ex) { System.out.println("Something bad happened!!"); ex.printStackTrace(); } } else { System.out.println("Unexistent file!" + pyScript); } } } </code></pre> <blockquote> <p>py/test.py</p> </blockquote> <pre><code>print("I'm a Python script!!!") </code></pre> <blockquote> <p><strong>Output:</strong> </p> <p>I will run a Python script!</p> <p>I'm a Python script!!! </p> <p>Python script ran!!</p> </blockquote>
0
2016-08-04T05:30:34Z
[ "java", "python", "pywin32" ]
Selenium execute_script adding "AI" to function
38,750,116
<p>I've selected a search button:</p> <pre><code>&lt;input type="button" name="Submit" value="Submit" onclick="FnAddSearchParameters();" class="myButton rightButton buttonGroup"&gt; </code></pre> <p>Using the chrome driver, I've been trying to click the button, to no avail. The regular <code>button.click()</code> function only highlights the button, but does not complete the onclick action.</p> <p>using <code>execute_script("FnAddSearchParameters();")</code> I get the error statement</p> <pre><code>selenium.common.exceptions.WebDriverException: Message: unknown error: window.opener.FnAddAISearchParameters is not a function </code></pre> <p>Any thoughts on why <code>AI</code> being added to the function call? Is there a way around this?</p>
1
2016-08-03T17:26:41Z
38,753,863
<p>Actually you are executing wrong using <code>execute_script</code>, you should try as below :-</p> <pre><code>button = driver.find_element_by_name("Submit") driver.execute_script("arguments[0].click()", button) </code></pre>
1
2016-08-03T21:21:51Z
[ "javascript", "python", "selenium" ]
python add items to list and stop when you get an empty value
38,750,174
<p>I have an excel document that I am reading, it has an unknown number of lines, I want to add each line and the three values of columns A B and C into a list and then stop once I reach none. I then want to run an action on each item in the list.</p> <p>I am terrible with <code>if/for loops</code> if someone could help.</p> <p>Below is loading argument 3 as the workbook and sheet. I need to start at line <code>A61</code> and add <code>A61,B61,C61</code> to a list and keep going until A whatever is = to none.</p> <p>Alright so I got this far, now how do I run a command for each item in the row?</p> <pre><code>if len(sys.argv) &gt; 3: wb = xlrd.open_workbook(sys.argv[3]) sheet = wb.sheet_by_index(0) first_kvm_ip = str(sheet.cell_value(34,1)) last_kvm_ip = str(sheet.cell_value(35,1)) kvm_netmask = str(sheet.cell_value(36,1)) rows = sheet.nrows curr_row = 52 while (curr_row &lt; rows - 1): curr_row += 1 row1 = int(sheet.cell_value(curr_row,0)) row2 = str(sheet.cell_value(curr_row,1)) vlanls1.append(row1) vlanls2.append(row2) </code></pre> <p>I want to run a command for each item in row1 vlan create(row1,row2)</p> <p>I assume I need a for i iteration. I just need help with that.</p> <p>I need to run this command for each iteration of row1 and row2</p> <pre><code>mo = FabricVlan(parent_mo_or_dn="fabric/lan", sharing="none", name=row2, id=row1, mcast_policy_name="", policy_owner="local", default_net="no", pub_nw_name="", compression_type="included") handle.add_mo(mo) </code></pre> <p>Alright I think I finally got it. Thanks for the help guys.</p> <pre><code>if len(sys.argv) &gt; 3: wb = xlrd.open_workbook(sys.argv[3]) sheet = wb.sheet_by_index(0) first_kvm_ip = str(sheet.cell_value(34,1)) last_kvm_ip = str(sheet.cell_value(35,1)) kvm_netmask = str(sheet.cell_value(36,1)) rows = sheet.nrows curr_row = 52 while (curr_row &lt; rows - 1): curr_row += 1 row1 = int(sheet.cell_value(curr_row,0)) row2 = str(sheet.cell_value(curr_row,1)) vlanls1.append(row1) vlanls2.append(row2) for x,y in zip(vlanls1,vlanls2): mo = FabricVlan(parent_mo_or_dn="fabric/lan", sharing="none", name=y, id=x, mcast_policy_name="", policy_owner="local", default_net="no", pub_nw_name="", compression_type="included") handle.add_mo(mo) </code></pre>
2
2016-08-03T17:29:41Z
38,751,980
<p><code>worksheet.rows</code> returns a list of all rows, no matter how many there are. Each row in that list is itself a list of the cells in that row. Knowing this, it would be fairly easy to implement a <code>for</code> loop that iterates through each row and appends the first three cells to a new list.</p> <p>This code should do the trick.</p> <pre><code>myList = [] for row in sheet.rows: myList.append([row[0],row[1],row[2]]) </code></pre> <p>I do recommend going through the openpyxl documentation though, it will avoid you some trouble to come. Also, read up on the way that for loops work if you know you have trouble with them :)</p> <p><a href="http://openpyxl.readthedocs.io/en/default/index.html" rel="nofollow">http://openpyxl.readthedocs.io/en/default/index.html</a></p> <p><a href="http://www.tutorialspoint.com/python/python_for_loop.htm" rel="nofollow">http://www.tutorialspoint.com/python/python_for_loop.htm</a></p>
1
2016-08-03T19:19:19Z
[ "python", "python-3.x", "if-statement", "for-loop" ]
Function that defines a function in python
38,750,177
<p>I have a program that defines the function <code>verboseprint</code> to either print or not print to the screen based on a boolean:</p> <pre><code># define verboseprint based on whether we're running in verbose mode or not if in_verbose_mode: def verboseprint (*args): for arg in args: print arg, print print "Done defining verbose print." else: # if we're not in verbosemode, do nothing verboseprint = lambda *a: None </code></pre> <p>My program uses multiple files, and I'd like to use this definition of verboseprint in all of them. All of the files will be passed the <code>in_verbose_mode</code> boolean. I know that I could just define <code>verboseprint</code> by itself in a file and then import it into all of my other files, but I need the function definition to be able to be declared two different ways based on a boolean. </p> <p>So in summary: I need a function that can declare another function in two different ways, that I can then import into multiple files.</p> <p>Any help would be appreciated. </p>
0
2016-08-03T17:29:50Z
38,750,404
<p>Usually you don't want define a function in this way.</p> <p>And I think the easy way to achieve this is you pass the boolean as a function parameter and define the behavior based on the parameter:</p> <pre><code>def verboseprint (*args, mode): if mode == in_verbose_mode: for arg in args: print arg, print print "Done defining verbose print." # if we're not in verbosemode, do nothing ##else: ## verboseprint = lambda *a: None </code></pre> <p>And then import this function to use in your other files.</p>
3
2016-08-03T17:44:00Z
[ "python", "function", "definition", "function-declaration", "helper-functions" ]
Function that defines a function in python
38,750,177
<p>I have a program that defines the function <code>verboseprint</code> to either print or not print to the screen based on a boolean:</p> <pre><code># define verboseprint based on whether we're running in verbose mode or not if in_verbose_mode: def verboseprint (*args): for arg in args: print arg, print print "Done defining verbose print." else: # if we're not in verbosemode, do nothing verboseprint = lambda *a: None </code></pre> <p>My program uses multiple files, and I'd like to use this definition of verboseprint in all of them. All of the files will be passed the <code>in_verbose_mode</code> boolean. I know that I could just define <code>verboseprint</code> by itself in a file and then import it into all of my other files, but I need the function definition to be able to be declared two different ways based on a boolean. </p> <p>So in summary: I need a function that can declare another function in two different ways, that I can then import into multiple files.</p> <p>Any help would be appreciated. </p>
0
2016-08-03T17:29:50Z
38,750,405
<p>You should look up the factory design pattern. It's basically designed to do exactly what you are talking about, though it would be with classes not functions. That being said, you can get the behavior that you want by having a class that returns one of two possible objects (based on your boolean). They both have the same method but it operates differently (just like your two functions). </p> <pre><code>Class A: def method(): do things one way Class B: def method(): do things another way import A,B Class Factory: def __init__(bool): self.printer = A if bool else B def do_thing(): self.printer.method() import Factory fac = Factory(True) fac.do_thing() # does A thing fac = Factor(False) fac.do_thing() # does B thing </code></pre>
3
2016-08-03T17:44:13Z
[ "python", "function", "definition", "function-declaration", "helper-functions" ]
python logging not displaying %(name)s format property as expected
38,750,178
<p>I have some ideas about what is going on but can't necessarily figure out how to fix it.</p> <p>I have an Abstract Base Class (ABC) that has an attribute of <code>logger = logging.getLogger(__name__)</code>. This happens in the <code>__init__</code></p> <p>I then have a concrete class that overwrites the attribute with the same code. The concrete class also has an import statement of <code>from ABC import *</code>.</p> <p>My question is... Why are all of my logging statements coming out with the name of the ABC despite the fact that half of them occur in my concrete class. I'm using a format string that includes <code>%(name)s</code> which it pulls from the logger instance above that uses the <code>__name__</code> attribute.</p> <p>Unfortunately I'm on a standalone system so I can't necessarily copy all the code over, but I think I've hit the key elements. The only other thing that I would add is that the concrete class does call the <code>super(concreteClass, self).__init__()</code> but it makes this call prior to running the code that should be overwriting the logger attribute. </p> <pre><code>import logging class ABC(object) def __init__(): self.logger = logging.getlogger(__name__) self.logger.info("hey I'm in the ABC") class Concrete(ABC) def __init__(): super(Concrete,self).__init__() self.logger = logging.getlogger(__name__) self.logger.info("hey I'm in the concrete") output conc = Concrete() (DATE) ABC INFO Hey I'm in the ABC (DATE) ABC INFO Hey I'm in the concrete </code></pre>
0
2016-08-03T17:29:55Z
38,750,574
<p>The way you are writing out your example code, it looks like the two classes are defined in the same file. Is that the case? Because <code>__name__</code> will give you the module name, which is essentially the file name. So in that case, the two should be the same</p> <p>Additional answer after it was verified that they were in different files:</p> <p>I can't replicate your results. The code you have posted is not actually runnable so it is very hard to locate your bug. I patched up your code until it was runnable and it works fine. Please take a look at what I ended up writing and see if you see anything you might have done differently.</p> <p>File: my_abc.py</p> <pre><code>import logging class ABC(object): def __init__(self): self.logger = logging.getLogger(__name__) self.logger.setLevel(logging.DEBUG) # create console handler and set level to debug ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) # create formatter formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') # add formatter to ch ch.setFormatter(formatter) # add ch to logger self.logger.addHandler(ch) self.logger.info("hey I'm in the ABC") </code></pre> <p>File: conc.py</p> <pre><code>import logging from my_abc import ABC class Concrete(ABC): def __init__(self): super(Concrete,self).__init__() self.logger = logging.getLogger(__name__) self.logger.setLevel(logging.DEBUG) # create console handler and set level to debug ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) # create formatter formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') # add formatter to ch ch.setFormatter(formatter) # add ch to logger self.logger.addHandler(ch) self.logger.info("hey I'm in the concrete") </code></pre> <p>File: run.py</p> <pre><code>from conc import Concrete conc = Concrete() print __name__ </code></pre> <p>When running the above, this is what I get:</p> <pre><code>$ python run.py 2016-08-03 14:15:56,681 - my_abc - INFO - hey I'm in the ABC 2016-08-03 14:15:56,681 - conc - INFO - hey I'm in the concrete __main__ </code></pre>
1
2016-08-03T17:54:37Z
[ "python", "oop", "inheritance", "logging" ]
how to choose and upload a file in python
38,750,191
<p>I am writing a program where it asks you what text file the user wants to read then it begins to read whatever file name the user inputs. Here is what I have so far:</p> <pre><code>import sys import os import re #CHOOSE FILE print "Welcome to the Parsing Database" raw_input=raw_input("enter file name to parse: ") #ASSIGN HEADERS AND SEQUENCES f=open("raw_input", "r") header=[] sequence=[] string="" for line in f: if "&gt;" in line and string=="": header.append(line[:-2]) elif "&gt;" in line and string!="": sequence.append(string) header.append(line[:-2]) string="" else: string=string+line[:-2] sequence.append(string) </code></pre> <p>The first two lines work but then it says it cannot find the file that I inputted to read. Please help! Thanks.</p>
-1
2016-08-03T17:30:50Z
38,750,259
<p>Off the top of my head, I think that <code>f = open("raw_input", "r")</code> needs to be <code>f=open(raw_input, "r")</code>, because you are trying to reference the string contained in the variable <code>raw_input</code>, as opposed to trying to open a file named raw_input. Also you should probably change the name of the variable to something more readable, because <code>raw_input()</code> is a function used in your code as well as a variable, which makes it hard to read. Are there any other <em>specific</em> problems you are having with your code?</p>
1
2016-08-03T17:34:37Z
[ "python", "python-2.7", "file", "import", "text-files" ]
how to choose and upload a file in python
38,750,191
<p>I am writing a program where it asks you what text file the user wants to read then it begins to read whatever file name the user inputs. Here is what I have so far:</p> <pre><code>import sys import os import re #CHOOSE FILE print "Welcome to the Parsing Database" raw_input=raw_input("enter file name to parse: ") #ASSIGN HEADERS AND SEQUENCES f=open("raw_input", "r") header=[] sequence=[] string="" for line in f: if "&gt;" in line and string=="": header.append(line[:-2]) elif "&gt;" in line and string!="": sequence.append(string) header.append(line[:-2]) string="" else: string=string+line[:-2] sequence.append(string) </code></pre> <p>The first two lines work but then it says it cannot find the file that I inputted to read. Please help! Thanks.</p>
-1
2016-08-03T17:30:50Z
38,750,671
<p><code>f=open("raw_input", "r")</code></p> <p>"raw_input" is a plain string. You have to referente to it as <code>raw_input</code>.</p> <p>Also, there's no lines if you don't use <code>.read()</code> with <code>open()</code> method so you can't parse them. Read lines from a file given from <code>raw_input</code> can be done doing that:</p> <pre><code>import sys import os import re #CHOOSE FILE print "Welcome to the Parsing Database" raw_input_file=raw_input("enter file name to parse: ") #ASSIGN HEADERS AND SEQUENCES testfile = open(raw_input_file, "r") secuence = [] for line in testfile.read().splitlines(): secuence.append(line) for i in secuence: print i testfile.close() </code></pre>
0
2016-08-03T18:00:08Z
[ "python", "python-2.7", "file", "import", "text-files" ]
Counting Inversion for a large text file
38,750,193
<p>The objective of the code is to find out the total no. of inversions for an array. My code works successfully. Tested successfully for 6 elements (all elements in reverse order starting with the highest) with inversion count= 15. Also,tested successfully for 10 elements(all elements in reverse order starting with the highest) with inversion count= 45 However, for a large file containing 100k integers, it is taking almost a 25 seconds. Is this expected ? Kindly suggest or can i further bring down the execution time ? I have just made a minor tweak in the conventional merge sort algorithm (i.e. the line to count the total no. of inversions) How can i further reduce the overall running time?</p> <pre><code>def mergeSort(final_list): global total_count if len(final_list)&gt;1: mid_no=len(final_list)//2 left_half=final_list[:mid_no] right_half=final_list[mid_no:] mergeSort(left_half) mergeSort(right_half) '''Below code is for merging the lists''' i=j=k=0 #i is index for left half, j for the right half and k for the resultant list while i&lt;len(left_half) and j&lt;len(right_half): if left_half[i] &lt; right_half[j]: final_list[k]=left_half[i] i+=1 k+=1 else: final_list[k]=right_half[j] print 'total count is' print total_count #total_count+=len(left_half)-i total_count+=len(left_half[i:]) print 'total_count is ' print total_count print 'pairs are ' print str(left_half[i:])+' with '+str(right_half[j]) j+=1 k+=1 while i&lt;len(left_half): final_list[k]=left_half[i] k+=1 i+=1 while j&lt;len(right_half): final_list[k]=right_half[j] j+=1 k+=1 '''Code for list merge ends''' #temp_list=[45,21,23,4,65] #temp_list=[1,5,2,3,4,6] #temp_list=[6,5,4,3,2,1] #temp_list=[1,2,3,4,5,6] #temp_list=[10,9,8,7,6,5,4,3,2,1] #temp_list=[1,22,3,4,66,7] temp_list=[] f=open('temp_list.txt','r') for line in f: temp_list.append(int(line.strip())) print 'list is ' print temp_list print 'list ends' print temp_list[0] print temp_list[-1] '''import time time.sleep(1000) print 'hhhhhhhhhh' ''' total_count=0 mergeSort(temp_list) print temp_list </code></pre>
0
2016-08-03T17:31:09Z
38,754,583
<p>I found it (and verified with profile)</p> <pre><code> #total_count+=len(left_half[i:]) total_count += len(left_half) - i </code></pre> <p>left_half[i:] creates a new list with a copy of several elements, many times, in the main loop of your recursive function. It was a clever use of splicing, but the side effects are killing your performance.</p> <p>Here's how I broke down the function to profile it:</p> <pre><code>def so_merge (final_list, left_half, right_half): global total_count i=j=k=0 #i is index for left half, j for the right half and k for the resultant list while i&lt;len(left_half) and j&lt;len(right_half): if left_half[i] &lt; right_half[j]: final_list[k]=left_half[i] i+=1 k+=1 else: final_list[k]=right_half[j] count1 = get_incriment_bad(left_half, i) count2 = get_incriment_good(left_half, i) if count1 != count2: raise ValueError total_count += count1 j+=1 k+=1 finish_left(final_list, left_half, i, k) finish_right(final_list, right_half, j, k) </code></pre> <p>and the results show that it spent 19.574 seconds getting len(left_half[i:])</p> <pre><code>ncalls tottime percall cumtime percall filename:lineno(function) 199999/1 0.805 0.000 29.562 29.562 week1.py:124(so_mergesort) 99999 7.496 0.000 28.735 0.000 week1.py:104(so_merge) 776644 19.512 0.000 19.574 0.000 week1.py:101(get_incriment_bad) 776644 0.839 0.000 0.895 0.000 week1.py:98(get_incriment_good) 5403164 0.382 0.000 0.382 0.000 {len} 99999 0.273 0.000 0.286 0.000 week1.py:92(finish_right) 99999 0.255 0.000 0.266 0.000 week1.py:86(finish_left) 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects} </code></pre>
1
2016-08-03T22:19:05Z
[ "python", "mergesort", "inversion" ]
Importing package installed with pip3 causes ImportError
38,750,206
<p>I installed the <strong>pillow 3.3.0</strong> package for Python 3.5.2 Mac by using the <strong>pip3 install statement</strong> in terminal, it successfully downloaded and installed. (I did the same for other pacakges.)</p> <p>When trying to call <em>import pillow</em>, following warning is displayed:</p> <pre><code>&gt;&gt;&gt;import pillow Traceback (most recent call last): File "&lt;pyshell#3&gt;", line 1, in &lt;module&gt; from pillow import * ImportError: No module named 'pillow' </code></pre> <p><em>I took following steps:</em></p> <p>Those are the packages locally installed:</p> <pre><code>import pip installed_packages = pip.get_installed_distributions() installed_packages_list = sorted(["%s==%s" % (i.key, i.version) for i in installed_packages]) print(installed_packages_list) ['numpy==1.11.1', 'pillow==3.3.0', 'pip==8.1.2', 'psycopg2==2.6.2', 'setuptools==20.10.1'] </code></pre> <p>When pip3 installing pillow again, following warning shows up:</p> <pre><code>MyComputer-MBP-2:~ user$ pip3 install Pillow Requirement already satisfied (use --upgrade to upgrade): Pillow in /Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages </code></pre> <p>Other packages work just fine.</p>
0
2016-08-03T17:31:41Z
38,750,312
<p>The importable name of the Pillow library is <code>PIL</code> because it is a fork of the original PIL. Just do</p> <pre><code>from PIL import * </code></pre> <p>Or even better, only import those names you actually need—see this <a href="http://stackoverflow.com/questions/2386714/why-is-import-bad">SO thread</a>.</p>
1
2016-08-03T17:37:57Z
[ "python", "python-3.x", "import", "package", "pillow" ]
Importing package installed with pip3 causes ImportError
38,750,206
<p>I installed the <strong>pillow 3.3.0</strong> package for Python 3.5.2 Mac by using the <strong>pip3 install statement</strong> in terminal, it successfully downloaded and installed. (I did the same for other pacakges.)</p> <p>When trying to call <em>import pillow</em>, following warning is displayed:</p> <pre><code>&gt;&gt;&gt;import pillow Traceback (most recent call last): File "&lt;pyshell#3&gt;", line 1, in &lt;module&gt; from pillow import * ImportError: No module named 'pillow' </code></pre> <p><em>I took following steps:</em></p> <p>Those are the packages locally installed:</p> <pre><code>import pip installed_packages = pip.get_installed_distributions() installed_packages_list = sorted(["%s==%s" % (i.key, i.version) for i in installed_packages]) print(installed_packages_list) ['numpy==1.11.1', 'pillow==3.3.0', 'pip==8.1.2', 'psycopg2==2.6.2', 'setuptools==20.10.1'] </code></pre> <p>When pip3 installing pillow again, following warning shows up:</p> <pre><code>MyComputer-MBP-2:~ user$ pip3 install Pillow Requirement already satisfied (use --upgrade to upgrade): Pillow in /Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages </code></pre> <p>Other packages work just fine.</p>
0
2016-08-03T17:31:41Z
38,750,341
<p>the package name is PIL</p> <p>use </p> <pre><code>from PIL import * </code></pre>
0
2016-08-03T17:40:25Z
[ "python", "python-3.x", "import", "package", "pillow" ]
Cannot get an output Python Classes and Functions code
38,750,364
<p>I recently submitted this homework but couldn't get the code of either problems working. I would love to know what I could have done to make sure I do it right the next time.</p> <p><strong>Question 1</strong> (5 points) Create a base/parent class called 'InterestCalculator'. Create a child class called 'CICalculator'. The 'CICalculator' class will have only one parent, the 'InterestCalculator'. Create a child class called 'SICalculator'. The 'SI' class will have only one parent, the 'InterestCalculator'. The parent class needs to have an <strong>init</strong> method, that will initialize all the values needed for calculating and storing interest.</p> <p>The child class 'CICalculator' and 'SICalculator' must implement 'calcfinalval' method that will calculate the final value for each case.</p> <p>Compound Interest is given by A = p*(1+(r/(n*100)))^(n*t) where p is the principal amount, r is the rate of interest and t is time in years and n is the number of times interest is compounded annually and A is the total amount after t years. Assume n = 2.</p> <p>Simple Interest is given by A = p(1+(r*t/100) where p is the principal, r is the rate of interest and t is time in years and A is the total amount after t years.</p> <p>Once all classes have been defined, the call to calculate and print the final value must follow the code below.</p> <pre><code> c = CICalculator(2,0.1,1000) c.calcfinalval() print c.finalval s = SICalculator(2,0.1,1000) s.calcfinalval() print s.finalval </code></pre> <p><strong># solution 1</strong></p> <pre><code>class InterestCalculator: def __init__(self, A, p, r, y, t): self.A = A self.p = p self.r = r self.y = y self.t = t def calcfinalval(self): return "Interest Rates" class CICalculator(InterestCalculator): def __init__(self, A, p, r, y, t): self.A = self.p*(1+(self.r/(self.t*100)))^(self.t*self.y) class SICalculator(InterestCalculator): def __init__(self, A, p, r, y): self.A = self.p(1+(self.r*self.y/100) c = CICalculator(2,0.1,1000) c.calcfinalval() print c.finalval s = SICalculator(2,0.1,1000) s.calcfinalval() print s.finalval </code></pre> <p><strong>Question 2</strong> (5 points) A queue follows FIFO (first-in, first-out). FIFO is the case where the first element added is the first element that can be retrieved. Consider a list with values [1,2,3]. Create a class called MyQueue that will have two methods: queueadd and queueretrieve to add and retrieve elements from the list in FIFO order respectively. After each function call, print the contents of the list. Add 7 to the queue and then follow the FIFO rules to retrieve an element.</p> <p>Your call to the class will be as follows a = [1,2,3] q = MyQueue(a) q.queueadd(7) q.queueretrieve()</p> <p>The output on the screen should similar to</p> <pre><code> 1 2 3 7 2 3 7 3 7 7 </code></pre> <p><strong># solution 2</strong></p> <pre><code> class MyQueue: def __init__(self): self.in_stack = [] self.out_stack = [] def queueadd(self, obj): self.in_stack.append(obj) def queueretrieve(self): if not self.out_stack: while self.in_stack: self.out_stack.append(self.in_stack.pop()) return self.out_stack.pop() a = [1,2,3] q = MyQueue(a) q.queueadd(7) q.queueretrieve() </code></pre>
-1
2016-08-03T17:41:42Z
38,751,180
<p>There are many errors in your code. Most of them being indent errors. I have only sorted the errors, the core algorithm you wanted to implement is unaltered. </p> <pre><code>class InterestCalculator: def __init__(self, p, r,t,n=1,A=0): self.A = A self.p = p self.r = r self.n = n self.t = t class CICalculator(InterestCalculator): def __init__(self, p, r, t, n=1, A=0): InterestCalculator.__init__(self,p,r,t,n) def calcfinalval(self): self.A = self.p*(1+ self.r/ (self.n*100) )**(self.n*self.t) return self.A class SICalculator(InterestCalculator): def __init__(self, p, r, t): InterestCalculator.__init__(self,p,r,t) def calcfinalval(self): self.A = self.p*(1+(self.r*self.t/100)) return self.A c = CICalculator(2,0.1,1000) c.calcfinalval() print c.A s = SICalculator(2,0.1,1000) s.calcfinalval() print s.A </code></pre> <p>For the 2nd problem</p> <pre><code>class MyQueue: def __init__(self,in_stack): self.in_stack = in_stack self.out_stack = [] def queueadd(self, obj): self.in_stack.append(obj) def queueretrieve(self): if not self.out_stack: while self.in_stack: self.out_stack.append(self.in_stack.pop()) return self.out_stack.pop() a = [1,2,3] q = MyQueue(a) q.queueadd(7) print (q.queueretrieve()) print (q.queueretrieve()) print (q.queueretrieve()) print (q.queueretrieve()) </code></pre>
-2
2016-08-03T18:31:54Z
[ "python", "python-2.7", "function", "class" ]
Cannot get an output Python Classes and Functions code
38,750,364
<p>I recently submitted this homework but couldn't get the code of either problems working. I would love to know what I could have done to make sure I do it right the next time.</p> <p><strong>Question 1</strong> (5 points) Create a base/parent class called 'InterestCalculator'. Create a child class called 'CICalculator'. The 'CICalculator' class will have only one parent, the 'InterestCalculator'. Create a child class called 'SICalculator'. The 'SI' class will have only one parent, the 'InterestCalculator'. The parent class needs to have an <strong>init</strong> method, that will initialize all the values needed for calculating and storing interest.</p> <p>The child class 'CICalculator' and 'SICalculator' must implement 'calcfinalval' method that will calculate the final value for each case.</p> <p>Compound Interest is given by A = p*(1+(r/(n*100)))^(n*t) where p is the principal amount, r is the rate of interest and t is time in years and n is the number of times interest is compounded annually and A is the total amount after t years. Assume n = 2.</p> <p>Simple Interest is given by A = p(1+(r*t/100) where p is the principal, r is the rate of interest and t is time in years and A is the total amount after t years.</p> <p>Once all classes have been defined, the call to calculate and print the final value must follow the code below.</p> <pre><code> c = CICalculator(2,0.1,1000) c.calcfinalval() print c.finalval s = SICalculator(2,0.1,1000) s.calcfinalval() print s.finalval </code></pre> <p><strong># solution 1</strong></p> <pre><code>class InterestCalculator: def __init__(self, A, p, r, y, t): self.A = A self.p = p self.r = r self.y = y self.t = t def calcfinalval(self): return "Interest Rates" class CICalculator(InterestCalculator): def __init__(self, A, p, r, y, t): self.A = self.p*(1+(self.r/(self.t*100)))^(self.t*self.y) class SICalculator(InterestCalculator): def __init__(self, A, p, r, y): self.A = self.p(1+(self.r*self.y/100) c = CICalculator(2,0.1,1000) c.calcfinalval() print c.finalval s = SICalculator(2,0.1,1000) s.calcfinalval() print s.finalval </code></pre> <p><strong>Question 2</strong> (5 points) A queue follows FIFO (first-in, first-out). FIFO is the case where the first element added is the first element that can be retrieved. Consider a list with values [1,2,3]. Create a class called MyQueue that will have two methods: queueadd and queueretrieve to add and retrieve elements from the list in FIFO order respectively. After each function call, print the contents of the list. Add 7 to the queue and then follow the FIFO rules to retrieve an element.</p> <p>Your call to the class will be as follows a = [1,2,3] q = MyQueue(a) q.queueadd(7) q.queueretrieve()</p> <p>The output on the screen should similar to</p> <pre><code> 1 2 3 7 2 3 7 3 7 7 </code></pre> <p><strong># solution 2</strong></p> <pre><code> class MyQueue: def __init__(self): self.in_stack = [] self.out_stack = [] def queueadd(self, obj): self.in_stack.append(obj) def queueretrieve(self): if not self.out_stack: while self.in_stack: self.out_stack.append(self.in_stack.pop()) return self.out_stack.pop() a = [1,2,3] q = MyQueue(a) q.queueadd(7) q.queueretrieve() </code></pre>
-1
2016-08-03T17:41:42Z
38,751,415
<p>A way to implement Q1 in a similar way that you have implemented in Solution 1 is :</p> <pre><code>class InterestCalculator: def __init__(self,p, r, y, t): self.p = p self.r = r self.y = y self.t = t class CICalculator(InterestCalculator): def __init__(self,InterestCalculator): self.p=InterestCalculator.p self.r=InterestCalculator.r self.y=InterestCalculator.y self.t=InterestCalculator.t def calcfinalval(self): val = self.p*(1+(self.r/(self.t*100.0)))**(self.t*self.y) return val class SICalculator(InterestCalculator): def __init__(self,InterestCalculator): self.p=InterestCalculator.p self.r=InterestCalculator.r self.y=InterestCalculator.y def calcfinalval(self): val = self.p*(1+(self.r*self.y/100.0)) return val #Initialize an interestcalculator object IC = InterestCalculator(1000,1,10,4) #Create a CICalculator object CI = CICalculator(IC) print CI.calcfinalval() SI = SICalculator(IC) print SI.calcfinalval() </code></pre> <p>However, there are a lot of intricacies that I have changed in this code and I would suggest sitting down with someone who knows this stuff if you are serious about learning python.</p>
-1
2016-08-03T18:46:06Z
[ "python", "python-2.7", "function", "class" ]
Emulating Behavior of Java String's Split Method in Python
38,750,387
<p>I am parsing sets of csv-type data into Python tuples by splitting the strings across a delimiting character. Very simple stuff.</p> <p>My issue is that any of the fields could potentially contain empty strings as valid data. This is fine, except if the very last field is a empty string, in which case the length of the resulting tuple is one less than it should be.</p> <p>For instance, given the following string, with commas as delimiters : </p> <pre><code>"2016-08-03,jim,,5146,,ok,,2," </code></pre> <p>I desire the following output:</p> <pre><code>["2016-08-03", "jim", "", "5146", "", "ok", "", "2", ""] </code></pre> <p>While trying to find a simple solution to this problem, I found <a href="http://stackoverflow.com/questions/14602062/java-string-split-removed-empty-values">this answer</a>, which details how to retain trailing empty strings in Java's split implementation. However, I have been unable to find anything equivalent in Python. Are there any alternative standard library methods or other simple tricks that would produce this behavior, or will I need add some additional logic into the script to accomplish this?</p> <p>(I realize that it would be very simple to write a new method that produces this output, but in the interest of less code is better from a maintenance standpoint, I thought I would first check to see if I am missing something even easier.)</p>
-1
2016-08-03T17:43:03Z
38,750,494
<p>I think python directly gives the correct output. Do you have any specific example where this is not the case? :</p> <pre><code>x = "5|6|7||8|9||" x.split("|") Out: ['5', '6', '7', '', '8', '9', '', ''] </code></pre>
0
2016-08-03T17:49:44Z
[ "python", "string", "split" ]
Using the hover tool with vbar glyphs
38,750,508
<h2>Question</h2> <p>Is it possible to use the hover tool with bokeh <code>vbar</code> glyphs?</p> <h2>Problem</h2> <p>Using the same basic setup, I can get great tool tips with the hover tool on <code>circle</code> glyphs, but not <code>vbar</code> glyphs</p> <h2>Demonstration</h2> <h3>Setup</h3> <pre><code>import numpy import pandas from bokeh import charts, plotting, models plotting.output_notebook() blue = 'STEELBLUE' green = 'FORESTGREEN' datalist = [ {'month': 'Oct', 'rain': 131., 'snow': 0.0, 'wy_month': 1}, {'month': 'Nov', 'rain': 12.4, 'snow': 0.0, 'wy_month': 2}, {'month': 'Dec', 'rain': 43.0, 'snow': 13.5, 'wy_month': 3}, {'month': 'Jan', 'rain': 63.0, 'snow': 9.2, 'wy_month': 4}, {'month': 'Feb', 'rain': 72.6, 'snow': 35.3, 'wy_month': 5}, {'month': 'Mar', 'rain': 13.5, 'snow': 4.2, 'wy_month': 6}, {'month': 'Apr', 'rain': 107., 'snow': 1.5, 'wy_month': 7}, {'month': 'May', 'rain': 77.0, 'snow': 0.0, 'wy_month': 8}, {'month': 'Jun', 'rain': 107., 'snow': 0.0, 'wy_month': 9}, {'month': 'Jul', 'rain': 216., 'snow': 0.0, 'wy_month': 10}, {'month': 'Aug', 'rain': 76.8, 'snow': 0.0, 'wy_month': 11}, {'month': 'Sep', 'rain': 76.4, 'snow': 0.0, 'wy_month': 12} ] data = pandas.DataFrame(datalist).assign(total=lambda df: df['rain'] + df['snow']) source = plotting.ColumnDataSource(data) tooltips = [ ("month", "@month"), ("rain", "@rain"), ("snow", "@snow"), ] </code></pre> <h3>Successful with <code>circle</code> glyphs</h3> <pre><code>hover_circle = models.HoverTool(tooltips=tooltips) TOOLS_circle = [hover_circle, models.ResizeTool(), models.ResetTool()] fig = plotting.figure(width=600, height=300, y_range=(0, 250), x_range=data['month'].tolist(), tools=TOOLS_circle) fig.circle(x='wy_month', y='rain', color=blue, source=source) fig.circle(x='wy_month', y='snow', color=green, source=source) plotting.show(fig) </code></pre> <p><a href="http://i.stack.imgur.com/m4FlU.png" rel="nofollow"><img src="http://i.stack.imgur.com/m4FlU.png" alt="enter image description here"></a></p> <h3>Unsuccessful with <code>vbar</code> glyphs</h3> <pre><code>hover_bar = models.HoverTool(tooltips=tooltips) TOOLS_bar = [hover_bar, models.ResizeTool(), models.ResetTool()] fig = plotting.figure(width=600, height=300, y_range=(0, 250), x_range=data['month'].tolist(), tools=TOOLS_bar) fig.vbar(x='wy_month', bottom=0, top='rain', width=0.5, color=blue, source=source) fig.vbar(x='wy_month', bottom='rain', top='total', width=0.5, color=green, source=source) plotting.show(fig) </code></pre> <p><a href="http://i.stack.imgur.com/EiUyh.png" rel="nofollow"><img src="http://i.stack.imgur.com/EiUyh.png" alt="enter image description here"></a></p>
1
2016-08-03T17:50:20Z
38,751,463
<p><strong>UPDATE</strong>: This feature has been implemented and will be in <code>0.12.2</code></p> <p>Not yet, as of Bokeh <code>0.12.1</code>. Given the choice to add <code>vbar</code>/<code>hbar</code> without hit-testing support, or not add them at all, it was decided to be useful to the most number of users to make them available sooner rather than later. Adding hit-testing to these glyphs is a short term priority, though the team is stretched very thin at the moment. If you are interested in contributing, please reach out on GitHub. </p>
1
2016-08-03T18:49:26Z
[ "python", "bokeh" ]
pysnmp error on specific query
38,750,540
<p>I have been trying to implement code that loads my device MIBS and walks through all the OIDS. In this one case when I try to load the OID for snmp 1.3.6.1.2.1.11 smi throws an exception when trying to load a specific OID. The previous OID works successfully: '.1.3.6.1.2.1.11.29.0' but this one generates the error message '.1.3.6.1.2.1.11.30.0'</p> <p>The exception is:</p> <blockquote> <p>File "/opt/anaconda/lib/python2.7/site-packages/pysnmp/smi/rfc1902.py", line 859, in resolveWithMib raise SmiError('MIB object %r having type %r failed to cast value %r: %s' % (self.<strong>args[0].prettyPrint(), self.__args[0].getMibNode().getSyntax().__class</strong>.<strong>name</strong>, self.__args[1], sys.exc_info()[1])) ;SmiError: MIB object 'SNMPv2-MIB::snmpEnableAuthenTraps.0' having type 'Integer32' failed to cast value Integer32(808466736): ConstraintsIntersection(ConstraintsIntersection(ConstraintsIntersection(), ValueRangeConstraint(-2147483648, 2147483647)), SingleValueConstraint(1, 2)) failed at: "SingleValueConstraint(1, 2) failed at: "808466736"" at Integer32</p> </blockquote> <p>Here is sample code that demonstrates the error. You will need to modify the DEVICE_IP. It is assuming that you are running SNMP v1 and against community 'public. It is running pysnmp version 4.3.2</p> <pre><code>from pysnmp.entity.rfc3413.oneliner import cmdgen from pysnmp.smi.rfc1902 import ObjectIdentity DEVICE_IP = 'localhost' def get_oid(oid): """ Requires a valid oid as input and retrieves the given OID """ snmp_target = (DEVICE_IP, 161) cmdGen = cmdgen.CommandGenerator() result = None errorIndication, errorStatus, errorIndex, varBindTable = cmdGen.nextCmd( cmdgen.CommunityData('public', mpModel=0), cmdgen.UdpTransportTarget(snmp_target), ObjectIdentity(oid, last=True), lexicographicMode=False ) if errorIndication: print(errorIndication) else: for varBindTableRow in varBindTable: for name, val in varBindTableRow: try: result = str(val) except: raise return result # Does not Throw Error print get_oid('.1.3.6.1.2.1.11.29.0') # Throws Error print get_oid('.1.3.6.1.2.1.11.30.0') </code></pre>
0
2016-08-03T17:52:23Z
38,937,615
<p>Your SNMP agent responded with <em>1.3.6.1.2.1.11.30.0=808466736</em> while OID 1.3.6.1.2.1.11.30.0 identifies MIB object <em>snmpEnableAuthenTraps</em> of type INTEGER with only two values permitted: 1 and 2.</p> <p>Here is formal definition from SNMPv2-MIB:</p> <pre><code>snmpEnableAuthenTraps OBJECT-TYPE SYNTAX INTEGER { enabled(1), disabled(2) } ... </code></pre> <p>So this time pysnmp seems to do the right thing - it shields you from the value that makes no sense. Root cause of this problem is the SNMP agent that sends malformed values for MIB objects.</p>
0
2016-08-13T22:45:23Z
[ "python", "snmp", "pysnmp" ]
PySerial: TypeError: 'float' object is not iterable
38,750,542
<p>So I'm writing a program to adjust the speed of a rotating magnetic field. Basically, I'm just trying to send a float through the serial port to represent the user's intended speed. But I'm getting an error that doesn't really make sense. I've isolated the error in a much smaller portion of code.</p> <p>Code:</p> <pre><code>import serial #imports PySerial Library #Function allows for user input and conversion to float. #If not float, "Invalid" is printed to the console, and input is requested again def get_float(prompt): while True: #Main Loop try: response = raw_input(prompt) #User inputs return float(response) #Conversion is attempted except: print("Invalid") #If conversion fails def magnet_speed(): input = get_float('Enter a speed in rpm to immediately change rotation speed\n&gt;&gt; ') print input arduino.write(input) #send to arduino arduino = serial.Serial('/dev/ttyACM0', 9600) #declares which serial port the arduino is con$ magnet_speed() exit() </code></pre> <p>This is the error if I run the script: </p> <pre><code>Enter a speed in rpm to immediately change rotation speed &gt;&gt; a Invalid Enter a speed in rpm to immediately change rotation speed &gt;&gt; 4 4.0 Traceback (most recent call last): File "magnet_speed.py", line 22, in &lt;module&gt; magnet_speed() File "magnet_speed.py", line 16, in magnet_speed arduino.write(input) #send to arduino File "/usr/local/lib/python2.7/dist-packages/serial/serialposix.py", line 498, in write d = to_bytes(data) File "/usr/local/lib/python2.7/dist-packages/serial/serialutil.py", line 66, in to_bytes for item in seq: TypeError: 'float' object is not iterable </code></pre> <p>My only thought is I'm not returning the float from <code>get_float()</code> right, or I'm not defining the variable <code>input</code> right. The <code>get_float()</code> function definitely works alone to print the inputted number if I run it in the python shell.</p>
0
2016-08-03T17:52:24Z
38,750,630
<p><code>serial.Serial.write()</code> expects to be passed in a <code>str</code> object, not a floating point value. A <code>str</code> object is iterable.</p> <p>From the <a href="http://pyserial.readthedocs.io/en/latest/pyserial_api.html#serial.Serial.write" rel="nofollow"><code>pyserial</code> documenation</a>:</p> <blockquote> <p>Write the bytes <em>data</em> to the port. This should be of type <code>bytes</code> (or compatible such as <code>bytearray</code> or <code>memoryview</code>). Unicode strings must be encoded (e.g. <code>'hello'.encode('utf-8'</code>).</p> <p>Changed in version 2.5: Accepts instances of <code>bytes</code> and <code>bytearray</code> when available (Python 2.6 and newer) and <code>str</code> otherwise.</p> </blockquote> <p>In Python 2, <code>bytes</code> is an alias for <code>str</code> (to make it easier to write code that is forward compatible with Python 3).</p> <p>Convert your float to a string <em>first</em>:</p> <pre><code>arduino.write(str(output)) </code></pre> <p>or use a different method to more precisely control how the float is converted to bytes. You could use the <a href="https://docs.python.org/2/library/functions.html#format" rel="nofollow"><code>format()</code> function</a> to control how many digits are put after the decimal point and / or if scientific notation is ever to be used, or you could use the <a href="https://docs.python.org/2/library/struct.html#struct.pack" rel="nofollow"><code>struct.pack()</code> function</a> to produce a C-compatible binary representation for the value:</p> <pre><code>arduino.write(format(output, '.4f')) # fixed point with 4 decimals arduino.write(pack('&gt;d', output)) # big-endian C double </code></pre> <p>what you pick depends on what the Arduino is expecting to read.</p>
1
2016-08-03T17:58:01Z
[ "python", "arduino", "iteration", "typeerror", "pyserial" ]
Killing a process on an open socket from another class
38,750,567
<p>Alright I have a program that opens a socket to a local port and starts processes, the code goes as follows:</p> <blockquote> <p>socket_opener.py</p> </blockquote> <pre><code>processes=[] Handler = CGIHTTPServer.CGIHTTPRequestHandler Handler.cgi_directories = ["/maps"] httpd = SocketServer.TCPServer(("", PORT), Handler) httpd.server_name = "localhost" httpd.server_port = 8008 processes.append(subprocess.Popen("ls")) processes.append(subprocess.Popen("ls")) httpd.serve_forever() </code></pre> <p>Now I want to kill a process from the pool of processes in the list <code>processes</code> declared above so I tried the following:</p> <blockquote> <p>process_killer.py</p> </blockquote> <pre><code>from socket_opener import processes </code></pre> <p>Sadly that's as far as I could go because it throws this error</p> <pre><code>socket.error: [Errno 98] Address already in use </code></pre> <p>What other way can I do this?</p>
0
2016-08-03T17:53:45Z
38,752,445
<p>The proximate cause here is that you're running all the code in <code>socket_opener</code> again by importing the module. That fails because there's already a socket bound to the port numbered <code>PORT</code> and you're attempting to bind another one. </p> <p>(As far as I can tell, you're adding <code>server_name</code> and <code>server_port</code> attributes to the object after you've created it that will have no effect on its operation. You really should provide a complete verifiable example (<a href="http://stackoverflow.com/help/mcve" title="mcve">mcve</a>).)</p> <p>But the bigger problem is that you appear to be operating under the assumption that you can define a list in one program (<code>socket_opener</code>) and then access that list from another program (<code>process_killer</code>). It doesn't work that way: the first program will be operating in its own process address space separate from that of the second program. The second program won't be able to access variables in the first.</p> <p>You would need to place the process list in some external object that is accessible from a different program (a file, shared memory segment, or some other IPC [interprocess communication] mechanism). And the form of the list would have to be one that a different program could consume: a textual list of process IDs, say, instead of a python <code>list</code> object containing python <code>Popen</code> objects, none of which would make sense outside of the originating program's address space.</p>
1
2016-08-03T19:50:24Z
[ "python", "python-2.7", "sockets", "process" ]
django orm join three tables
38,750,667
<p>I have three models (A, B, C) and I need to join them like so:</p> <p>Model A fk1 to Model B pk1 and then Model B fk1 to Model C.</p> <p>It is joining tables but not joining them correctly. I can join model a to b but it won't let me pull fields from the last table (c) after the first join.</p> <p>Sample SQL that works:</p> <pre><code>select a.field1, a.field2, b.char1, b.char2, c.var1, c.var2 from TableA a inner join TableB b on a.field1 = b.char1 left join TableC c on b.char2 = c.var1 where a.field2 = 'number' </code></pre> <p>Django code:</p> <pre><code>TableA.objects.select_related('field1').filter(field2=var).prefetch_related('char1').values('field1', 'field2', 'char1', 'char1__var1', 'char1__var2') </code></pre> <p>Django models.py:</p> <pre><code>class TableA(models.Model): field2 = models.CharField(db_column='FIELD2', max_length=8, primary_key=True) # Field name made lowercase. field1 = models.ForeignKey('TableB', db_column='FIELD1', max_length=6) # Field name made lowercase. class Meta: managed = False db_table = 'TableA' class TableB(models.Model): char1 = models.CharField(db_column='CHAR1', max_length=6) # Field name made lowercase. char2 = models.ForeignKey('TableC', db_column='CHAR2', max_length=6, primary_key=True) # Field name made lowercase. class Meta: managed = False db_table = 'TableB' class TableC(models.Model): var1 = models.CharField(db_column='VAR1', max_length=6, primary_key=True) # Field name made lowercase. var2 = models.CharField(db_column='VAR2', max_length=50) # Field name made lowercase. class Meta: managed = False db_table = 'TableC' </code></pre>
0
2016-08-03T17:59:55Z
38,751,018
<p><strong>Update</strong>: Question was edited, so this answer is not relevant anymore.</p> <pre><code>TableA.objects.filter(field2=var, b__isnull=False, b__c__isnull=True).values( 'field1', 'field2', 'b__char1', 'b__c__var1', 'b__c__var2', ) </code></pre> <ol> <li><code>b__isnull=False</code> is for <code>INNER JOIN tableb</code> and <code>b__c__isnull=True</code> is for <code>LEFT JOIN tablec</code>. </li> <li>You can refer to fields on related models in <code>values()</code>.</li> </ol>
0
2016-08-03T18:22:29Z
[ "python", "sql", "django", "join" ]
OpenCV Python copying certain portion of image to another
38,750,688
<p>I want to calculate the difference betwwn two images. I'm only interested in the difference value for a certain portion of image. For that i am copying the required portion of image to a temp images, and operating on those images. However using the pixel allocation using as specified on <a href="http://docs.opencv.org/3.0-beta/doc/py_tutorials/py_core/py_basic_ops/py_basic_ops.html" rel="nofollow">http://docs.opencv.org/3.0-beta/doc/py_tutorials/py_core/py_basic_ops/py_basic_ops.html</a>. Here it is given, </p> <p><code>ball = img[280:340, 330:390] img[273:333, 100:160] = ball</code></p> <p>Using the similar logic, i have written a python program,</p> <pre><code>import cv2 import numpy as np img_file = 'carparking2_1.jpg' img = cv2.imread(img_file, cv2.IMREAD_COLOR) img_withoutcar = 'carparking2_1.jpg' img_withcar = 'carparking2.jpg' img1 = img_withoutcar[47:151, 106:157] img2 = img_withcar[47:151, 106:157] diff1 = cv2.absdiff(img1, img2) diff2 = cv2.absdiff(img1, img1) print 'RGB shape: ', img.shape # Rows, cols, channels print 'Difference with car and without: ', diff1 print 'Difference with car and with car: ', diff2 </code></pre> <p>However, im getting the output message: </p> <pre><code>File "D:/Projects/IoT Smart Parking/differenceinframes.py", line 8, in &lt;module&gt; img1 = img_withoutcar[47:151, 106:157] TypeError: string indices must be integers, not tuple </code></pre> <p>I am running Python 2.7 with OpenCV 3.1.0 on Windows 10.</p>
0
2016-08-03T18:01:10Z
38,753,881
<p>You are getting the error because your command is trying to slice the string 'carparking2_1.jpg' as if it were the image data.</p> <pre><code>#First assign the file names: file_name_without_car='carparking2_1.jpg' file_name_with_car='carparking2.jpg' #load the images img_withoutcar= cv2.imread(file_name_without_car, cv2.IMREAD_COLOR) img_withcar= cv2.imread(file_name_with_car, cv2.IMREAD_COLOR) #now you can slice regions of the images #note that color images have a third dimension for color channel. img1 = img_withoutcar[47:151, 106:157,:] img2 = img_withcar[47:151, 106:157,:] </code></pre>
0
2016-08-03T21:23:18Z
[ "python", "image", "opencv" ]
How can I print multiple lines, having subsequent lines replacing each of them independently (Python)
38,750,727
<p>I am running a program that works in parallel, utilizing the <code>Pool</code> object from the multiprocessing module.</p> <p>What I am trying to do is run a function n number of times in parallel, each having a separate loading %, and I would like it to be updating the percentage for each function without replacing other percentages... example:</p> <pre><code>f(x): while x &lt; 0: print 'For x = {0}, {1}% completed...\r'.format(x, percentage), </code></pre> <p>And I would run the function multiple times in parallel.</p> <p>The effect I am trying to achieve is the following, for f(10000000), f(15000000), f(7000000):</p> <pre><code>For x = 10000000, 43% completed For x = 15000000, 31% completed For x = 7000000, 77% completed </code></pre> <p>And the percentages will be updating in their individual lines without replacing for other values of x, in this function <code>f</code> which will be running three times at the same time.</p> <p>I tried using the carriage return '\r' but that replaces every line and just creates a mess.</p> <p>Thanks for taking the time to read this post! I hope you can tell me.</p> <p>I am using Python 2.7 but if it can only be achieved with Python 3 I am open to suggestions.</p>
0
2016-08-03T18:03:47Z
38,751,532
<h1>Curses</h1> <p>As @Keozon mentioned in the comments, one way to achieve this would be to use the <a href="https://docs.python.org/3/library/curses.html" rel="nofollow">curses</a> library.</p> <p>There is a <a href="https://docs.python.org/3/howto/curses.html" rel="nofollow">good guide for curses</a> on the python website. </p> <h1>ANSI Escape Codes</h1> <p>Alternatively, you might try using <a href="https://en.wikipedia.org/wiki/ANSI_escape_code" rel="nofollow">ANSI escape codes</a> to move the cursor around.</p> <p>This is in Python3, but it'll work just fine in any version, you'll just need to change the print statements around (or <code>from __future__ import print_function</code>).</p> <pre><code>print('Hello') print('World') print('\033[F\033[F\033[K', end='') # Up, Up, Clear line # Cursor is at the 'H' of 'Hello' print('Hi') # Overwriting 'Hello' # Cursor is at the 'W' of 'World' print('\033[E', end='') # Down # Cursor is on the blank line after 'World' print('Back to the end') </code></pre> <h2>Output:</h2> <pre><code>Hi World Back to the end </code></pre> <hr> <h1>Edit:</h1> <p>I've done way too much work for you here, but hey, here's basically a full solution using the ANSI method I mentioned above:</p> <pre><code>import time import random class ProgressBar: def __init__(self, name): self._name = name self._progress = 0 @property def name(self): return self._name def get_progress(self): """ Randomly increment the progress bar and ensure it doesn't go over 100 """ self._progress += int(random.random()*5) if self._progress &gt; 100: self._progress = 100 return self._progress class MultipleProgressBars: def __init__(self, progress_bars): self._progress_bars = progress_bars self._first_update = True self._all_finished = False @property def all_finished(self): """ A boolean indicating if all progress bars are at 100 """ return self._all_finished def update(self): """ Update each progress bar """ # We don't want to move up and clear a line on the first run # so we have a flag to make sure this only happens on later # calls if not self._first_update: # Move up and clear the line the correct number of times print('\033[F\033[K'*len(self._progress_bars),end='', sep='') num_complete = 0 # Number of progress bars complete for progress_bar in self._progress_bars: name = progress_bar.name progress = progress_bar.get_progress() if progress == 100: num_complete += 1 # Print out a progress bar (scaled to 40 chars wide) print( name.ljust(10), '[' + ('='*int(progress*0.4)).ljust(40) + ']', str(progress)+'%') if num_complete == len(self._progress_bars): self._all_finished = True self._first_update = False # Mark the first update done # Create a list of ProgressBars and give them relevant names progress_bars = [ ProgressBar('James'), ProgressBar('Bert'), ProgressBar('Alfred'), ProgressBar('Frank') ] # Create a new instance of our MultipleProgressBars class mpb = MultipleProgressBars(progress_bars) # Keep updating them while at least one of them is still active while not mpb.all_finished: mpb.update() time.sleep(0.2) </code></pre>
0
2016-08-03T18:52:53Z
[ "python", "printing", "parallel-processing", "percentage", "lines" ]
Trying to transfer 5009 rows from csv file to xlsx
38,750,729
<pre><code>import pandas as pd df1=pd.read_csv('out.csv') df2=pd.read_excel('file.xls') df2['Location']=df1['Location'] df2['Sublocation']=df1['Sublocation'] df2['Zone']=df1['Zone'] df2['Subnet Type']=df1['Subnet Type'] df2['Description']=df1['Description'] newfile = input("Enter a name for the combined xlsx file: ") print('Saving to new xlsx file...') writer = pd.ExcelWriter(newfile) df2.to_excel(writer, index=False) writer.save() </code></pre> <p>Basically, it reads a csv file with 5 columns and it reads a xls file with existing columns, then makes a xlsx file where the two files are combined with the 5 new columns.</p> <p>So it works, but only for 4999 rows, the last 10 dont have the 5 new columns in the new xlsx file.</p>
0
2016-08-03T18:04:05Z
38,750,991
<p>I think you should append data</p> <pre><code>import pandas as pd df1=pd.read_csv('out.csv') df2=pd.read_excel('file.xls') df2.append(df1) newfile = input("Enter a name for the combined xlsx file: ") print('Saving to new xlsx file...') writer = pd.ExcelWriter(newfile) df2.to_excel(writer, index=False) writer.save() </code></pre>
0
2016-08-03T18:21:02Z
[ "python", "python-3.x", "csv", "pandas", "xls" ]
Trying to transfer 5009 rows from csv file to xlsx
38,750,729
<pre><code>import pandas as pd df1=pd.read_csv('out.csv') df2=pd.read_excel('file.xls') df2['Location']=df1['Location'] df2['Sublocation']=df1['Sublocation'] df2['Zone']=df1['Zone'] df2['Subnet Type']=df1['Subnet Type'] df2['Description']=df1['Description'] newfile = input("Enter a name for the combined xlsx file: ") print('Saving to new xlsx file...') writer = pd.ExcelWriter(newfile) df2.to_excel(writer, index=False) writer.save() </code></pre> <p>Basically, it reads a csv file with 5 columns and it reads a xls file with existing columns, then makes a xlsx file where the two files are combined with the 5 new columns.</p> <p>So it works, but only for 4999 rows, the last 10 dont have the 5 new columns in the new xlsx file.</p>
0
2016-08-03T18:04:05Z
38,752,996
<p>I am little confused about the problem, so i came up with 2 options 1. append df1 to df2 2. Merge df1 to df2 (adds new columns to existing df) . I think in your case you dont have same number of rows in csv and excel and for that reason last 10 rows dont have value in the output</p> <pre><code>import numpy as np import pandas as pd df1 = pd.DataFrame(np.array([ ['a', 51, 61], ['b', 52, 62], ['c', 53, 63]]), columns=['name', 'attr11', 'attr12']) df2 = pd.DataFrame(np.array([ ['a', 31, 41], ['b', 32, 42], ['c', 33, 43], ['d',34,44]]), columns=['name', 'attr21', 'attr22']) df3= df1.append(df2) print df3 print pd.merge(df1,df2,on='name',how='right') </code></pre>
1
2016-08-03T20:25:17Z
[ "python", "python-3.x", "csv", "pandas", "xls" ]
Trying to transfer 5009 rows from csv file to xlsx
38,750,729
<pre><code>import pandas as pd df1=pd.read_csv('out.csv') df2=pd.read_excel('file.xls') df2['Location']=df1['Location'] df2['Sublocation']=df1['Sublocation'] df2['Zone']=df1['Zone'] df2['Subnet Type']=df1['Subnet Type'] df2['Description']=df1['Description'] newfile = input("Enter a name for the combined xlsx file: ") print('Saving to new xlsx file...') writer = pd.ExcelWriter(newfile) df2.to_excel(writer, index=False) writer.save() </code></pre> <p>Basically, it reads a csv file with 5 columns and it reads a xls file with existing columns, then makes a xlsx file where the two files are combined with the 5 new columns.</p> <p>So it works, but only for 4999 rows, the last 10 dont have the 5 new columns in the new xlsx file.</p>
0
2016-08-03T18:04:05Z
38,773,531
<p>Most likely there is a way to do what you want within <code>pandas</code>, but in case there isn't, you can use lower-level packages to accomplish your task.</p> <p>To read the CSV file, use the <code>csv</code> module that comes with Python. The following code loads all the data into a Python list, where each element of the list is a row in the CSV. Note that this code is not as compact as an experienced Python programmer would write. I've tried to strike a balance between being readable for Python beginners and being "idiomatic":</p> <pre><code>import csv with open('input1.csv', 'rb') as f: reader = csv.reader(f) csvdata = [] for row in reader: csvdata.append(row) </code></pre> <p>To read the .xls file, use <a href="https://pypi.python.org/pypi/xlrd" rel="nofollow"><code>xlrd</code></a>, which should already be installed since <code>pandas</code> uses it, but you can install it separately if needed. Again, the following code is not the shortest possible, but is hopefully easy to understand:</p> <pre><code>import xlrd wb = xlrd.open_workbook('input2.xls') ws = wb.sheet_by_index(0) # use the first sheet xlsdata = [] for rx in range(ws.nrows): xlsdata.append(ws.row_values(rx)) </code></pre> <p>Finally, write out the combined data to a .xlsx file using <a href="https://pypi.python.org/pypi/XlsxWriter" rel="nofollow">XlsxWriter</a>. This is another package that may already be installed if you've used <code>pandas</code> to write Excel files, but can be installed separately if needed. Once again, I've tried to stick to relatively simple language features. For example, I've avoided <code>zip()</code>, whose workings might not be obvious to Python beginners:</p> <pre><code>import xlsxwriter wb = xlsxwriter.Workbook('output.xlsx') ws = wb.add_worksheet() assert len(csvdata) == len(xlsdata) # we expect the same number of rows for rx in range(len(csvdata)): ws.write_row(rx, 0, xlsdata[rx]) ws.write_row(rx, len(xlsdata[rx]), csvdata[rx]) wb.close() </code></pre> <p>Note that <code>write_row()</code> lets you choose the destination cell of the leftmost data element. So I've used it twice for each row: once to write the .xls data at the far left, and once more to write the CSV data with a suitable offset.</p>
1
2016-08-04T17:09:41Z
[ "python", "python-3.x", "csv", "pandas", "xls" ]
Filtering itertools combinations for dynamic number of constraints
38,750,858
<p>I have python program and function that returns a series of rows from my MySQL database. These returned rows are filtered by a set of IDs contained in a tuple, I then use itertools and list comprehension to form 'combinations' that conform to a fixed set of constraints (the attributes of each combination must be either "all equal" or "all unique" within that combination). </p> <p>I'd like to make the function dynamic for different number of IDs but I'm not sure how to filter the returned rows dynamically (without a mess of nested IF statements). Is there a way I can re-write the if/and conditions in the function below to make them dynamic for len(tuple_of_ids)?</p> <p>I'm very much still a learner when it comes to python/code development so any assistance would be appreciated!</p> <p>My current (psuedo-) code:</p> <pre><code>import itertools def get_valid_combinations(tuple_of_ids): data = get_filtered_data_from_database(valid_ids=tuple_of_ids) # (row1, row2, row3) assumes that the tuple_of_ids has len=3. If tuple_of_ids had 4 members I'd need (row1, row2, row3, row4) etc valid_combinations = [(row1, row2, row3) for row1, row2, row3 in list(itertools.combinations(data, 3)) if ((row1.Age == row2.Age) # All items in combination have same Age and (row2.Age == row3.Age)) and ((row1.School != row2.School) and (row2.School != row3.School) and (row1.School != row3.School)) # All items in combination have different School ] # ...etc (i.e. there may be multiple filtering criteria, but always either ("all equal" or "all different") return valid_combinations ids_to_search_for = ('C00001', 'C00002', 'C00003') get_valid_combinations(tuple_of_ids = ids_to_search_for) &gt;&gt;&gt; [(&lt;database_row_object_1&gt;, &lt;database_row_object_2&gt;, &lt;database_row_object_3&gt;), (&lt;database_row_object_x&gt;, &lt;database_row_object_y&gt;, &lt;database_row_object_z&gt;),...] </code></pre>
0
2016-08-03T18:12:12Z
38,751,054
<p>As Martijn stated in the comment, you may look at doing the filtering in SQL, which is bound to be probably more efficient. If the filtering must be done in Python, the <em>"all equal" or "all different"</em> check could easily be done with a set comprehension:</p> <pre><code>length = len(tuple_of_ids) valid_combinations = [tup for tup in itertools.combinations(data, length) if len({r.Age for r in tup}) == 1 and len({r.School for r in tup}) == length] </code></pre> <p>The only overhead with doing this is that the sets are destroyed as soon as they are created, as only their lengths are needed. </p> <p>On a side note, you can drop the <em>cast</em> to <code>list</code> for <code>itertools.combinations</code> since you don't actually need the list.</p>
1
2016-08-03T18:23:59Z
[ "python", "python-2.7" ]
Filtering itertools combinations for dynamic number of constraints
38,750,858
<p>I have python program and function that returns a series of rows from my MySQL database. These returned rows are filtered by a set of IDs contained in a tuple, I then use itertools and list comprehension to form 'combinations' that conform to a fixed set of constraints (the attributes of each combination must be either "all equal" or "all unique" within that combination). </p> <p>I'd like to make the function dynamic for different number of IDs but I'm not sure how to filter the returned rows dynamically (without a mess of nested IF statements). Is there a way I can re-write the if/and conditions in the function below to make them dynamic for len(tuple_of_ids)?</p> <p>I'm very much still a learner when it comes to python/code development so any assistance would be appreciated!</p> <p>My current (psuedo-) code:</p> <pre><code>import itertools def get_valid_combinations(tuple_of_ids): data = get_filtered_data_from_database(valid_ids=tuple_of_ids) # (row1, row2, row3) assumes that the tuple_of_ids has len=3. If tuple_of_ids had 4 members I'd need (row1, row2, row3, row4) etc valid_combinations = [(row1, row2, row3) for row1, row2, row3 in list(itertools.combinations(data, 3)) if ((row1.Age == row2.Age) # All items in combination have same Age and (row2.Age == row3.Age)) and ((row1.School != row2.School) and (row2.School != row3.School) and (row1.School != row3.School)) # All items in combination have different School ] # ...etc (i.e. there may be multiple filtering criteria, but always either ("all equal" or "all different") return valid_combinations ids_to_search_for = ('C00001', 'C00002', 'C00003') get_valid_combinations(tuple_of_ids = ids_to_search_for) &gt;&gt;&gt; [(&lt;database_row_object_1&gt;, &lt;database_row_object_2&gt;, &lt;database_row_object_3&gt;), (&lt;database_row_object_x&gt;, &lt;database_row_object_y&gt;, &lt;database_row_object_z&gt;),...] </code></pre>
0
2016-08-03T18:12:12Z
38,751,363
<p>I think that passing functions by reference is a pretty pythonic way of easily adding or removing constraints from your code. This is a contrived example:</p> <pre><code>#Just an example class class Person(object): __slots__ = ["age","height","weight"] def __init__(self,age,height,weight): self.age = age self.height = height self.weight = weight ​ #Function to try all tests def test_people(people,tests): test_results = [test(people) for test in tests] print "Passed all tests:",all(test_results) print "Passed at least one:",any(test_results) #Testing functions to be passed into the test_people def first_lighter_than_second(people): p1 = people[0] p2 = people[1] return True if p1.weight &lt; p2.weight else False def third_older_than_first(people): p1 = people[0] p3 = people[2] return True if p3.age &gt; p1.age else False ​ #Building people list p1 = Person(24,182.1,90.5) p2 = Person(50,170.4,83) p3 = Person(62,150.3,67) people = [p1,p2,p3] ​ #Building list of test functions tests = [] tests.append(first_lighter_than_second) tests.append(third_older_than_first) ​ #Try all tests test_people(people,tests) #Output Passed all tests: False Passed at least one: True </code></pre> <p>A downside is that you need to create lots of small functions and remember to add them to a list</p>
0
2016-08-03T18:42:42Z
[ "python", "python-2.7" ]
Python : While threading why does the conditional statement work differently?
38,750,970
<p>I was trying to write a simple function and call it from a thread for different values. The function worked perfectly when called normally. But as soon as we call it from a thread the conditional statements inside the function do not work.</p> <pre><code>def func(count): print "In func count = {0}".format(count) if count == 3: print "If count = {0}".format(count) print "Sleeping as count = {0}".format(count) else: print "Else count = {0}".format(count) print "{0} so No sleep".format(count) -------------------------------------------------- </code></pre> <p>While calling the above function works perfectly.</p> <pre><code>print func(2) print func(3) print func(4) </code></pre> <p>Output is :</p> <pre><code>In func: count = 2 Printing Else Count = 2 In func: count = 3 Printing If Count = 3 In func: count = 4 Printing Else Count = 4 ------------------------------ </code></pre> <p>But while using the same function in a thread the behavior is different.</p> <pre><code>thread_arr = [] for index in range(2,5,1): thread_arr.append(threading.Thread(target=func, args=("{0}".format(int(index))))) thread_arr[-1].start() for thread in thread_arr: thread.join() </code></pre> <p>Output is :</p> <pre><code>In func: count = 2 Printing Else Count = 2 In func: count = 3 Printing Else Count = 3 In func: count = 4 Printing Else Count = 4 </code></pre> <p>Can anyone help why is the behavior different?</p>
0
2016-08-03T18:19:42Z
38,751,042
<p>You passed the index as a string to the function, but you are checking for equality with an integer.</p> <p>Also, doing <code>int(index)</code> is redundant. It's already an int.</p> <p>You can check this by doing <code>print type(count)</code></p> <p>Edit: Here's an example of what you're doing.</p> <pre><code> &gt;&gt;&gt; x = "{0}".format(1) &gt;&gt;&gt; x '1' &gt;&gt;&gt; type(x) &lt;class 'str'&gt; &gt;&gt;&gt; 1 == x False </code></pre>
2
2016-08-03T18:23:21Z
[ "python", "multithreading", "conditional" ]
No module named 'django.core.context_processors', in views.py
38,751,005
<p>In my django app, When I run server I am getting the error.</p> <p>from . import views from django.core.context_processors import csrf ImportError: No module named 'django.core.context_processors'</p> <p>My views.py file is </p> <pre><code> from django.views.generic import View from django.utils import timezone from django.shortcuts import render, get_object_or_404,render_to_response,redirect from django.http import HttpResponseRedirect from django.contrib import auth from django.contrib.auth import authenticate,login from django.core.context_processors import csrf from .forms import UserForm # Create your views here. def home(request): return render(request, 'fosssite/home.html') def login(request): c={} c.update(csrf(request)) return render_to_response('fosssite/login.html',c) def UserFormView(request): form_class=UserForm template_name='fosssite/signup.html' if request.method=='GET': form=form_class(None) return render(request,template_name,{'form':form}) #validate by forms of django if request.method=='POST': form=form_class(request.POST) if form.is_valid(): # not saving to database only creating object user=form.save(commit=False) #normalized data username=form.cleaned_data['username'] password=form.cleaned_data['password'] #not as plain data user.set_password(password) user.save() #saved to database user=auth.authenticate(username=username,password=password) if user is not None: auth.login(request,user) return HttpResponseRedirect('/')#url in brackets return render(request,template_name,{'form':form}) def auth_view(request): username=request.POST.get('username', '') password=request.POST.get('password', '') user=auth.authenticate(username=username,password=password) if user is not None: auth.login(request,user) return HttpResponseRedirect('/profileuser')#url in brackets else: return HttpResponseRedirect('/invalid') def profileuser(request): return render_to_response('fosssite/profileuser.html',{'fullname':request.user.username}) def logout(request): auth.logout(request) pass def edit_user_profile(request): pass def invalid_login(request): return render_to_response('fosssite/invalid_login.html') </code></pre> <p>and settings.py file is </p> <pre><code>""" Django settings for foss project. Generated by 'django-admin startproject' using Django 1.9.7. For more information on this file, see https://docs.djangoproject.com/en/1.9/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.9/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'fosssite', ] MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'foss.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'foss.wsgi.application' # Database # https://docs.djangoproject.com/en/1.9/ref/settings/#databases # read database.md file for configuring DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': '', 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '', } } # Password validation # https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.9/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.9/howto/static-files/ STATIC_URL = '/static/' </code></pre>
1
2016-08-03T18:21:56Z
38,751,259
<p>Try to change this import to <code>from django.template.context_processors import csrf</code>. Your current import seems to be depreciated (via <a href="https://docs.djangoproject.com/en/1.9/releases/1.8/#django-core-context-processors" rel="nofollow">https://docs.djangoproject.com/en/1.9/releases/1.8/#django-core-context-processors</a>)</p>
0
2016-08-03T18:36:20Z
[ "python", "django" ]
No module named 'django.core.context_processors', in views.py
38,751,005
<p>In my django app, When I run server I am getting the error.</p> <p>from . import views from django.core.context_processors import csrf ImportError: No module named 'django.core.context_processors'</p> <p>My views.py file is </p> <pre><code> from django.views.generic import View from django.utils import timezone from django.shortcuts import render, get_object_or_404,render_to_response,redirect from django.http import HttpResponseRedirect from django.contrib import auth from django.contrib.auth import authenticate,login from django.core.context_processors import csrf from .forms import UserForm # Create your views here. def home(request): return render(request, 'fosssite/home.html') def login(request): c={} c.update(csrf(request)) return render_to_response('fosssite/login.html',c) def UserFormView(request): form_class=UserForm template_name='fosssite/signup.html' if request.method=='GET': form=form_class(None) return render(request,template_name,{'form':form}) #validate by forms of django if request.method=='POST': form=form_class(request.POST) if form.is_valid(): # not saving to database only creating object user=form.save(commit=False) #normalized data username=form.cleaned_data['username'] password=form.cleaned_data['password'] #not as plain data user.set_password(password) user.save() #saved to database user=auth.authenticate(username=username,password=password) if user is not None: auth.login(request,user) return HttpResponseRedirect('/')#url in brackets return render(request,template_name,{'form':form}) def auth_view(request): username=request.POST.get('username', '') password=request.POST.get('password', '') user=auth.authenticate(username=username,password=password) if user is not None: auth.login(request,user) return HttpResponseRedirect('/profileuser')#url in brackets else: return HttpResponseRedirect('/invalid') def profileuser(request): return render_to_response('fosssite/profileuser.html',{'fullname':request.user.username}) def logout(request): auth.logout(request) pass def edit_user_profile(request): pass def invalid_login(request): return render_to_response('fosssite/invalid_login.html') </code></pre> <p>and settings.py file is </p> <pre><code>""" Django settings for foss project. Generated by 'django-admin startproject' using Django 1.9.7. For more information on this file, see https://docs.djangoproject.com/en/1.9/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.9/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'fosssite', ] MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'foss.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'foss.wsgi.application' # Database # https://docs.djangoproject.com/en/1.9/ref/settings/#databases # read database.md file for configuring DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': '', 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '', } } # Password validation # https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.9/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.9/howto/static-files/ STATIC_URL = '/static/' </code></pre>
1
2016-08-03T18:21:56Z
38,752,901
<p>First, remove the invalid import that is causing the error</p> <pre><code>from django.core.context_processors import csrf </code></pre> <p>Next, the <code>render_to_response</code> shortcut is obsolete, you should use <code>render</code> instead. For example:</p> <pre><code>from django.shortcuts import render def login(request): c={} return render(request, 'fosssite/login.html', c) </code></pre> <p>The <code>render</code> shortcut uses a <code>RequestContext</code> automatic, so you don't have to manage the csrf token in the view manually. </p>
0
2016-08-03T20:19:24Z
[ "python", "django" ]
Sharing data with multiple python programms
38,751,024
<p>i am scraping data through multiple websites. To do that i have written multiple web scrapers with using selenium and PhantomJs.</p> <p>Those scrapers return values.</p> <p>My question is: is there a way i can feed those values to a single python program that will sort through that data in real time.</p> <p>What i want to do is not save that data to analyze it later i want to send it to a program that will analyze it in real time.</p> <p><strong>what i have tried</strong>: i have no idea where to even start</p>
0
2016-08-03T18:22:51Z
38,751,112
<p>You can try writing the data you want to share to a file and have the other script read and interpret it. Have the other script run in a loop to check if there is a new file or the file has been changed.</p>
-1
2016-08-03T18:27:27Z
[ "python", "osx", "os.system" ]
Sharing data with multiple python programms
38,751,024
<p>i am scraping data through multiple websites. To do that i have written multiple web scrapers with using selenium and PhantomJs.</p> <p>Those scrapers return values.</p> <p>My question is: is there a way i can feed those values to a single python program that will sort through that data in real time.</p> <p>What i want to do is not save that data to analyze it later i want to send it to a program that will analyze it in real time.</p> <p><strong>what i have tried</strong>: i have no idea where to even start</p>
0
2016-08-03T18:22:51Z
38,751,162
<p>Simply use files for data exchange and a trivial locking mechanism. Each writer or reader (only one reader, it seems) gets a unique number. If a writer or reader wants to write to the file, it renames it to its original name + the number and then writes or reads, renaming it back after that. The others wait until the file is available again under its own name and then access it by locking it in a similar way.</p> <p>Of course you have shared memory and such, or memmapped files and semaphores. But this mechanism has worked flawlessly for me for over 30 years, on any OS, over any network. Since it's trivially simple.</p> <p>It is in fact a poor man's mutex semaphore. To find out if a file has changed, look to its writing timestamp. But the locking is necessary too, otherwise you'll land into a mess.</p>
-1
2016-08-03T18:31:00Z
[ "python", "osx", "os.system" ]
Sharing data with multiple python programms
38,751,024
<p>i am scraping data through multiple websites. To do that i have written multiple web scrapers with using selenium and PhantomJs.</p> <p>Those scrapers return values.</p> <p>My question is: is there a way i can feed those values to a single python program that will sort through that data in real time.</p> <p>What i want to do is not save that data to analyze it later i want to send it to a program that will analyze it in real time.</p> <p><strong>what i have tried</strong>: i have no idea where to even start</p>
0
2016-08-03T18:22:51Z
38,751,225
<p>Perhaps a <a href="http://linux.die.net/man/3/mkfifo" rel="nofollow">named pipe</a> would be suitable:</p> <p><code>mkfifo whatever</code> (you can also do this from within your python script; <a href="https://docs.python.org/2/library/os.html#os.mkfifo" rel="nofollow">os.mkfifo</a>)</p> <p>You can write to <code>whatever</code> like a normal file (it will block until something reads it) and read from <code>whatever</code> with a different process (it will block if there is no data available)</p> <h1>Example:</h1> <pre><code># writer.py with open('whatever', 'w') as h: h.write('some data') # Blocks until reader.py reads the data # reader.py with open('whatever', 'r') as h: print(h.read()) # Blocks until writer.py writes to the named pipe </code></pre>
0
2016-08-03T18:34:39Z
[ "python", "osx", "os.system" ]
lxml HtmlElement xpath parses more than it should be able to
38,751,203
<p>Trying to parse HTML, I fail to loop through all <code>li</code> elements:</p> <pre><code>from lxml import html page="&lt;ul&gt;&lt;li&gt;one&lt;/li&gt;&lt;li&gt;two&lt;/li&gt;&lt;/ul&gt;" tree = html.fromstring(page) for item in tree.xpath("//li"): print(html.tostring(item)) print(item.xpath("//li/text()")) </code></pre> <p>I expect this output:</p> <pre><code>b'&lt;li&gt;one&lt;/li&gt;' ['one'] b'&lt;li&gt;two&lt;/li&gt;' ['two'] </code></pre> <p>but I get this:</p> <pre><code>b'&lt;li&gt;one&lt;/li&gt;' ['one', 'two'] b'&lt;li&gt;two&lt;/li&gt;' ['one', 'two'] </code></pre> <p>How is it possible that <code>xpath</code> can get both <code>li</code> elements' text from <code>item</code> in both iteration steps?</p> <p>I can solve this using an counter as an index of course but I would like to understand what's going on.</p>
0
2016-08-03T18:33:05Z
38,751,250
<p><code>item.xpath("//li/text()")</code> would search for all <code>li</code> elements in the entire tree. Since you want the text of the current node, you can just get the <code>text()</code>: <code>item.xpath("text()")</code>.</p> <p>Or, even better, just get the <a href="http://lxml.de/lxmlhtml.html#html-element-methods" rel="nofollow"><em>text content</em></a>:</p> <pre><code>for item in tree.xpath("//li"): print(html.tostring(item)) print(item.text_content()) </code></pre>
1
2016-08-03T18:35:44Z
[ "python", "xpath", "lxml" ]
lxml HtmlElement xpath parses more than it should be able to
38,751,203
<p>Trying to parse HTML, I fail to loop through all <code>li</code> elements:</p> <pre><code>from lxml import html page="&lt;ul&gt;&lt;li&gt;one&lt;/li&gt;&lt;li&gt;two&lt;/li&gt;&lt;/ul&gt;" tree = html.fromstring(page) for item in tree.xpath("//li"): print(html.tostring(item)) print(item.xpath("//li/text()")) </code></pre> <p>I expect this output:</p> <pre><code>b'&lt;li&gt;one&lt;/li&gt;' ['one'] b'&lt;li&gt;two&lt;/li&gt;' ['two'] </code></pre> <p>but I get this:</p> <pre><code>b'&lt;li&gt;one&lt;/li&gt;' ['one', 'two'] b'&lt;li&gt;two&lt;/li&gt;' ['one', 'two'] </code></pre> <p>How is it possible that <code>xpath</code> can get both <code>li</code> elements' text from <code>item</code> in both iteration steps?</p> <p>I can solve this using an counter as an index of course but I would like to understand what's going on.</p>
0
2016-08-03T18:33:05Z
38,751,517
<p>From <a href="http://stackoverflow.com/questions/1725268/lxml-html-xpath-context">Lxml html xpath context</a>:</p> <blockquote> <p>XPath expression <code>//input</code> will match all input elements, anywhere in your document, while <code>.//input</code> will match all inside current context.</p> </blockquote> <p>The solution is to use:</p> <pre><code>from lxml import html page="&lt;ul&gt;&lt;li&gt;one&lt;/li&gt;&lt;li&gt;two&lt;/li&gt;&lt;/ul&gt;" tree = html.fromstring(page) for item in tree.xpath("//li"): print(html.tostring(item)) print(item.xpath(".//text()")) #only changed line </code></pre> <p>Adding <code>.</code> before <code>//</code> prevents matching entire document and <code>li/</code> needs to be removed since you are "inside" the <code>li</code> tags already.</p> <p>The output is:</p> <pre><code>b'&lt;li&gt;one&lt;/li&gt;' ['one'] b'&lt;li&gt;two&lt;/li&gt;' ['two'] </code></pre>
1
2016-08-03T18:52:05Z
[ "python", "xpath", "lxml" ]
Slicing a date range that includes time
38,751,223
<p>I have a dataframe which contains a column <code>Date</code> &amp; <code>Time</code>, with each row containing an entry in the format: <code>MM/DD/YYYY HH:MM:SS</code></p> <p>I would like to be able to slice the dataframe based on only a date range, say for instance: <code>5/01/2016 to 5/30/2016</code>.</p> <p>Any suggestions would be greatly appreciated!</p>
0
2016-08-03T18:34:38Z
38,751,400
<p>for variables sdate and edate </p> <pre><code>frame = [] record = 0 for date,time in my_list: if date == sdate or record == 1: frame.append([date,time]) record = 1 if date == edate: break; print (frame) </code></pre>
0
2016-08-03T18:45:25Z
[ "python", "pandas" ]
Slicing a date range that includes time
38,751,223
<p>I have a dataframe which contains a column <code>Date</code> &amp; <code>Time</code>, with each row containing an entry in the format: <code>MM/DD/YYYY HH:MM:SS</code></p> <p>I would like to be able to slice the dataframe based on only a date range, say for instance: <code>5/01/2016 to 5/30/2016</code>.</p> <p>Any suggestions would be greatly appreciated!</p>
0
2016-08-03T18:34:38Z
38,752,563
<p>You could use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.loc.html" rel="nofollow"><code>loc</code></a> to select the subset of the dataframe for which the condition (<em>interval between dates</em>) is satisfied:</p> <p><strong>Data Preparation</strong></p> <pre><code>In [13]: from io import StringIO ...: import pandas as pd ...: In [14]: df = pd.read_csv(StringIO(''' ...: Date ...: 5/01/2016 00:00:00 ...: 5/02/2016 00:00:00 ...: 5/03/2016 00:00:00 ...: 5/04/2016 00:00:00 ...: 5/05/2016 00:00:00 ...: 5/06/2016 00:00:00 ...: 5/07/2016 00:00:00 ...: 5/08/2016 00:00:00 ...: 5/09/2016 00:00:00 ...: 5/010/2016 00:00:00 ...: ''')) </code></pre> <p><strong>Operations</strong></p> <pre><code>In [15]: df['Date'] = pd.to_datetime(df['Date']) In [16]: start = "5/02/2016" ...: end = "5/05/2016" In [17]: mask = (df['Date'] &gt;= pd.to_datetime(start)) &amp; (df['Date'] &lt;= pd.to_datetime(end)) In [18]: df.loc[mask] Out[18]: Date 1 2016-05-02 2 2016-05-03 3 2016-05-04 4 2016-05-05 </code></pre>
0
2016-08-03T19:58:44Z
[ "python", "pandas" ]
Can py2exe keep a py file as configure script?
38,751,240
<p>I want to distribute a python program as an executable file. I use py2exe with <code>options = {"py2exe":{"bundle_files": 1}}</code>. But I want to keep a py file as configure script ( including not just variables but also functions and classes ).</p> <p>Can py2exe do this? Or any other way to do it?</p>
0
2016-08-03T18:35:13Z
38,751,432
<p>It can if you exec () the contents of the .py file.</p>
0
2016-08-03T18:47:28Z
[ "python", "py2exe" ]
group and output on partial column value pandas python
38,751,299
<p>I have a sample data set:</p> <pre><code>import pandas as pd import re df = {'READID': [1,2,3 ,4,5 ,6,7 ,8,9], 'VG': ['LV5-F*01','LV5-F*01' ,'LV5-A*02','LV5-D*01','LV5-E*01','LV5-C*01','LV5-D*01','LV5-E*01','LV5-F*01'], 'Pro': [1,1,1,0.33,0.59,1,0.96,1,1]} df = pd.DataFrame(df) </code></pre> <p>it looks like this:</p> <pre><code>df Out[12]: Pro READID VG 0 1.00 1 LV5-F*01 1 1.00 2 LV5-F*01 2 1.00 3 LV5-A*02 3 0.33 4 LV5-D*01 4 0.59 5 LV5-E*01 5 1.00 6 LV5-C*01 6 0.96 7 LV5-D*01 7 1.00 8 LV5-E*01 8 1.00 9 LV5-F*01 </code></pre> <p>i want to groupby column 'VG' but only the part before '*' for each row, and then group by the same values and output them into separate files.</p> <p>my concept is:</p> <ol> <li>group the dataset 'df' by column 'VG'</li> <li>for each row of column 'VG' look at only the part before the '*', e.g. 'LV5-F', 'LV5-A', 'LV5-D', etc. </li> <li>group the dataset once again but this time for the same values from step 2</li> <li>output each different grouped set to a separate file.</li> </ol> <p>desire output, individual separate files:</p> <pre><code>'LV5-F.txt': Pro READID VG 0 1.00 1 LV5-F*01 1 1.00 2 LV5-F*01 8 1.00 9 LV5-F*01 'LV5-A.txt': Pro READID VG 2 1.00 3 LV5-A*02 'LV5-D.txt': Pro READID VG 3 0.33 4 LV5-D*01 6 0.96 7 LV5-D*01 'LV5-E.txt': Pro READID VG 4 0.59 5 LV5-E*01 7 1.00 8 LV5-E*01 'LV5-C.txt': Pro READID VG 5 1.00 6 LV5-C*01 </code></pre> <p>my attempt:</p> <pre><code>(df.groupby('VG') .apply(lambda x: re.findall('([0-9A-Z-]+)\*',x) ) .groupby('VG') .apply(lambda gp: gp.to_csv('{}.txt'.format(gp.name), sep='\t', index=False)) ) </code></pre> <p>but it failed at the '.apply(lambda x: re.findall('([0-9A-Z-]+)*',x)' step and i'm not sure why it doesn't work because when i ran that code by itself without in the context of being a lambda function, it worked fine. </p>
0
2016-08-03T18:38:48Z
38,751,428
<p>You'll have to adjust the function below <code>to_csv</code> to suit your needs. In particular, instead of printing, just provide a file name somehow.</p> <p>But I'd structure it this way:</p> <pre><code>def to_csv(df): print df.to_csv() # extract # within # parens # /------\ # r'^([^\*]+)' # ^ \----/ # | \__________________________ # match | | | # beginning [^this] \* '+' # of string matches have to match # not this escape * one or more # df.groupby(df.VG.str.extract(r'^([^\*]+)', expand=False)).apply(to_csv) ,Pro,READID,VG 2,1.0,3,LV5-A*02 ,Pro,READID,VG 2,1.0,3,LV5-A*02 ,Pro,READID,VG 5,1.0,6,LV5-C*01 ,Pro,READID,VG 3,0.33,4,LV5-D*01 6,0.96,7,LV5-D*01 ,Pro,READID,VG 4,0.59,5,LV5-E*01 7,1.0,8,LV5-E*01 ,Pro,READID,VG 0,1.0,1,LV5-F*01 1,1.0,2,LV5-F*01 8,1.0,9,LV5-F*01 </code></pre>
1
2016-08-03T18:47:21Z
[ "python", "pandas" ]
group and output on partial column value pandas python
38,751,299
<p>I have a sample data set:</p> <pre><code>import pandas as pd import re df = {'READID': [1,2,3 ,4,5 ,6,7 ,8,9], 'VG': ['LV5-F*01','LV5-F*01' ,'LV5-A*02','LV5-D*01','LV5-E*01','LV5-C*01','LV5-D*01','LV5-E*01','LV5-F*01'], 'Pro': [1,1,1,0.33,0.59,1,0.96,1,1]} df = pd.DataFrame(df) </code></pre> <p>it looks like this:</p> <pre><code>df Out[12]: Pro READID VG 0 1.00 1 LV5-F*01 1 1.00 2 LV5-F*01 2 1.00 3 LV5-A*02 3 0.33 4 LV5-D*01 4 0.59 5 LV5-E*01 5 1.00 6 LV5-C*01 6 0.96 7 LV5-D*01 7 1.00 8 LV5-E*01 8 1.00 9 LV5-F*01 </code></pre> <p>i want to groupby column 'VG' but only the part before '*' for each row, and then group by the same values and output them into separate files.</p> <p>my concept is:</p> <ol> <li>group the dataset 'df' by column 'VG'</li> <li>for each row of column 'VG' look at only the part before the '*', e.g. 'LV5-F', 'LV5-A', 'LV5-D', etc. </li> <li>group the dataset once again but this time for the same values from step 2</li> <li>output each different grouped set to a separate file.</li> </ol> <p>desire output, individual separate files:</p> <pre><code>'LV5-F.txt': Pro READID VG 0 1.00 1 LV5-F*01 1 1.00 2 LV5-F*01 8 1.00 9 LV5-F*01 'LV5-A.txt': Pro READID VG 2 1.00 3 LV5-A*02 'LV5-D.txt': Pro READID VG 3 0.33 4 LV5-D*01 6 0.96 7 LV5-D*01 'LV5-E.txt': Pro READID VG 4 0.59 5 LV5-E*01 7 1.00 8 LV5-E*01 'LV5-C.txt': Pro READID VG 5 1.00 6 LV5-C*01 </code></pre> <p>my attempt:</p> <pre><code>(df.groupby('VG') .apply(lambda x: re.findall('([0-9A-Z-]+)\*',x) ) .groupby('VG') .apply(lambda gp: gp.to_csv('{}.txt'.format(gp.name), sep='\t', index=False)) ) </code></pre> <p>but it failed at the '.apply(lambda x: re.findall('([0-9A-Z-]+)*',x)' step and i'm not sure why it doesn't work because when i ran that code by itself without in the context of being a lambda function, it worked fine. </p>
0
2016-08-03T18:38:48Z
38,751,759
<p>I modified my code with help from @piRSquared and it worked :</p> <pre><code>df.groupby(df.VG.str.extract(r'^([^\*]+)')).apply(lambda gp: gp.to_csv('{}.txt'.format(gp.name), sep='\t', index=False)) </code></pre>
0
2016-08-03T19:05:43Z
[ "python", "pandas" ]
Django rendering display name of choice field in form
38,751,300
<p>tl;dr: How do I make a form output the ‘nice’ name of the choices in a model?</p> <p>I have a Django model with choices, defined like this:</p> <pre><code>class City(models.Model): AMSTERDAM = 'AMS' ROTTERDAM = 'ROT' THE_HAGUE = 'THE' UTRECHT = 'UTR' CITY_CHOICES = ( (AMSTERDAM, 'Amsterdam'), (ROTTERDAM, 'Rotterdam'), (THE_HAGUE, 'The Hague'), (UTRECHT, 'Utrecht'), ) name = models.CharField( max_length=3, choices=CITY_CHOICES, default=AMSTERDAM, blank=False, ) </code></pre> <p>In forms.py, the widgets are defined like this:</p> <pre><code>class ArticleForm(ModelForm): class Meta: model = Article fields = ['title', 'text', 'categories', 'city'] widgets = {'title': forms.TextInput(attrs={ 'placeholder': 'Enter a descriptive title'}), 'text': forms.Textarea(attrs={'placeholder': 'The article'}), 'categories': forms.CheckboxSelectMultiple(), 'city': forms.RadioSelect(), } </code></pre> <p>The form itself is rendered manually (although the same effect happens with just <code>{{form}}</code>:</p> <pre><code>&lt;form action="{% url 'article-submit' %}" method="POST"&gt; {% csrf_token %} {{% for field in form %} &lt;fieldset class="article-form__field"&gt; {% if field.name = "categories"%} {{ field.label_tag }} &lt;ul id={{ field.auto_id }}&gt; {% for checkbox in field %} &lt;li&gt; &lt;label for="{{ checkbox.id_for_label }}"&gt; {{ checkbox.choice_label }} &lt;/label&gt; {{ checkbox.tag }} &lt;/li&gt; {% endfor %} &lt;/ul&gt; {% elif field.name = "city" %} {{ field.label_tag }} &lt;ul id={{ field.auto_id }}&gt; {% for radio in field %} &lt;li&gt; &lt;label for="{{ radio.id_for_label }}"&gt; {{ radio.choice_label }} &lt;/label&gt; {{ radio.tag }} &lt;/li&gt; {% endfor %} &lt;/ul&gt; {% else %} {{ field.label_tag }} {{ field }} {% endif %} &lt;/fieldset&gt; {% endfor %}} &lt;fieldset class="article-form__field"&gt; &lt;input class="button" type="submit" value="submit"&gt; &lt;/fieldset&gt; &lt;/form&gt; </code></pre> <p>However the output is not Amsterdam, but AMS:</p> <pre><code> &lt;fieldset class="article-form__field"&gt; &lt;label for="city_0"&gt;City:&lt;/label&gt; &lt;ul id=city&gt; &lt;li&gt; &lt;label for="city_0"&gt; --------- &lt;/label&gt; &lt;input checked="checked" id="city_0" name="city" type="radio" value="" /&gt; &lt;/li&gt; &lt;li&gt; &lt;label for="city_1"&gt; AMS &lt;/label&gt; &lt;input id="city_1" name="city" type="radio" value="1" /&gt; &lt;/li&gt; etc. </code></pre> <p>In other templates, I could do this: <code>{{city.get_name_display}}</code>, to get the full name. How do I do this in the form?</p> <p><a href="https://gist.github.com/Flobin/56bdaf52094dd7b99b255a3cae458227" rel="nofollow">full code is here</a></p>
1
2016-08-03T18:38:53Z
38,751,737
<p>In your line <code>'city': forms.RadioSelect(),</code>, you need to define the choices for it. It should look like:</p> <pre><code>from blah.models import City class ArticleForm(ModelForm): class Meta: model = Article fields = ['title', 'text', 'categories', 'city'] widgets = {'title': forms.TextInput(attrs={ 'placeholder': 'Enter a descriptive title'}), 'text': forms.Textarea(attrs={'placeholder': 'The article'}), 'categories': forms.CheckboxSelectMultiple(), 'city': forms.RadioSelect(choices=City.CITY_CHOICES), } </code></pre> <p>The radio select widget inherits from the select widget, which has a brief mention of the choices argument in the docs here: <a href="https://docs.djangoproject.com/en/1.10/ref/forms/widgets/#django.forms.Select" rel="nofollow">https://docs.djangoproject.com/en/1.10/ref/forms/widgets/#django.forms.Select</a></p>
1
2016-08-03T19:04:47Z
[ "python", "django", "django-forms", "jinja2" ]
Django rendering display name of choice field in form
38,751,300
<p>tl;dr: How do I make a form output the ‘nice’ name of the choices in a model?</p> <p>I have a Django model with choices, defined like this:</p> <pre><code>class City(models.Model): AMSTERDAM = 'AMS' ROTTERDAM = 'ROT' THE_HAGUE = 'THE' UTRECHT = 'UTR' CITY_CHOICES = ( (AMSTERDAM, 'Amsterdam'), (ROTTERDAM, 'Rotterdam'), (THE_HAGUE, 'The Hague'), (UTRECHT, 'Utrecht'), ) name = models.CharField( max_length=3, choices=CITY_CHOICES, default=AMSTERDAM, blank=False, ) </code></pre> <p>In forms.py, the widgets are defined like this:</p> <pre><code>class ArticleForm(ModelForm): class Meta: model = Article fields = ['title', 'text', 'categories', 'city'] widgets = {'title': forms.TextInput(attrs={ 'placeholder': 'Enter a descriptive title'}), 'text': forms.Textarea(attrs={'placeholder': 'The article'}), 'categories': forms.CheckboxSelectMultiple(), 'city': forms.RadioSelect(), } </code></pre> <p>The form itself is rendered manually (although the same effect happens with just <code>{{form}}</code>:</p> <pre><code>&lt;form action="{% url 'article-submit' %}" method="POST"&gt; {% csrf_token %} {{% for field in form %} &lt;fieldset class="article-form__field"&gt; {% if field.name = "categories"%} {{ field.label_tag }} &lt;ul id={{ field.auto_id }}&gt; {% for checkbox in field %} &lt;li&gt; &lt;label for="{{ checkbox.id_for_label }}"&gt; {{ checkbox.choice_label }} &lt;/label&gt; {{ checkbox.tag }} &lt;/li&gt; {% endfor %} &lt;/ul&gt; {% elif field.name = "city" %} {{ field.label_tag }} &lt;ul id={{ field.auto_id }}&gt; {% for radio in field %} &lt;li&gt; &lt;label for="{{ radio.id_for_label }}"&gt; {{ radio.choice_label }} &lt;/label&gt; {{ radio.tag }} &lt;/li&gt; {% endfor %} &lt;/ul&gt; {% else %} {{ field.label_tag }} {{ field }} {% endif %} &lt;/fieldset&gt; {% endfor %}} &lt;fieldset class="article-form__field"&gt; &lt;input class="button" type="submit" value="submit"&gt; &lt;/fieldset&gt; &lt;/form&gt; </code></pre> <p>However the output is not Amsterdam, but AMS:</p> <pre><code> &lt;fieldset class="article-form__field"&gt; &lt;label for="city_0"&gt;City:&lt;/label&gt; &lt;ul id=city&gt; &lt;li&gt; &lt;label for="city_0"&gt; --------- &lt;/label&gt; &lt;input checked="checked" id="city_0" name="city" type="radio" value="" /&gt; &lt;/li&gt; &lt;li&gt; &lt;label for="city_1"&gt; AMS &lt;/label&gt; &lt;input id="city_1" name="city" type="radio" value="1" /&gt; &lt;/li&gt; etc. </code></pre> <p>In other templates, I could do this: <code>{{city.get_name_display}}</code>, to get the full name. How do I do this in the form?</p> <p><a href="https://gist.github.com/Flobin/56bdaf52094dd7b99b255a3cae458227" rel="nofollow">full code is here</a></p>
1
2016-08-03T18:38:53Z
38,805,327
<p>I got the <a href="https://www.reddit.com/r/django/comments/4w051c/how_to_render_display_name_for_choice_field_in/d641ose" rel="nofollow">following answer</a> from reddit user roambe:</p> <p>Since city is a foreign key, Django will use the __str__ (or __unicode__) method of the City model for the choice label. This should make it start behaving like you want to (substitute for unicode if needed):</p> <pre><code>def __str__(self): return self.get_name_display() </code></pre>
0
2016-08-06T14:27:15Z
[ "python", "django", "django-forms", "jinja2" ]
Microsoft Emotion API for video with Python
38,751,315
<p>I'm using the following code to send my video and apparently I got no error. But the response is coming blank. How can I read the response?</p> <pre><code>########### Python 2.7 ############# import httplib, urllib, base64, json headers = { # Request headers 'Ocp-Apim-Subscription-Key': 'xxxxxxxxxxxxxxxxxxxx', 'Content-Type': 'application/json' } video_filename = {"url":"https://fsarquivoeastus.blob.core.windows.net/public0/WhatsApp-Video-20160727.mp4"} params = urllib.urlencode({}) try: conn = httplib.HTTPSConnection('api.projectoxford.ai') conn.request("POST", "/emotion/v1.0/recognizeinvideo?%s" % params, json.dumps(video_filename), headers) response = conn.getresponse() data = response.read() print(data) conn.close() except Exception as e: print("[Errno {0}] {1}".format(e.errno, e.strerror)) </code></pre>
0
2016-08-03T18:39:46Z
38,753,882
<p>The Cognitive Service Video APIs, including Emotion, operate asynchronously, and by design return an empty response body when the POST succeeds. What you must do instead is retrieve the operation URL from the headers, as shown here:</p> <pre><code>response = conn.getresponse() location = response.getheader('operation-location'); print(location); </code></pre> <p>You call GET on that <code>location</code> URL to check on the status of the operation. More on that <a href="https://dev.projectoxford.ai/docs/services/5639d931ca73072154c1ce89/operations/56f8d4471984551ec0a0984f" rel="nofollow">here</a>.</p>
1
2016-08-03T21:23:31Z
[ "python", "azure", "microsoft-cognitive" ]
Microsoft Emotion API for video with Python
38,751,315
<p>I'm using the following code to send my video and apparently I got no error. But the response is coming blank. How can I read the response?</p> <pre><code>########### Python 2.7 ############# import httplib, urllib, base64, json headers = { # Request headers 'Ocp-Apim-Subscription-Key': 'xxxxxxxxxxxxxxxxxxxx', 'Content-Type': 'application/json' } video_filename = {"url":"https://fsarquivoeastus.blob.core.windows.net/public0/WhatsApp-Video-20160727.mp4"} params = urllib.urlencode({}) try: conn = httplib.HTTPSConnection('api.projectoxford.ai') conn.request("POST", "/emotion/v1.0/recognizeinvideo?%s" % params, json.dumps(video_filename), headers) response = conn.getresponse() data = response.read() print(data) conn.close() except Exception as e: print("[Errno {0}] {1}".format(e.errno, e.strerror)) </code></pre>
0
2016-08-03T18:39:46Z
38,790,995
<p>@FelipeSouzaLima, To getting the operation result from Emotion Recognition in Video, you need to do two steps as below.</p> <ol> <li><p>Call the REST API for <a href="https://dev.projectoxford.ai/docs/services/5639d931ca73072154c1ce89/operations/56f8d40e1984551ec0a0984e" rel="nofollow">Emotion Recognition in Video</a>, then you will get the blank response body and the <code>operation-location</code> header which will be called at the next step as @cthrash said.</p></li> <li><p>Call the url of the value of <code>operation-location</code> header above with the same <code>Ocp-Apim-Subscription-Key</code> as request header, then you can get the json response body which includes the recognition job status. If the value of <code>status</code> field in the json response is <code>Succeeded</code>, you will get the operation result as <code>processingResult</code> field in the json result, please refer to the REST API of <a href="https://dev.projectoxford.ai/docs/services/5639d931ca73072154c1ce89/operations/56f8d4471984551ec0a0984f" rel="nofollow">Get Recognition in Video Operation Result</a>.</p></li> </ol>
0
2016-08-05T13:53:30Z
[ "python", "azure", "microsoft-cognitive" ]
MiniBatchKMeans gives different centroids after subsequent iterations
38,751,364
<p>I am using the <code>MiniBatchKMeans</code> model from the <code>sklearn.cluster</code> module in anaconda. I am clustering a data-set that contains approximately 75,000 points. It looks something like this:</p> <p><code>data = np.array([8,3,1,17,5,21,1,7,1,26,323,16,2334,4,2,67,30,2936,2,16,12,28,1,4,190...])</code></p> <p>I fit the data using the process below.</p> <p><code>from sklearn.cluster import MiniBatchKMeans kmeans = MiniBatchKMeans(batch_size=100) kmeans.fit(data.reshape(-1,1) </code></p> <p>This is all well and okay, and I proceed to find the centroids of the data:</p> <p><code>centroids = kmeans.cluster_centers_ print centroids</code></p> <p>Which gives me the following output:</p> <p><code>array([[ 13.09716569], [ 2908.30379747], [ 46.05089228], [ 725.83453237], [ 95.39868475], [ 1508.38356164], [ 175.48099948], [ 350.76287263]])</code></p> <p>But, when I run the process again, using the same data, I get different values for the centroids, such as this:</p> <p><code>array([[ 29.63143489], [ 1766.7244898 ], [ 171.04417206], [ 2873.70454545], [ 70.05295277], [ 1074.50387597], [ 501.36134454], [ 8.30600975]])</code></p> <p>Can anyone explain why this is?</p>
0
2016-08-03T18:42:47Z
38,751,473
<p>The behavior you are experiencing probably has to do with the under the hood implementation of k-means clustering that you are using. k-means clustering is an NP-hard problem, so all the implementations out there are heuristic methods. What this means practically is that for a given seed, it will converge toward a local optima that isn't necessarily consistent across multiple seeds.</p>
0
2016-08-03T18:49:52Z
[ "python", "statistics", "scikit-learn", "cluster-analysis", "k-means" ]
MiniBatchKMeans gives different centroids after subsequent iterations
38,751,364
<p>I am using the <code>MiniBatchKMeans</code> model from the <code>sklearn.cluster</code> module in anaconda. I am clustering a data-set that contains approximately 75,000 points. It looks something like this:</p> <p><code>data = np.array([8,3,1,17,5,21,1,7,1,26,323,16,2334,4,2,67,30,2936,2,16,12,28,1,4,190...])</code></p> <p>I fit the data using the process below.</p> <p><code>from sklearn.cluster import MiniBatchKMeans kmeans = MiniBatchKMeans(batch_size=100) kmeans.fit(data.reshape(-1,1) </code></p> <p>This is all well and okay, and I proceed to find the centroids of the data:</p> <p><code>centroids = kmeans.cluster_centers_ print centroids</code></p> <p>Which gives me the following output:</p> <p><code>array([[ 13.09716569], [ 2908.30379747], [ 46.05089228], [ 725.83453237], [ 95.39868475], [ 1508.38356164], [ 175.48099948], [ 350.76287263]])</code></p> <p>But, when I run the process again, using the same data, I get different values for the centroids, such as this:</p> <p><code>array([[ 29.63143489], [ 1766.7244898 ], [ 171.04417206], [ 2873.70454545], [ 70.05295277], [ 1074.50387597], [ 501.36134454], [ 8.30600975]])</code></p> <p>Can anyone explain why this is?</p>
0
2016-08-03T18:42:47Z
38,754,035
<p>Read up on what mini-batch k-means is.</p> <p>It will never even <em>converge</em>. Do one more iteration, the result will change <em>again</em>.</p> <p>It is design for data sets so huge you cannot load them into memory at once. So you load a batch, pretend this were the full data set, do one iterarion. Repeat woth the next batch. If your batches are large enough and random, then the result will be "close enough" to be usable. While itjs never optimal.</p> <p>Thus:</p> <ol> <li>the minibatch results are even more random than regular k-means results. They change every iteration.</li> <li>if you can load your data into memory, don't use minibatch. Instead use a fast k-means implementation. (most are surprisingly slow).</li> </ol> <p>P.S. on one-dimensional data, <em>sort</em> your data set and then use an algorithm that benefits from the sorting instead of k-means.</p>
0
2016-08-03T21:36:12Z
[ "python", "statistics", "scikit-learn", "cluster-analysis", "k-means" ]
Retrive a column in pandas
38,751,369
<pre><code>print(pd.read_excel(File,Sheet_Name,0,None,0,None,["Column_Name"],1)) </code></pre> <p>Since i am a noob to pandas i want to retrive a column of ExcelSheet using pandas in the form of array. I tried the code above but it didn't really work. </p>
0
2016-08-03T18:42:58Z
38,751,524
<p>The way to do it is:</p> <pre><code>import pandas as pd df = pd.read_excel(File,sheetname=Sheet_Name) print(df['column_name']) </code></pre>
2
2016-08-03T18:52:24Z
[ "python", "pandas", "machine-learning", "analytics" ]
Iotivity scons build error
38,751,482
<p>This is my build environment</p> <ul> <li>OS:OS X El Capitan 10.11.5</li> <li>Android SDK build-tool : 24.0.1</li> <li>Android NDK : 12</li> <li>Scons version : 2.5.0</li> </ul> <p>This is build command</p> <ul> <li>SCons TARGET_OS=android TARGET_ARCH=armeabi-v7a TARGET_TRANSPORT=ALL RELEASE=1 SECURED=0 ANDROID_HOME=/Users/KangSengGil/Library/Android/sdk ANDROID_NDK=/Users/KangSengGil/Library/Android/sdk/ndk-bundle ANDROID_GRADLE=/Library/gradle-2.14.1/bin/gradle scons: Reading SConscript files ...</li> </ul> <p>To obtain .aar file, I have to build Iotivity project. but Scons build is showing me some error. I don`t know How i solve this problem. Please Answer This problem!! Thank you</p> <p>Below shows the error</p> <pre><code>NameError: name 'SCons' is not defined: File "/Users/KangSengGil/Documents/iotivity-1.1.0/SConstruct", line 28: SConscript('build_common/SConscript') File "/usr/local/lib/scons-2.5.0/SCons/Script/SConscript.py", line 604: return method(*args, **kw) File "/usr/local/lib/scons-2.5.0/SCons/Script/SConscript.py", line 541: return _SConscript(self.fs, *files, **subst_kw) File "/usr/local/lib/scons-2.5.0/SCons/Script/SConscript.py", line 250: exec _file_ in call_stack[-1].globals File "/Users/KangSengGil/Documents/iotivity-1.1.0/build_common/SConscript", line 386: env.SConscript(target_os + '/SConscript') File "/usr/local/lib/scons-2.5.0/SCons/Script/SConscript.py", line 541: return _SConscript(self.fs, *files, **subst_kw) File "/usr/local/lib/scons-2.5.0/SCons/Script/SConscript.py", line 250: exec _file_ in call_stack[-1].globals File "/Users/KangSengGil/Documents/iotivity-1.1.0/build_common/android/SConscript", line 241: SConscript(env.get('SRC_DIR') + '/extlibs/boost/SConscript') File "/usr/local/lib/scons-2.5.0/SCons/Script/SConscript.py", line 604: return method(*args, **kw) File "/usr/local/lib/scons-2.5.0/SCons/Script/SConscript.py", line 541: return _SConscript(self.fs, *files, **subst_kw) File "/usr/local/lib/scons-2.5.0/SCons/Script/SConscript.py", line 250: exec _file_ in call_stack[-1].globals File "/Users/KangSengGil/Documents/iotivity-1.1.0/extlibs/boost/SConscript", line 35: raise SCons.Errors.EnvironmentError(msg) </code></pre>
0
2016-08-03T18:50:20Z
38,822,955
<p>Looks like a typo - please confirm. SCons command is not found. Maybe use 'scons' ?</p>
0
2016-08-08T06:57:05Z
[ "android", "python", "scons", "iotivity" ]
How to avoid defunct python processes in Linux?
38,751,498
<p>With python3 (3.4.3) on Ubuntu 14.04 I have created a <code>Forker</code> class which I use in two different processes to create child processes. Here is the <code>Forker</code> class:</p> <pre><code>class Forker(object): def __init__(self): self.active_children = [] def reap_children(self): while self.active_children: pid,stat = os.waitpid(0, os.WNOHANG) if not pid: break self.active_children.remove(pid) def fork(self, function, *args, **kwargs): self.reap_children() child_pid = os.fork() if child_pid == 0: function(*args, **kwargs) os._exit(0) else: self.active_children.append(child_pid) return child_pid </code></pre> <p>In the two different Linux processes I derive from this class and then call e.g. something like:</p> <pre><code>self.fork(my_function, my_data) </code></pre> <p>However, I still get a couple of defunct python processes:</p> <pre><code>alexand+ 24777 24735 0 20:40 pts/29 00:00:00 [python3] &lt;defunct&gt; alexand+ 24838 24733 0 20:40 pts/29 00:00:00 [python3] &lt;defunct&gt; </code></pre> <p>Maybe there is something I can change to avoid these defunct processes?</p>
0
2016-08-03T18:51:01Z
38,897,057
<p>Children which exited are <code>&lt;defunct&gt;</code> until the parent waits for them. Since you are calling <em>wait</em> in <code>reap_children()</code> only when you <code>fork()</code> a new child, the exited children stay <code>&lt;defunct&gt;</code> until the next child is forked. To get rid of them earlier, you could call <code>reap_children()</code> (i. e. <em>wait</em>) at earlier times. Normally, this is done through a handler for the SIGCHLD signal.</p>
1
2016-08-11T12:57:06Z
[ "python", "linux", "python-3.x" ]
How to avoid defunct python processes in Linux?
38,751,498
<p>With python3 (3.4.3) on Ubuntu 14.04 I have created a <code>Forker</code> class which I use in two different processes to create child processes. Here is the <code>Forker</code> class:</p> <pre><code>class Forker(object): def __init__(self): self.active_children = [] def reap_children(self): while self.active_children: pid,stat = os.waitpid(0, os.WNOHANG) if not pid: break self.active_children.remove(pid) def fork(self, function, *args, **kwargs): self.reap_children() child_pid = os.fork() if child_pid == 0: function(*args, **kwargs) os._exit(0) else: self.active_children.append(child_pid) return child_pid </code></pre> <p>In the two different Linux processes I derive from this class and then call e.g. something like:</p> <pre><code>self.fork(my_function, my_data) </code></pre> <p>However, I still get a couple of defunct python processes:</p> <pre><code>alexand+ 24777 24735 0 20:40 pts/29 00:00:00 [python3] &lt;defunct&gt; alexand+ 24838 24733 0 20:40 pts/29 00:00:00 [python3] &lt;defunct&gt; </code></pre> <p>Maybe there is something I can change to avoid these defunct processes?</p>
0
2016-08-03T18:51:01Z
38,897,577
<p>Process marked as <code>&lt;defunct&gt;</code> are called zombie processes. The system keeps them in that defunct state to allow their parent to read their status after they have finished running.</p> <p>There are two ways to remove them:</p> <ul> <li>wait for them in the caller <em>shortly</em> after they have finished. The caller could setup a handler for SIGCHLD to be warned that one of its child have just ended, or simply poll them from time to time</li> <li>just ignore them. If the caller explicitely ignores SIGCHLD (<code>signal(SIGCHLD, SIG_IGN);</code>) at fork time, the childs will be immediately removed (no defunct state), but the parent has no more way to wait for them.</li> </ul>
1
2016-08-11T13:19:58Z
[ "python", "linux", "python-3.x" ]
Why doesn't except object catch everything in Python?
38,751,530
<p>The python language reference states in <a href="https://docs.python.org/2.7/reference/compound_stmts.html#the-try-statement" rel="nofollow">section 7.4</a>: </p> <blockquote> <p>For an except clause with an expression, that expression is evaluated, and the clause matches the exception if the resulting object is “compatible” with the exception. An object is compatible with an exception if it is the class or a base class of the exception object, or a tuple containing an item compatible with the exception.</p> </blockquote> <p>So, why doesn't <code>except object:</code> catch everything? <code>object</code> is the base class of all exception classes, so <code>except object:</code> should be able to catch every exception. </p> <p>For example, this should catch the <code>AssertionError</code></p> <pre><code>print isinstance(AssertionError(), object) # prints True try: raise AssertionError() except object: # This block should execute but it never does. print 'Caught exception' </code></pre>
13
2016-08-03T18:52:50Z
38,752,183
<p>I believe the answer can be found in the <a href="https://github.com/tadhgmister/cpython/blob/2.7/Python/ceval.c#L4841" rel="nofollow">source code for python 2.7</a>:</p> <pre><code> else if (Py_Py3kWarningFlag &amp;&amp; !PyTuple_Check(w) &amp;&amp; !Py3kExceptionClass_Check(w)) { int ret_val; ret_val = PyErr_WarnEx( PyExc_DeprecationWarning, CANNOT_CATCH_MSG, 1); if (ret_val &lt; 0) return NULL; } </code></pre> <p>so if <code>w</code> (I assume the expression in the <code>except</code> statement) is not a tuple or exception class <em>and the <code>Py_Py3kWarningFlag</code> is set</em> then trying to use an invalid exception type in the except block will show a warning.</p> <p>That flag is set by adding the <code>-3</code> flag when executing your file:</p> <pre><code>Tadhgs-MacBook-Pro:~ Tadhg$ python2 -3 /Users/Tadhg/Documents/codes/test.py True /Users/Tadhg/Documents/codes/test.py:5: DeprecationWarning: catching classes that don't inherit from BaseException is not allowed in 3.x except object: Traceback (most recent call last): File "/Users/Tadhg/Documents/codes/test.py", line 4, in &lt;module&gt; raise AssertionError() AssertionError </code></pre>
3
2016-08-03T19:32:45Z
[ "python", "exception", "python-2.x", "python-internals" ]
How to Access Spark PipelineModel Parameters
38,751,536
<p>I am running a linear regression using <a href="https://spark.apache.org/docs/latest/ml-pipeline.html#ml-pipelines" rel="nofollow">Spark Pipelines</a> in pyspark. Once the linear regression model is trained, how do I get the coefficients out?</p> <p>Here is my pipeline code:</p> <pre><code># Get all of our features together into one array called "features". Do not include the label! feature_assembler = VectorAssembler(inputCols=get_column_names(df_train), outputCol="features") # Define our model lr = LinearRegression(maxIter=100, elasticNetParam=0.80, labelCol="label", featuresCol="features", predictionCol = "prediction") # Define our pipeline pipeline_baseline = Pipeline(stages=[feature_assembler, lr]) # Train our model using the training data model_baseline = pipeline_baseline.fit(df_train) # Use our trained model to make predictions using the validation data output_baseline = model_baseline.transform(df_val) #.select("features", "label", "prediction", "coefficients") predictions_baseline = output_baseline.select("label", "prediction") </code></pre> <p>I have tried using methods from the <a href="https://spark.apache.org/docs/latest/api/python/pyspark.ml.html?highlight=pipeline#pyspark.ml.PipelineModel" rel="nofollow">PipelineModel class</a>. Here are my attempts to get the coefficients, but I only get an empty list and an empty dictionary:</p> <pre><code>params = model_baseline.stages[1].params print 'Try 1 - Parameters: %s' %(params) params = model_baseline.stages[1].extractParamMap() print 'Try 2 - Parameters: %s' %(params) Out[]: Try 1 - Parameters: [] Try 2 - Parameters: {} </code></pre> <p>Are there methods for PipelineModel that return the trained coefficients?</p>
2
2016-08-03T18:52:58Z
38,752,234
<p>You looking at the wrong property. <code>params</code> can be used to extract <code>Estimator</code> or <code>Transformer</code> <code>Params</code> like input or output columns (see <a href="https://spark.apache.org/docs/latest/ml-pipeline.html#parameters" rel="nofollow">ML Pipeline parameters docs</a> and not estimated values. </p> <p>For <code>LinearRegressionModel</code> use <code>coefficients</code>:</p> <pre><code>model.stages[-1].coefficients </code></pre>
1
2016-08-03T19:35:58Z
[ "python", "apache-spark", "pyspark", "pyspark-sql", "apache-spark-ml" ]
Python 3 Tkinter notebook tabid. How to return the text of all tabs instead of the number ids?
38,751,559
<p>Hey guys I've been learning about Tkinter and making some GUI apps. I'm experimenting with the notebook widget and I'm stuck at one spot. I was wondering if there is a way to use a for loop for all of the current tabs and return the text names of all the tabs instead of the number id. I would like to use it to keep track of the frames. I have searched around and found out how to show tab text for the current tab but I need all the tabs. I haven't been able to find anything specifically for that. Let me know if you have an idea. Thanks.</p> <p>[EDIT] Code snippet</p> <pre class="lang-html prettyprint-override"><code>from tkinter import * from tkinter import messagebox from tkinter.scrolledtext import ScrolledText from tkinter import ttk class Window(Frame): def __init__(self, master): Frame.__init__(self, master) self.master = master self.init_window() self.second_window() self.pm_tabs = [] def init_window(self):# Builds the UI for the main window self.n = ttk.Notebook(root) self.get_tabs_button = Button(self.textboxframe, width=20, text='Get Tab Names', command=lambda:self.get_tab_names()) self.get_tabs_button.grid(row = 0, column= 1, padx=(5,5), pady=(5,150), sticky=N+S+E+W) self.n.add(self.textboxframe, text='Chat') self.n.grid(row=0, column=0, sticky=N+S+E+W) def second_window(self):# UI for second window self.get_tabs_button = Button(self.textboxframe, width=20, text='Get Tab Names', command=lambda:self.get_tab_names()) self.get_tabs_button.grid(row = 0, column= 1, padx=(5,5), pady=(5,150), sticky=N+S+E+W) self.n.add(self.textboxframe, text='Second') def get_tab_names(self): # get the names of the tabs. Hoping to get the text names of the tab. for tabs in self.n.tabs(): print(tabs) if __name__ == '__main__': root = Tk() app = Window(root) root.mainloop() </code></pre>
-1
2016-08-03T18:54:01Z
38,753,930
<p>According to the official documentation, the <a href="https://docs.python.org/3.5/library/tkinter.ttk.html#tkinter.ttk.Notebook.tab" rel="nofollow">tab</a> method of the notebook can be used to return information about a tab, such as the text on the tab.</p> <p>Thus, you can get a list of the text for all of the tabs with something like this:</p> <pre><code>notebook = ttk.Notebook(...) ... tab_names = [notebook.tab(i, option="text") for i in notebook.tabs()] </code></pre> <p>If you're new to list comprehensions, the above is the same as this:</p> <pre><code>tab_names = [] for i in notebook.tabs(): tab_names.append(notebook.tab(i, "text")) </code></pre>
1
2016-08-03T21:26:57Z
[ "python", "python-3.x", "tkinter" ]
Retrieve dictionary items according to a list or priority keys
38,751,577
<p>I would like to retrieve dictionary keys according to a list of priority keys. The dictionary looks like:</p> <pre><code>My_dic = {'name': 'John', 'age': '33', 'gender':'male', 'car': 'SUV'} </code></pre> <p>And the list of criteria is:</p> <pre><code>My_criteria = ['gender', 'age', 'car', 'name'] </code></pre> <p>How can this be done in a pythonic way?</p>
-1
2016-08-03T18:55:09Z
38,751,679
<p>you can retrieve elements by the order you specified</p> <pre><code>for k in sorted(My_dic, key=My_criteria.index): print(k,":",My_dic.get(k)) </code></pre>
2
2016-08-03T19:01:27Z
[ "python", "python-2.7", "python-3.x" ]
Retrieve dictionary items according to a list or priority keys
38,751,577
<p>I would like to retrieve dictionary keys according to a list of priority keys. The dictionary looks like:</p> <pre><code>My_dic = {'name': 'John', 'age': '33', 'gender':'male', 'car': 'SUV'} </code></pre> <p>And the list of criteria is:</p> <pre><code>My_criteria = ['gender', 'age', 'car', 'name'] </code></pre> <p>How can this be done in a pythonic way?</p>
-1
2016-08-03T18:55:09Z
38,751,685
<p>Dictionaries are not sortable, due to the way the information is stored (<a href="http://www.python-course.eu/dictionaries.php" rel="nofollow">http://www.python-course.eu/dictionaries.php</a>).</p> <p>You could create a new list of tuple values using list comprehension, like:</p> <p><code>ordered_info = [(i,my_dic[i]) for i in my_criteria]</code></p>
0
2016-08-03T19:01:51Z
[ "python", "python-2.7", "python-3.x" ]
Retrieve dictionary items according to a list or priority keys
38,751,577
<p>I would like to retrieve dictionary keys according to a list of priority keys. The dictionary looks like:</p> <pre><code>My_dic = {'name': 'John', 'age': '33', 'gender':'male', 'car': 'SUV'} </code></pre> <p>And the list of criteria is:</p> <pre><code>My_criteria = ['gender', 'age', 'car', 'name'] </code></pre> <p>How can this be done in a pythonic way?</p>
-1
2016-08-03T18:55:09Z
38,751,831
<p>You could use an OrderedDict:</p> <pre><code>from collections import OrderedDict My_dic = {'name': 'John', 'age': '33', 'gender':'male', 'car': 'SUV'} My_criteria = ['gender', 'age', 'car', 'name'] My_dic = OrderedDict([(x, My_dic[x]) for x in My_criteria]) # OrderedDict([('gender', 'male'), # ('age', '33'), # ('car', 'SUV'), # ('name', 'John')]) </code></pre> <p>The advantage is that you can still access your data as if it was a dictionary (e.g. <code>My_dic['age']</code>).</p>
1
2016-08-03T19:10:13Z
[ "python", "python-2.7", "python-3.x" ]
Retrieve dictionary items according to a list or priority keys
38,751,577
<p>I would like to retrieve dictionary keys according to a list of priority keys. The dictionary looks like:</p> <pre><code>My_dic = {'name': 'John', 'age': '33', 'gender':'male', 'car': 'SUV'} </code></pre> <p>And the list of criteria is:</p> <pre><code>My_criteria = ['gender', 'age', 'car', 'name'] </code></pre> <p>How can this be done in a pythonic way?</p>
-1
2016-08-03T18:55:09Z
38,751,916
<p>Just iterate through your priority keys, not your dict, then get values using those keys:</p> <pre><code>for key in My_criteria: print My_dic[key] </code></pre> <p>will print the values of your keys in the order that <code>My_criteria</code> is in.</p>
0
2016-08-03T19:15:40Z
[ "python", "python-2.7", "python-3.x" ]