title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
How do I get the size of an RstDocument in Kivy?
38,949,366
<p>This feels like a dumb question but I've crawled the internet for the past few days to no avail over something that seems really simple. Anyways, what I am trying to do is have a TreeView widget that has RstDocument leaves. Now, when I do this I get a bunch of leaves that have smaller windows in a similar fashion to this individual: <a href="http://stackoverflow.com/questions/36523492/kivy-making-a-custom-treeviewnode">Kivy Making a Custom TreeViewNode</a></p> <p>Their solution doesn't work for me because the RstDocument object does not have a texture object associated with it. Upon further research, it doesn't seem to have any attribute associated with this size in pixels for that matter, and neither does the ScrollView layout that it inherits from. Trying to find such numbers gives me stuff that gives sizes that are 100px, which is not what is being displayed.</p> <p>Ideally, I'm trying to get it so that the RstDocument displays completely when extended, so the end-user scrolls through the tree, collapsing what they don't need. I don't need the RstDocument to scroll as a ScrollView is already on the TreeView Widget.</p> <p>The code as close as legally possible:</p> <pre><code>from kivy.app import App from kivy.uix.treeview import TreeView from kivy.uix.treeview import TreeViewLabel from kivy.uix.treeview import TreeViewNode from kivy.uix.scrollview import ScrollView from kivy.uix.rst import RstDocument class TreeViewRst (RstDocument,TreeViewNode): pass class TreeApp (App): def build (self): root = StackLayout() scroll = ScrollView(pos = (0, 0),size_hint=(1,0.78)) body = TreeView(hide_root=True,indent_level=0,size_hint=(1,None)) body.bind(minimum_height=body.setter('height')) intro = body.add_node(TreeViewLabel(text="Title",font_size=18)) intro_diag = body.add_node(TreeViewLabel(text="Article")) body.add_node(TreeViewRst(source='lopsem.rst',size=(100,100)),parent=intro_diag) scroll.add_widget(body) root.add_widget(scroll) return root Window.size = (360,640) tree = TreeApp() tree.run() </code></pre> <p>And a pic of the result:</p> <p><a href="http://i.stack.imgur.com/dQVil.png" rel="nofollow"><img src="http://i.stack.imgur.com/dQVil.png" alt="enter image description here"></a></p>
1
2016-08-15T04:34:01Z
38,983,864
<p>Nevermind, I found the solution to my question. I will post it here for reference to someone else having the same or similar issue.</p> <p>The problem I had when I was trying to get a size out of the RstDocument Object was the fact that at the time the node was still collapsed, and the object's height was 0 as a result. When open, the viewport attribute inherited from the ScrollView had the size of the document in pixels before the scroll. It wasn't 100% as the height when initially opened was larger than it actually was, which is corrected when clicked on, or if scrolling was attempted (so I suspect the object doesn't know until these events occur, where a calculation is performed to determine that).</p> <p>Here is what I did:</p> <pre><code>from kivy.app import App from kivy.uix.treeview import TreeView from kivy.uix.treeview import TreeViewLabel from kivy.uix.treeview import TreeViewNode from kivy.uix.scrollview import ScrollView from kivy.uix.rst import RstDocument from kivy.core.window import Window from kivy.uix.stacklayout import StackLayout class TreeViewRst (RstDocument,TreeViewNode): pass def update_size (event1,event2): event1.size = event1.viewport_size class TreeApp (App): def build (self): root = StackLayout() scroll = ScrollView(pos = (0, 0),size_hint=(1,0.78)) body = TreeView(hide_root=True,indent_level=0,size_hint=(1,None)) body.bind(minimum_height=body.setter('height')) intro = body.add_node(TreeViewLabel(text="Title",font_size=18)) intro_diag = body.add_node(TreeViewLabel(text="Article")) test = body.add_node(TreeViewRst(source='lopsem.rst',size=(100,400)),parent=intro_diag) test.bind(on_scroll_start=update_size) scroll.add_widget(body) root.add_widget(scroll) return root Window.size = (360,640) tree = TreeApp() tree.run() </code></pre> <p>The result was all I could hope for:</p> <p><a href="http://i.stack.imgur.com/WJCFc.png" rel="nofollow">Here it is!!!</a></p> <p>I just want to thank IceMAN for the edit from the other day.</p> <p>Also, thanks all for this site. This is my first time posting a question, but it's been instrumental in answering many questions that I have had in the past.</p>
0
2016-08-16T20:25:47Z
[ "android", "python", "treeview", "scrollview", "kivy" ]
How can I invoke a Python 3 script as a CCS/Eclipse build step on both Linux and Windows?
38,949,377
<p>I have a Python 3.5 script that I would like to invoke as a pre-build step in my Code Composer build. To be clear, it should be run as one of the entries in <em>(my project) > Properties > CCS Build > Steps > Pre-build steps</em>.</p> <p>The script currently begins with the hashbang <code>#!/usr/bin/env python3</code>, but I can change this.</p> <p>On Linux, I can invoke the script as <code>../prebuild.py ../output_file</code>. This fails on Windows 10 with:</p> <pre><code>"C:\\ti\\ccsv6\\utils\\bin\\gmake" -k all ../prebuild.py ../output_file makefile:217: recipe for target 'pre-build' failed process_begin: CreateProcess(NULL, env python3 C:\path\to\prebuild.py ../output_file, ...) failed. make (e=2): The system cannot find the file specified. </code></pre> <p>The path separator does not affect this at all.</p> <p>I also tried <code>python3 ../prebuild.py ../output_file</code>. This does not work on Windows 10 because there is no <code>python3</code> executable. Python 3 is installed as <code>python.exe</code>. Using <code>python</code> fails on Linux because of course Python 3 is installed as <code>python3</code>, and <code>python</code> refers to Python 2.</p> <p>I also tried <code>py ../prebuild.py ../output_file</code>. This fails on Linux because there is no <code>py</code> executable.</p> <p>Is there a cross-platform way to invoke a Python 3 script that can be used for an Eclipse pre-build step? I would like to avoid requiring that developers modify their distribution/Python installation.</p> <p>I am using Code Composer Studio 6, which is based on Eclipse. I expect any answer to this would apply to either.</p> <h2>Context</h2> <p>One of the things I am trying to achieve is to insert the SHA1 of the current Git commit into a file. The <a href="http://stackoverflow.com/a/3443485/188535">accepted answer</a> for doing this is to generate the file as part of the build process by parsing Git output. I have a Python script that can do this on both Windows and Linux, so I need a way to invoke it as part of Eclipse's build process.</p>
2
2016-08-15T04:35:34Z
39,066,986
<p>Have a wrapper script that works under both Python 2 and 3 to detect and run the script with the correct Python version. The Eclipse/CCS pre build step can then be <code>python ../wrapper.py</code> (possibly with extra arguments like <code>../prebuild.py args</code>).</p> <p>You could just check if it is running on Windows or Linux and what version of Python it is running. If it is running on Linux and running the wrong Python version, run <code>subprocess.call(['python3','prebuild.py'])</code>. To check the Python version and OS use:</p> <pre><code>import os, sys, subprocess if sys.version_info[0] &lt; 3 and os.name == 'posix': subprocess.call(['python3','../prebuild.py']) sys.exit() else: subprocess.call(['python','../prebuild.py']) sys.exit() </code></pre> <p>A more generic script might <a href="http://stackoverflow.com/questions/9079036/detect-python-version-at-runtime">check if the interpreter</a> is already the right one and try to pass through arguments if it is:</p> <pre><code>import sys if sys.version_info[0] &gt;= 3 and sys.version_info[1] &gt;= 3: subprocess.call([sys.executable] + sys.argv[1:] </code></pre> <p>Otherwise the wrapper could iterate over a list of possible interpreters until it succeeds, like:</p> <pre><code>interpreters = [["py", "-3"], ["python3"]] for interp in interpreters: # Try a subprocess.call(...) as above. Detect bad return codes (eg. py failed) or OSErrors (ie. command wasn't found). success = False try: success = subprocess.call(...) == 0 except OSError: pass if success: break </code></pre>
1
2016-08-21T17:34:02Z
[ "python", "eclipse", "cross-platform", "code-composer" ]
How to use the argument of a function to determine which class to call?
38,949,378
<p>Let's say we have a bunch of monster classes, which include a Goblin and an Imp:</p> <pre><code>class Goblin(object): def __init__(self): self.Name = "Goblin" self.HP = random.randint(15,20) self.Damage = random.randint(5,10) class Imp(object): def __init__(self): self.Name = "Imp" self.HP = random.randint(5,10) self.Damage = random.randint(2,5) </code></pre> <p>And we have a function that creates monsters, where "Type" will be the type of monster being created:</p> <pre><code>def GenerateCharacter(Type, Number): i=0 while i &lt; (Number): TempChar = #what do I put here so it knows to create Goblins if I do GenerateCharacter(Goblin, 10) Character_List.append(TempChar) i = i + 1 </code></pre> <p>How do I make it so that the class being put into TempChar is a Goblin if the Type argument of the function is "Goblin", the name of the class? So that if I do GenerateCharacter(X, 10), it does TempChar = X() ??</p> <p>If I do GenerateCharacter(Goblin, 10), I would want it to generate 10 instances of the Goblin class and append to Character_List, but if I do GenerateCharacter(Imp, 10) I would want it to do 10 imps.</p>
1
2016-08-15T04:35:34Z
38,949,412
<p>if you're passing it as a string, you can use the <code>globals()</code> method which returns a dictionary of all the variables in the global namespace</p> <pre><code>def GenerateCharacter(Type, Number): Character_List = [] for i in range(Number): name = Type TempChar = globals()[name](name) Character_List.append(TempChar) return Character_List </code></pre> <p>also create the Character_List outside the loop and use a for loop, because it's cleaner and you avoid incrementing the counter of the loop yourself.</p>
1
2016-08-15T04:41:36Z
[ "python", "python-3.x", "oop", "object" ]
How to use the argument of a function to determine which class to call?
38,949,378
<p>Let's say we have a bunch of monster classes, which include a Goblin and an Imp:</p> <pre><code>class Goblin(object): def __init__(self): self.Name = "Goblin" self.HP = random.randint(15,20) self.Damage = random.randint(5,10) class Imp(object): def __init__(self): self.Name = "Imp" self.HP = random.randint(5,10) self.Damage = random.randint(2,5) </code></pre> <p>And we have a function that creates monsters, where "Type" will be the type of monster being created:</p> <pre><code>def GenerateCharacter(Type, Number): i=0 while i &lt; (Number): TempChar = #what do I put here so it knows to create Goblins if I do GenerateCharacter(Goblin, 10) Character_List.append(TempChar) i = i + 1 </code></pre> <p>How do I make it so that the class being put into TempChar is a Goblin if the Type argument of the function is "Goblin", the name of the class? So that if I do GenerateCharacter(X, 10), it does TempChar = X() ??</p> <p>If I do GenerateCharacter(Goblin, 10), I would want it to generate 10 instances of the Goblin class and append to Character_List, but if I do GenerateCharacter(Imp, 10) I would want it to do 10 imps.</p>
1
2016-08-15T04:35:34Z
38,949,458
<p>Assuming you're passing in the name of the class as a string, try something like this:</p> <pre><code>def GenerateCharacter(Type, Number): i=0 while i &lt; (Number): if Type == "Goblin": TempChar = Goblin() elif Type == "Imp": TempChar = Imp() # Etc. for every type of monster you have Character_List.append(TempChar) i += 1 </code></pre> <p>There is perhaps a better way to do this by encapsulating the types Goblin and Imp in a Monster class, which may make your code a little easier to maintain going forward. See here for more info and an example: <a href="http://python-3-patterns-idioms-test.readthedocs.io/en/latest/Factory.html" rel="nofollow">http://python-3-patterns-idioms-test.readthedocs.io/en/latest/Factory.html</a></p> <p>Edit: Here is much closer to what you want:</p> <pre><code>list_of_monsters = [] class Foo: def __init__(self): print "foo created" class Bar: def __init__(self): print "bar created" class Fubar: def __init__(self, num, word): print "Fubar created" self.number = num self.phrase = word def create_monster(class_name, *args): local_class = class_name(*args) list_of_monsters.append(local_class) create_monster(Foo) create_monster(Bar) # You can even pass in arguments: create_monster(Fubar, 1, "Hello") print list_of_monsters </code></pre> <p>If you inspect this code, you will see that list_of_monsters will contain 3 objects, one of each class.</p>
1
2016-08-15T04:48:27Z
[ "python", "python-3.x", "oop", "object" ]
How to get chat id with Kik Api
38,949,402
<p>I've created code with the Kik Api in Python 3.5, but I've come to a stand still when I am trying to get the chat id. I have searched, but I have no idea to use the api to find a chat id to send messages to. How do you get the chat id with the api? My code is here: <a href="http://pastebin.com/LP8ahhhd" rel="nofollow">http://pastebin.com/LP8ahhhd</a> </p>
0
2016-08-15T04:39:35Z
38,949,425
<p>If I'm not mistaken, the code you posted has a chatID field in it? You need to use that to send messages back to the same conversation. See here for more information: <a href="https://dev.kik.com/#/docs/messaging#sending-messages" rel="nofollow">https://dev.kik.com/#/docs/messaging#sending-messages</a></p>
0
2016-08-15T04:43:43Z
[ "python", "json", "api", "kik" ]
How to get chat id with Kik Api
38,949,402
<p>I've created code with the Kik Api in Python 3.5, but I've come to a stand still when I am trying to get the chat id. I have searched, but I have no idea to use the api to find a chat id to send messages to. How do you get the chat id with the api? My code is here: <a href="http://pastebin.com/LP8ahhhd" rel="nofollow">http://pastebin.com/LP8ahhhd</a> </p>
0
2016-08-15T04:39:35Z
38,957,737
<p>When you receive a message it will look something like this</p> <pre><code>{ "messages": [ { "chatId": "0ee6d46753bfa6ac2f089149959363f3f59ae62b10cba89cc426490ce38ea92d", "id": "0115efde-e54b-43d5-873a-5fef7adc69fd", "type": "text", "from": "laura", "participants": ["laura"], "body": "omg r u real?", "timestamp": 1439576628405, "readReceiptRequested": true, "mention": null }, { "chatId": "0ee6d46753bfa6ac2f089149959363f3f59ae62b10cba89cc426490ce38ea92d", "id": "74ded818-1eb7-4266-91bc-c301c2f41fe3", "type": "picture", "from": "aleem", "participants": ["aleem"], "picUrl": "http://example.kik.com/apicture.jpg", "timestamp": 1439576628405, "readReceiptRequested": true, "mention": null } ] } </code></pre> <p>You can grab the appropriate <code>chatId</code> from the <code>chatId</code> of the message you received</p>
0
2016-08-15T15:06:44Z
[ "python", "json", "api", "kik" ]
Intricate file/text manipulation
38,949,431
<p>I have some rather tricky file manipulation I need to perform, but I am rather bad with coding and I am immediately stumped with where to even begin. Any help would be amazing, so thanks in advance. Preferably in Shell or Python as they are the languages I have cursory knowledge of, however if there is an easy solution in another language I am open to it.</p> <hr> <p>I have 2 massive files with information that correlates, however they are not correctly aligned with their columns which makes it difficult to match the data. To complicate things even further, they have varying values after the decimal point, even though it is only the values before the decimal point which are of interest.</p> <p>So what I need to do:</p> <ul> <li><p>Read <code>file1</code>, <code>column1</code>, <code>row1</code>, but ignore all values after the decimal point.</p></li> <li><p>Read <code>file2</code> and search <code>column1</code> for the value taken from <code>file1</code> while again ignoring what comes after the decimal point.</p></li> <li><p>Once the correlative value is found in <code>file2</code>, output both of these lines into a new file (<code>file3</code>) with the rest of the data from their respective lines.</p></li> </ul> <p>That is step one, and if anyone could help me get there I'd be greatly appreciative. The next step is to apply a loop to this process so that it moves onto <code>file1, line2</code> and repeats the process. </p>
-3
2016-08-15T04:44:38Z
38,962,628
<p>You will need to learn Python better than you know it now. Here is an outline what you will need to do. It is very typical for this kind of "file manipulation".</p> <ol> <li>Make a regular expression that will match lines from <code>file1</code> and <code>file2</code> (or two regular expression if the files do not have the same format). Include in your regex, syntax to capture groups that are important to you. </li> <li>Read <code>file1</code> line by line.</li> <li>As each line is read, match it with your regex, find groups that are important, and store them in a hash.</li> <li>Now read <code>file2</code> line by line.</li> <li>As each line is read, match it with your regex, find groups that are important, and search the hash for a match.</li> <li>When you find the match, output to <code>file3</code></li> <li>Go back to 4 and repeat. </li> </ol>
1
2016-08-15T20:35:02Z
[ "python", "shell", "data-manipulation" ]
How do I improve my Python code about heap sort?
38,949,481
<p>I tried to write a heap sort program myself for <a href="https://leetcode.com/problems/contains-duplicate/" rel="nofollow">Leetcode 217. Contains Duplicate</a> as below rather than using Python built-in sort method. Leetcode should accept heap sort method, but for some reasons I don't know, although my heap sort program works well, I still got the runtime rejection from Leetcode. Can anyone help? </p> <p><strong>Solved, below code is re-edited using Floyd algorithm to initialize heap and has passed Leetcode</strong></p> <pre><code>def heapsort(nums): def swap(i, j): nums[i], nums[j] = nums[j], nums[i] def sift(start, size): l = (start &lt;&lt; 1) + 1 # Do not forget () for &lt;&lt; r = l + 1 largest = start if l &lt;= size - 1 and nums[start] &lt; nums[l]: largest = l if r &lt;= size - 1 and nums[largest] &lt; nums[r]: largest = r if largest != start: swap(start, largest) sift(largest, size) size = len(nums) # Initialize heap (Floyd Algorithm) end = (size &gt;&gt; 1) - 1 while end &gt;= 0: sift(end, size) end -= 1 swap(0, size - 1) size -= 1 # Heapify recursively while size &gt; 1: sift(0, size) swap(0, size - 1) size -= 1 </code></pre>
-1
2016-08-15T04:52:56Z
38,949,559
<p>Speaking of heap sort, consider <a href="https://docs.python.org/2/library/heapq.html" rel="nofollow"><code>heapq</code></a> python module. It exists for this very purpose - provide an implementation of the heap queue algorithm. It isn't designed not very conveniently, but there are handy <a href="http://code.activestate.com/recipes/502295-heap-a-heapq-wrapper-class" rel="nofollow">wrappers</a> - you can google it yourself.</p> <p>Speaking of finding duplicates, any <code>n log(n)</code> sorting algorithm shouldn't be efficient enough. Take a look at the python <a href="https://docs.python.org/2.4/lib/types-set.html" rel="nofollow">set</a> builtin!</p>
0
2016-08-15T05:04:38Z
[ "python", "algorithm", "sorting", "heapsort" ]
How do I improve my Python code about heap sort?
38,949,481
<p>I tried to write a heap sort program myself for <a href="https://leetcode.com/problems/contains-duplicate/" rel="nofollow">Leetcode 217. Contains Duplicate</a> as below rather than using Python built-in sort method. Leetcode should accept heap sort method, but for some reasons I don't know, although my heap sort program works well, I still got the runtime rejection from Leetcode. Can anyone help? </p> <p><strong>Solved, below code is re-edited using Floyd algorithm to initialize heap and has passed Leetcode</strong></p> <pre><code>def heapsort(nums): def swap(i, j): nums[i], nums[j] = nums[j], nums[i] def sift(start, size): l = (start &lt;&lt; 1) + 1 # Do not forget () for &lt;&lt; r = l + 1 largest = start if l &lt;= size - 1 and nums[start] &lt; nums[l]: largest = l if r &lt;= size - 1 and nums[largest] &lt; nums[r]: largest = r if largest != start: swap(start, largest) sift(largest, size) size = len(nums) # Initialize heap (Floyd Algorithm) end = (size &gt;&gt; 1) - 1 while end &gt;= 0: sift(end, size) end -= 1 swap(0, size - 1) size -= 1 # Heapify recursively while size &gt; 1: sift(0, size) swap(0, size - 1) size -= 1 </code></pre>
-1
2016-08-15T04:52:56Z
38,958,205
<p>Your code does way too much. You're rebuilding the entire heap with every item that you remove. So what should be an O(n log n) algorithm is instead O(n^2).</p> <p>Essentially, your code is doing this:</p> <pre><code>while array is not empty rearrange array into a heap extract the smallest item </code></pre> <p>Rearranging the heap takes, at best, O(n) time. And extracting the smallest takes O(log n). So your algorithm is O(n^2 + n log n). </p> <p>Actually, your method of building the heap from the bottom up is O(n log n) in itself. So your heap sort algorithm is actually O((n+1)*(n log n)). In any case, it's a highly sub-optimal algorithm.</p> <p>The idea behind heap sort is that you arrange the array into a heap <em>one time</em>. That is an O(n) operation. The algorithm is pretty simple:</p> <pre><code>for i = heap.length/2 downto 1 siftDown(i) </code></pre> <p>This is called <a href="https://en.wikipedia.org/wiki/Binary_heap#Building_a_heap" rel="nofollow">Floyd's algorithm</a>, after its inventor. </p> <p>Note that we start in the middle of the array and sift <em>down</em>. The idea is that the last n/2 items are leaf nodes, so they can't sift down, anyway. By starting at n/2 and working backwards, we can heapify the entire array in O(n) time.</p> <p>After the array is arranged into a heap, we do the following:</p> <pre><code>while heap is not empty output the item at heap[0] move the item at the end of the heap to heap[0] reduce the count of items by 1 siftDown(0) </code></pre> <p>The item at heap[0] is the smallest item remaining in the heap, so we output it. Then, there's no need to rebuild the entire heap. All you have to do is take the last item in the heap, place it at the top, and sift it down into position. The rest of the heap remains valid.</p> <p>Making those changes should reduce the running time, although I don't know if that's going to make your code acceptable. There is another way to check for duplicates. It requires O(n) extra space, but it's faster than sorting.</p> <p>The idea is to create a hash table and then go through the array, checking if the item is in the hash table. If not, add it. If it's already in the table, then it's a duplicate. As Harold pointed out, Python has a <a href="https://docs.python.org/2.4/lib/types-set.html" rel="nofollow">set</a> type that makes this kind of thing easy to do.</p>
1
2016-08-15T15:34:48Z
[ "python", "algorithm", "sorting", "heapsort" ]
How restrict creation of objects of one class to instances of another in Python?
38,949,544
<p>I have encountered a conundrum. I think I should know how to solve this — I am extremely knowledgeable and experienced in Python — but I can't figure it out. It seems like what I am struggling with should be addressed by a design pattern that is a variation on the factory theme, but I can't recall one. (At the end of this writeup I suggest a technical solution, but it seems an implausible one.) I hope you find this discussion interesting in its own right, but I look forward to hearing some suggestions for solutions to my problem.</p> <p>Given classes, A, B, C, and D, I want to limit creation of B instances to methods of A, C instances to methods of B, and D instances to methods of C — in other words A instances are the factories for B instances, B instances the factories for C instances, and C instances the factories for D instances. (I also want each instance of D to store which instance of C created it, each instance of C to store which instance of B created it, and each instance of B to store which instance of A created it, but this is easily arranged by having each instance provide itself as an <code>__init__</code> argument when it creates an instance of the next class down in the hierarchy.)</p> <p>These are model-layer classes that an application manipulates. There is no problem with the application manipulating instances of B, C, or D, it just shouldn't create them directly — all it should be able to create directly are instances of A (and A might even be a singleton). There are various kinds of validation, management, tracking, auditing, etc. that could be implemented in the methods of one class that create instances of the next.</p> <p>An example might be a Operating System that can create Filesystems that can create Directories that can create Files, but application code would have to follow that chain. For example, even if it had its hands on a Directory, it shouldn't be able to create a File giving <code>File.__init__</code> the Directory instance even though that is what instances of Directory would do when asked to create a File.</p> <p>I am looking for a design solution backed up some implementation, not something user-proof -- I understand the futility of the latter.</p> <p>The only thing I have thought of so far is:</p> <ol> <li>begin all class name except A with an underscore</li> <li>access _B() only from A instances, _C() only from B instances, and _D() only from _C instances</li> <li>rely on application-layer programmers to respect this arrangement and directly create instances only of the (possibly singleton) class A</li> </ol> <p>Module-level "hiding" by omitting the class from the module's <code>__all__</code> list is insufficient, because the only affects <code>import *</code> constructions — another module could still reach the class by <code>import module</code> then referencing <code>module.class</code>.</p> <p>(This is all vaguely reminiscent of the C++ problems that require two classes to be friends because they participate in a two-way relationship: instances of each class must be able to reference the methods of the other class that manage that the other side of the relationship.)</p> <p>The solution that may best conform to the semantics and pragmatics of Python is to define D inside C, C defined inside B, and B defined inside A. This seems an awfully ugly way to cram multiple modules worth of code into a single very large class. (And imagine if the chain went down a few more levels.) This is an extension of more common uses of nested classes and maybe the only technically sound way of doing this, but I have never seen this sort of Russian-doll class structure.</p> <p>Ideas?</p>
5
2016-08-15T05:01:52Z
38,949,788
<p>Python is not very good at completely hiding it's objects ... <em>Even</em> if you decide to do the "Russian doll" closure to attempt to hide a class definition, a user can still get at it...</p> <pre><code>class A(object): def create_b(self): class B(object): pass return B() a = A() b = a.create_b() b_cls = type(b) another_b = b_cls() </code></pre> <p>Simply put -- If a user has access to the source code (and they can get it via <code>inspect</code> or at the very least, they can get the bytecode via <code>dis</code> which to a trained eye is good enough), then they have the power to create instances of your class themselves if they're motivated enough.</p> <p>Generally though, it's good enough to just document the class as being something that the user shouldn't instantiate themselves -- If they break that trust, it's their fault when their program crashes and burns (and has some nasty side-effect that causes their computer to catch fire after clearing their hard-drive). This is a pretty central python philosophy, stated nicely in the <a href="https://mail.python.org/pipermail/tutor/2003-October/025932.html">python mail archives</a>:</p> <blockquote> <p>Nothing is really private in python. No class or class instance can keep you away from all what's inside (this makes introspection possible and powerful). Python trusts you. It says "hey, if you want to go poking around in dark places, I'm gonna trust that you've got a good reason and you're not making trouble."</p> <p>After all, we're all consenting adults here.</p> <p>C++ and Java don't have this philosophy (not to the same extent). They allow you create private methods and static members. </p> <p>Perl culture is like python in this respect, but Perl expresses the sentiment a bit differently. As the Camel book puts it,</p> <p><em>"a Perl module would prefer that you stayed out of its living room because you weren't invited, not because it has a shotgun."</em></p> <p>But the sentiment is identical.</p> </blockquote>
6
2016-08-15T05:33:16Z
[ "python", "class", "encapsulation" ]
How restrict creation of objects of one class to instances of another in Python?
38,949,544
<p>I have encountered a conundrum. I think I should know how to solve this — I am extremely knowledgeable and experienced in Python — but I can't figure it out. It seems like what I am struggling with should be addressed by a design pattern that is a variation on the factory theme, but I can't recall one. (At the end of this writeup I suggest a technical solution, but it seems an implausible one.) I hope you find this discussion interesting in its own right, but I look forward to hearing some suggestions for solutions to my problem.</p> <p>Given classes, A, B, C, and D, I want to limit creation of B instances to methods of A, C instances to methods of B, and D instances to methods of C — in other words A instances are the factories for B instances, B instances the factories for C instances, and C instances the factories for D instances. (I also want each instance of D to store which instance of C created it, each instance of C to store which instance of B created it, and each instance of B to store which instance of A created it, but this is easily arranged by having each instance provide itself as an <code>__init__</code> argument when it creates an instance of the next class down in the hierarchy.)</p> <p>These are model-layer classes that an application manipulates. There is no problem with the application manipulating instances of B, C, or D, it just shouldn't create them directly — all it should be able to create directly are instances of A (and A might even be a singleton). There are various kinds of validation, management, tracking, auditing, etc. that could be implemented in the methods of one class that create instances of the next.</p> <p>An example might be a Operating System that can create Filesystems that can create Directories that can create Files, but application code would have to follow that chain. For example, even if it had its hands on a Directory, it shouldn't be able to create a File giving <code>File.__init__</code> the Directory instance even though that is what instances of Directory would do when asked to create a File.</p> <p>I am looking for a design solution backed up some implementation, not something user-proof -- I understand the futility of the latter.</p> <p>The only thing I have thought of so far is:</p> <ol> <li>begin all class name except A with an underscore</li> <li>access _B() only from A instances, _C() only from B instances, and _D() only from _C instances</li> <li>rely on application-layer programmers to respect this arrangement and directly create instances only of the (possibly singleton) class A</li> </ol> <p>Module-level "hiding" by omitting the class from the module's <code>__all__</code> list is insufficient, because the only affects <code>import *</code> constructions — another module could still reach the class by <code>import module</code> then referencing <code>module.class</code>.</p> <p>(This is all vaguely reminiscent of the C++ problems that require two classes to be friends because they participate in a two-way relationship: instances of each class must be able to reference the methods of the other class that manage that the other side of the relationship.)</p> <p>The solution that may best conform to the semantics and pragmatics of Python is to define D inside C, C defined inside B, and B defined inside A. This seems an awfully ugly way to cram multiple modules worth of code into a single very large class. (And imagine if the chain went down a few more levels.) This is an extension of more common uses of nested classes and maybe the only technically sound way of doing this, but I have never seen this sort of Russian-doll class structure.</p> <p>Ideas?</p>
5
2016-08-15T05:01:52Z
38,950,026
<p>Just from the top of my head:</p> <pre><code>def B(object): pass def D(object): pass def bound(object): if type(object) is C: assert isinstance(D) if type(object) is A: assert isinstance(B) else: assert false @bound def C(D): pass @bound def A(B): pass </code></pre>
1
2016-08-15T06:02:42Z
[ "python", "class", "encapsulation" ]
Raspberry Pi - How to print hex value?
38,949,574
<p><a href="http://i.stack.imgur.com/eb68s.png" rel="nofollow"><img src="http://i.stack.imgur.com/eb68s.png" alt="enter image description here"></a>I m using Python in Raspberry Pi and my packet is in hexadecimal value like <code>"0x750x010x010x060x000x08"</code>. I want serial communication between UART and Raspberry Pi so I wrote a program using Python in Raspberry Pi and I'm checking data on terminal but when I selected ASCII option in terminal it showing below output:</p> <pre><code>75 01 01 06 00 08 </code></pre> <p>And when I selected hex option in terminal it is not showing above output. Now I want above output when I will select hex option but not ASCII option. So how to get that? If I need to convert it into hex or byte or any other than tell me the code in Python. Below is my Python script:</p> <pre><code>import serial port=serial.Serial("/dev/ttyAMA0",baudrate=115200,timeout=3.0) while True: a="0x750x010x010x060x000x08" for char in a: if char in a: b=a.replace("0x"," ") port.write("\r\n"+b) </code></pre>
0
2016-08-15T05:06:46Z
38,949,684
<pre><code>import serial port=serial.Serial("/dev/ttyAMA0",baudrate=115200,timeout=3.0) while True: a="0x750x010x010x060x000x08" b=a.replace("0x"," ") #print b alist = b.split(" ") for element in alist port.write("\r\n"+str(element)) </code></pre> <p>this gives the desired formatted data you want</p>
0
2016-08-15T05:21:34Z
[ "python", "windows", "hex", "putty", "raspberry-pi3" ]
Raspberry Pi - How to print hex value?
38,949,574
<p><a href="http://i.stack.imgur.com/eb68s.png" rel="nofollow"><img src="http://i.stack.imgur.com/eb68s.png" alt="enter image description here"></a>I m using Python in Raspberry Pi and my packet is in hexadecimal value like <code>"0x750x010x010x060x000x08"</code>. I want serial communication between UART and Raspberry Pi so I wrote a program using Python in Raspberry Pi and I'm checking data on terminal but when I selected ASCII option in terminal it showing below output:</p> <pre><code>75 01 01 06 00 08 </code></pre> <p>And when I selected hex option in terminal it is not showing above output. Now I want above output when I will select hex option but not ASCII option. So how to get that? If I need to convert it into hex or byte or any other than tell me the code in Python. Below is my Python script:</p> <pre><code>import serial port=serial.Serial("/dev/ttyAMA0",baudrate=115200,timeout=3.0) while True: a="0x750x010x010x060x000x08" for char in a: if char in a: b=a.replace("0x"," ") port.write("\r\n"+b) </code></pre>
0
2016-08-15T05:06:46Z
38,949,911
<p>First of all your <code>for</code> loop and <code>if</code> statment are used wrong here, and they are not required. The <code>while</code> loop can be equivently rewriten as:</p> <pre><code>a = "0x750x010x010x060x000x08" b = a.replace("0x", " ") while True: port.write("\r\n"+b) </code></pre> <p>Your main misanderstanding is that you assume Python understands you want to iterate over hex numbers. But it doesn't. In you original loop it just iterates the <code>a</code> string letter by letter. And in fact at each iteration of <code>for</code> loop you just changes the orignal <code>a</code> string to " 75 01 01 06 00 08" and send it as a string.</p> <p>If you need to send bytes, you should split your string into separate records with each byte's infromation and convert these records to bytes. Here is the code for that</p> <pre><code>a = "0x750x010x010x060x000x08" b1 = a.split("0x") # b1 is ["", "75", "01", "01", "06", "00", "08"], the values are still strings b2 = [int(x, 16) for x in b1[1:]] # b2 is a list of integers, the values calculated from strings assuming they are hex (16-bit) numbers # use b1[1:] to cut the first blank string b = str(bytearray(b2)) #b joins values list into a bytes string (each interger transformed into one byte) while True: port.write("\r\n" + b) </code></pre> <p>Update for question in comments: If <code>a</code> format is like this "0x750101060008", you just split it by 2 letters:</p> <pre><code>b1 = [a[2*i:2*i+2] for i in range(len(a)/2)] </code></pre>
0
2016-08-15T05:49:13Z
[ "python", "windows", "hex", "putty", "raspberry-pi3" ]
Thread identifier in multiprocessing pool workers
38,949,614
<p>I believed <code>Thread.ident</code> as a unique identifier of threads but now I see different worker processes in <code>multiprocessing.poo.Pool</code> reporting same thread identifier by <code>threading.current_thread().ident</code>. How?</p>
0
2016-08-15T05:12:52Z
38,949,714
<p>Depending on the platform, the ids may or may not be unique. The important thing to note here is that the python multiprocessing library actually uses processes instead of threads for multiprocessing, and so thread ids in between processes is actually a platform-specific implementation detail. </p> <p>On Unix/Linux: a thread id is guaranteed to be unique inside a single process. However, a thread id is not guaranteed to be unique across processes. The processid (pid), however, will be unique across processes. Thus, you can obtain a unique identifier by putting the two together. Detail from the <code>man pthread</code> page <a href="http://man7.org/linux/man-pages/man7/pthreads.7.html" rel="nofollow">http://man7.org/linux/man-pages/man7/pthreads.7.html</a></p> <p>On windows: a thread id is unique across the whole machine: <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/ms686746(v=vs.85).aspx" rel="nofollow">https://msdn.microsoft.com/en-us/library/windows/desktop/ms686746(v=vs.85).aspx</a></p>
1
2016-08-15T05:25:03Z
[ "python", "multithreading", "multiprocessing", "python-multiprocessing" ]
How to implement a Nadex autotrading bot?
38,949,710
<p>I have been searching for a way to autotrade on Nadex</p> <blockquote> <p><a href="https://www.nadex.com" rel="nofollow">https://www.nadex.com</a></p> </blockquote> <p>and came across this script <a href="https://github.com/FreeTheQuarks/NadexBot" rel="nofollow">https://github.com/FreeTheQuarks/NadexBot</a></p> <p>It is an old script and I am not that experienced in Python.</p> <p><strong><code>Q1:</code></strong> Is this a good way to go about, thus since it is not a official API and is probably scraping data from the site, which would mean slower requests and trade execution?</p> <hr> <p>There is also an unofficial API client <a href="https://github.com/knoguchi/nadex/tree/master/nadex" rel="nofollow">https://github.com/knoguchi/nadex/tree/master/nadex</a></p> <p>But again, not sure if good for live trading.</p> <p><strong><code>Q2:</code></strong> Is there better ways to go about this and if so where should I start?</p>
-1
2016-08-15T05:24:36Z
38,958,186
<h2><strong><code>A1:</code></strong> Measure Twice Rather Before One Cut$</h2> <p>Simply put, it is your money you trade with, so warnings like this one ( from FreeTheQuarks )</p> <blockquote> <p><em>(cit.:</em>)<br><strong>This was the first non-trivial program I wrote.<br>It hasn't received any significant updates in years.<br>I've only made minor readability updates after first putting this on git.</strong></p> </blockquote> <p>should give one a sufficient sign to re-think the risks, before one puts a first dollar on table.</p> <p>This is a for-profit game, isn't it?</p> <hr> <h2><strong><code>A2:</code></strong> Yes, there is a better way.</h2> <p>All quantitatively supported trading strategies need stable and consistent care - i.e. one needs to have</p> <ol> <li>rock-solid historical data</li> <li>stable API to work with ( Trade Execution &amp; Management, Market Events )</li> <li>reliable &amp; performant testbed for validating one's own quantitative model of the trading strategy</li> </ol> <p>Having shared this piece of some 100+ man*years experience, one may decide on one's own whether to rely on or rather forget to start any reasonable work with just some reverse-engineering efforts on an "un-official API client".</p> <p>In case the profit generation capability of some trading strategy supports the case, one may safely order an outsourced technical implementation and technical integration efforts in a turn-key manner.</p> <blockquote> <p><strong><code>Epilogue:</code></strong><br><br>If there are quantitatively supported reasons to implement a trading strategy,<br>the profit envelope thereof sets the ultimate economically viable model<br>for having that strategy automated and operated in-vivo.<br><br><strong>Failure to decide in this order of precedence<br>results in nothing but wasted time &amp; money.<br><em>Your money.</em></strong></p> </blockquote>
0
2016-08-15T15:33:20Z
[ "python", "api", "trading", "algorithmic-trading" ]
Openerp Scheduler is working but the attached funciton not executing
38,949,745
<p>I tried to execute a function using Openerp scheduler but it changed nothing. If I run the function only it works perfectly fine but not with the scheduler. Please help me with this.</p> <p>in hr_holidays.xml file I added this,</p> <pre><code>&lt;record id="ir_cron_scheduler" model="ir.cron"&gt; &lt;field name="name"&gt;Casual Leave Allocation&lt;/field&gt; &lt;field name="interval_number"&gt;1&lt;/field&gt; &lt;field name="interval_type"&gt;minutes&lt;/field&gt; &lt;field name="numbercall"&gt;-1&lt;/field&gt; &lt;field eval="False" name="doall"/&gt; &lt;field eval="'hr.holidays'" name="hr.holidays"/&gt; &lt;field eval="'allocate_on_probations'" name="allocate_on_probations"/&gt; &lt;field eval="'()'" name="args"/&gt; &lt;/record&gt; </code></pre> <p>and with little adjustments UI looks like this; <a href="http://i.stack.imgur.com/jB86e.png" rel="nofollow"><img src="http://i.stack.imgur.com/jB86e.png" alt="enter image description here"></a></p> <p><a href="http://i.stack.imgur.com/olmRu.png" rel="nofollow"><img src="http://i.stack.imgur.com/olmRu.png" alt="enter image description here"></a></p> <p><a href="http://i.stack.imgur.com/3Vqrd.png" rel="nofollow"><img src="http://i.stack.imgur.com/3Vqrd.png" alt="enter image description here"></a></p> <p>The function</p> <pre><code>def allocate_on_probations(self, cr, uid, ids,tl, context=None): allo=0 state='active' result = {} emps=self.pool.get('hr.employee').search(cr, uid, [('current_status','=','active')], context=context) if emps: for r in emps: hol_state=2 gt_dt=cr.execute("""SELECT appointed_date FROM hr_employee WHERE id= %d order by id"""%(r)) gt_dd=cr.fetchone()[0] #getting today details today = datetime.datetime.now() tt=today.date() td=tt.day tm=tt.month ty=tt.year #getting appointment date details app=datetime.datetime.strptime(gt_dd, "%Y-%m-%d").date() #print app ay=app.year am=app.month ad=app.day if ay==ty: #compairing today and appointed date comp=(tt-app) chat=int(comp.days) chat_mod=chat%30 print chat_mod print r if chat_mod==29: hol_obj=self.pool.get('hr.holidays') print hol_obj condition_1=[('employee_id','=',r),('type','=','add'),('holiday_status_id','=',hol_state)] hol_emp=hol_obj.search(cr, uid,condition_1, context=context) if hol_emp: for n in hol_emp: hol_dt=cr.execute("""SELECT number_of_days_temp FROM hr_holidays WHERE id= %d order by id"""%(n)) hol_dd=cr.fetchone()[0] hol_inc=(hol_dd+0.5) print hol_inc cr.execute("""UPDATE hr_holidays SET number_of_days_temp= %d WHERE id= %d"""%(hol_inc,n)) cr.execute("""UPDATE hr_holidays SET number_of_days= %d WHERE id= %d"""%(hol_inc,n)) return True </code></pre>
0
2016-08-15T05:29:06Z
38,953,768
<p>You just need to set default value for that parameter and no need to pass it via cron, and if it is required in function the pass it from the cron.</p> <pre><code>def allocate_on_probations(self, cr, uid, ids,tl=False, context=None): allo=0 state='active' result = {} emps=self.pool.get('hr.employee').search(cr, uid, [('current_status','=','active')], context=context) if emps: for r in emps: hol_state=2 gt_dt=cr.execute("""SELECT appointed_date FROM hr_employee WHERE id= %d order by id"""%(r)) gt_dd=cr.fetchone()[0] #getting today details today = datetime.datetime.now() tt=today.date() td=tt.day tm=tt.month ty=tt.year #getting appointment date details app=datetime.datetime.strptime(gt_dd, "%Y-%m-%d").date() #print app ay=app.year am=app.month ad=app.day if ay==ty: #compairing today and appointed date comp=(tt-app) chat=int(comp.days) chat_mod=chat%30 print chat_mod print r if chat_mod==29: hol_obj=self.pool.get('hr.holidays') print hol_obj condition_1=[('employee_id','=',r),('type','=','add'),('holiday_status_id','=',hol_state)] hol_emp=hol_obj.search(cr, uid,condition_1, context=context) if hol_emp: for n in hol_emp: hol_dt=cr.execute("""SELECT number_of_days_temp FROM hr_holidays WHERE id= %d order by id"""%(n)) hol_dd=cr.fetchone()[0] hol_inc=(hol_dd+0.5) print hol_inc cr.execute("""UPDATE hr_holidays SET number_of_days_temp= %d WHERE id= %d"""%(hol_inc,n)) cr.execute("""UPDATE hr_holidays SET number_of_days= %d WHERE id= %d"""%(hol_inc,n)) return True </code></pre> <p>And if it is mandatory then you need to pass t1 value from the cron in <strong>args</strong></p> <p><a href="http://i.stack.imgur.com/cGbRk.png" rel="nofollow"><img src="http://i.stack.imgur.com/cGbRk.png" alt="enter image description here"></a></p>
1
2016-08-15T10:57:02Z
[ "python", "openerp" ]
AttributeError: 'list' object has no attribute 'astimezone'
38,950,012
<p>My python script: </p> <pre><code>import ftplib import hashlib import httplib import pytz from datetime import datetime import urllib from pytz import timezone import os.path, time import glob def ftphttp(): files = glob.glob('Desktop/images/*.png') ts = map(os.path.getmtime, files) dts = map(datetime.fromtimestamp, ts) print ts timeZone= timezone('Asia/Singapore') #converting the timestamp in ISOdatetime format localtime = dts.astimezone(timeZone).isoformat() </code></pre> <p>I was trying to get the multiple files timestamp. I able to print out all the files in my folder</p> <pre><code> [1467910949.379998, 1466578005.0, 1466528946.0] </code></pre> <p>But it also prompt me this error about the timezone. Anybody got any ideas?</p> <pre><code>Traceback (most recent call last): File "&lt;pyshell#76&gt;", line 1, in &lt;module&gt; ftphttp() File "/home/kevin403/Testtimeloop.py", line 22, in ftphttp localtime = dts.astimezone(timeZone).isoformat() AttributeError: 'list' object has no attribute 'astimezone' </code></pre>
-4
2016-08-15T06:01:50Z
38,950,045
<p>You are trying to call a method on a list of objects, instead of the objects in the list. Try calling the method on the first object instead:</p> <pre><code>localtime = dts[0].astimezone(timeZone).isoformat() </code></pre> <p>Or map over the list to get all timestamps in iso format:</p> <pre><code>localtimes = map(lambda x: x.astimezone(timeZone).isoformat(), dts) </code></pre>
1
2016-08-15T06:04:32Z
[ "python", "python-2.7" ]
AttributeError: 'list' object has no attribute 'astimezone'
38,950,012
<p>My python script: </p> <pre><code>import ftplib import hashlib import httplib import pytz from datetime import datetime import urllib from pytz import timezone import os.path, time import glob def ftphttp(): files = glob.glob('Desktop/images/*.png') ts = map(os.path.getmtime, files) dts = map(datetime.fromtimestamp, ts) print ts timeZone= timezone('Asia/Singapore') #converting the timestamp in ISOdatetime format localtime = dts.astimezone(timeZone).isoformat() </code></pre> <p>I was trying to get the multiple files timestamp. I able to print out all the files in my folder</p> <pre><code> [1467910949.379998, 1466578005.0, 1466528946.0] </code></pre> <p>But it also prompt me this error about the timezone. Anybody got any ideas?</p> <pre><code>Traceback (most recent call last): File "&lt;pyshell#76&gt;", line 1, in &lt;module&gt; ftphttp() File "/home/kevin403/Testtimeloop.py", line 22, in ftphttp localtime = dts.astimezone(timeZone).isoformat() AttributeError: 'list' object has no attribute 'astimezone' </code></pre>
-4
2016-08-15T06:01:50Z
38,950,053
<p><code>dts</code> is a list of time zones. So you need to do:</p> <pre><code>[ts.astimezone(timeZone) for ts in dts] </code></pre> <p>This will give you a list of the three time zones</p>
0
2016-08-15T06:05:09Z
[ "python", "python-2.7" ]
matplotlib loaded font appears fade on another machine
38,950,173
<p>I have a python code using matplotlib which appears fine on a centos7 machine but on another centos7 machine, the font appears fade on the axes and legend: <a href="http://i.stack.imgur.com/xuQcx.png" rel="nofollow"><img src="http://i.stack.imgur.com/xuQcx.png" alt="enter image description here"></a></p> <p>My font is at <code>/usr/share/fonts/MyFont</code> I checked that my font appears in <code>/root/.cache/matplotlib/fontList.cache</code> I've tried deleting and regenerating it.</p> <pre><code>def plot(data, format='png', width=400, height=400, font='MyFont'): font_size = max(3, int(width / 40)) plt.cla() plt.clf() matplotlib.rcParams.update({'font.size': font_size,\ 'font.family': font}) fig = plt.figure() _width = width / fig.get_dpi() _height = height / fig.get_dpi() fig.set_size_inches(_width, _height) plt.xlabel('this is x axis') plt.ylabel('this is y axis') plt.legend(bbox_transform=plt.gcf().transFigure, loc=2) x = [1,2,3,4] y = x plt.plot(x, y, color='b', label='line1') plt.legend(bbox_transform=plt.gcf().transFigure, loc=2) plt.title('this is title', fontweight='bold') </code></pre> <hr> <p>update:</p> <p>I think the problem is that I have Lato-Hairline.ttf and Lato-Regular.ttf and on one operating system it is taking Regular as the default where on this new machine it is taking Hairline as the default which is so fade.</p>
0
2016-08-15T06:19:17Z
38,966,526
<p>I deleted <code>Lato-HairlineItalic.ttf</code> and <code>Lato-Hairline.ttf</code> and then deleted <code>/root/.cache/matplotlib/fontList.cache</code>. It caused matplotlib to pick the other ttf file which is the proper regular form of the font. I still would like to know how matplotlib determines which font is the regular form (default) such that it is behaviing randomly on different centos machines.</p>
0
2016-08-16T04:09:15Z
[ "python", "matplotlib" ]
Pump bytes from asyncio StreamReader into a file descriptor
38,950,347
<p>I have a Python function (implemented in C++) that reads from a file descriptor (wrapped in <code>FILE*</code> on the C++ side) and I need to feed the function from an <code>asyncio.StreamReader</code>. Specifically, the reader is the content of a HTTP response: <a href="http://aiohttp.readthedocs.io/en/stable/client_reference.html#aiohttp.ClientResponse.content" rel="nofollow">aiohttp.ClientResponse.content</a>.</p> <p>I thought I might <a href="https://docs.python.org/3.5/library/os.html?highlight=fdopen#os.pipe" rel="nofollow">open a pipe</a>, pass the read-end to the C++ function and <a href="https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.AbstractEventLoop.connect_write_pipe" rel="nofollow">connect the write-end</a> to <code>asyncio</code>'s event loop. However, how can I move the data from the stream reader to the pipe, with proper flow control and as little copying as possible?</p> <p>The skeleton of the code with the missing parts is as following:</p> <pre><code># obtain the StreamReader from aiohttp content = aiohttp_client_response.content # create a pipe (pipe_read_fd, pipe_write_fd) = os.pipe() # now I need a suitable protocol to manage the pipe transport protocol = ? (pipe_transport, __) = loop.connect_write_pipe(lambda: protocol, pipe_write_fd) # the protocol should start reading from `content` and writing into the pipe return pipe_read_fd </code></pre>
3
2016-08-15T06:36:20Z
39,332,188
<p>I got around this issue by using a <code>ThreadPoolExecutor</code> and blocking calls to <code>os.write</code>:</p> <pre><code>(read_fd, write_fd) = os.pipe() task_1 = loop.create_task(pump_bytes_into_fd(write_fd)) task_2 = loop.run_in_executor(executor_1, parse_bytes_from_fd(read_fd)) async def pump_bytes_into_fd(write_fd): while True: chunk = await stream.read(CHUNK_SIZE) if chunk is None: break # process the chunk await loop.run_in_executor(executor_2, os.write, write_fd, chunk) </code></pre> <p>It is crucial that two different executors are used for blocking reads and writes to avoid deadlocks.</p>
0
2016-09-05T13:55:57Z
[ "python", "python-asyncio", "aiohttp" ]
mocking an instance method of inner object in python 3.4
38,950,349
<p>I have a class in my code that makes use of a third party library. I would like to mock the instance method of the object that I obtain by calling an instance method of the library class. I am not clear on how to mock the instance method of this inner object. Following is my code:</p> <p>My class:</p> <pre><code>from a import A class MyClass(object): def __init__(self): self.obj = A() def do_something(self): b = self.obj.get_inner_object() result = b.do_inner() return result </code></pre> <p>Here is my test class:</p> <pre><code>from unittest import TestCase from unittest.mock import MagicMock from unittest.mock import patch from a import A class TestMyClass(TestCase): def __init__(self): self.my_class = MyClass() @patch.object(A,'get_inner_object') def test_do_something(self, mock_get_inner_object): test_res = self.my_class.do_something() </code></pre> <p>As you can see above, I would like to mock away 2 methods of my library - get_inner_object() and do_inner() which is the instance method of the object returned by get_inner_object(). I was able to mock get_inner_object(), but I am not clear on how to mock the do_inner() method. Please clarify. Here's the help I am following: <a href="https://www.toptal.com/python/an-introduction-to-mocking-in-python" rel="nofollow">https://www.toptal.com/python/an-introduction-to-mocking-in-python</a></p>
0
2016-08-15T06:36:26Z
38,950,490
<p>Just mock out all of <code>A</code>:</p> <pre><code>@patch('a.A') def test_do_something(self, mock_A): mock_b = mock_A.return_value.get_inner_object.return_value mock_b.do_inner.return_value = 'mocked return value' test_res = self.my_class.do_something() self.assertEqual(test_res, 'mocked return value') </code></pre> <p>After all, you are testing <code>MyClass</code> here, not <code>A</code>.</p> <p>Either way, wether you use <code>@patch.object(A, 'get_inner_object')</code> or patch all of <code>A</code>, the <code>self.obj.get_inner_object()</code> expression <em>calls</em> a <code>Mock</code> instance, so the <code>.return_value</code> attribute is returned at that point. The <code>do_inner</code> method is just another chained call on that returned mock here, so you can set what is returned for that method by setting the <code>.return_value</code> attribute to something you test for.</p> <p>To translate that back to your <code>@patch.object()</code> situation, <code>mock_b</code> is then the <code>mock_inner_object.return_value</code> object:</p> <pre><code>@patch.object(A,'get_inner_object') def test_do_something(self, mock_get_inner_object): mock_b = mock_get_inner_object.return_value mock_b.do_inner.return_value = 'mocked return value' test_res = self.my_class.do_something() self.assertEqual(test_res, 'mocked return value') </code></pre>
0
2016-08-15T06:49:01Z
[ "python", "unit-testing", "python-3.x", "mocking" ]
Opening file from Docker Container in Python/Django Web App
38,950,376
<p>I have create a docker container which specifies</p> <pre><code>WORKDIR /usr/src/app </code></pre> <p>Inside my Django web app, I try to access</p> <pre><code>file_path = '/usr/src/app/management_app/mock/printable-profile.json' File "/usr/src/app/management_app/urls/__init__.py", line 5, in &lt;module&gt; app_1 | from ..views import views app_1 | File "/usr/src/app/management_app/views/views.py", line 13, in &lt;module&gt; app_1 | json_data = open(file_path) app_1 | FileNotFoundError: [Errno 2] No such file or directory: '/usr/src/app/management_app/mock/printable-profile.json' </code></pre> <p>The container was built correctly. I accessed the container file system by creating a snapshot and running</p> <pre><code>$ docker run -t -i mgmtsnapshot /bin/bash </code></pre> <p>And I can confirm the file exists at the required path. Is there a problem with calling <code>open()</code> inside a docker container? Or what else is causing the <code>file not found</code> error?</p>
0
2016-08-15T06:38:32Z
38,952,709
<p>Are you mounting /usr/src/app as a volume from the host? If yes, you probably rather run into permission issues, since the host enforces the uid/guid/permissions and if your <strong>python application runs under user X</strong>, but the host defined uid=14 which is noth userX, but also <code>u=r,g=,o=</code> as permissions, you cannot access it. Ensure, you do either fix the permission issues on the host by losing them up (ugly) or use tools which can offer you user-ownership mapping on sync, like <a href="http://docker-sync.io" rel="nofollow">http://docker-sync.io</a></p>
0
2016-08-15T09:40:05Z
[ "python", "django", "docker" ]
Error while deploy my django website on heroku
38,950,526
<p>I created a personal portfolio website using django and it also includes a blog. You can see the exact directory listing and source code in my github repository by clicking <a href="https://github.com/ikushum/First-django-website" rel="nofollow">here </a></p> <p>I have the procfile and the requirements.txt files as said in the heroku website and did the following in command prompt as directed by heroku :</p> <pre><code>$ heroku login $ heroku git:clone -a appname $ cd appname $ git add . $ git commit -am "make it better" $ git push heroku master </code></pre> <p>Now I see the following error while deploying and the push fails :</p> <pre><code>Warning: Your application is missing a Procfile. This file tells Heroku how to run your application. </code></pre> <p>Yes there is a procfile in the directory though. Please help me deploy this website in heroku.</p>
0
2016-08-15T06:52:28Z
38,951,230
<p>Your file is called Procfile.txt. It should be called just Procfile.</p>
0
2016-08-15T07:49:29Z
[ "python", "django", "heroku" ]
Error while deploy my django website on heroku
38,950,526
<p>I created a personal portfolio website using django and it also includes a blog. You can see the exact directory listing and source code in my github repository by clicking <a href="https://github.com/ikushum/First-django-website" rel="nofollow">here </a></p> <p>I have the procfile and the requirements.txt files as said in the heroku website and did the following in command prompt as directed by heroku :</p> <pre><code>$ heroku login $ heroku git:clone -a appname $ cd appname $ git add . $ git commit -am "make it better" $ git push heroku master </code></pre> <p>Now I see the following error while deploying and the push fails :</p> <pre><code>Warning: Your application is missing a Procfile. This file tells Heroku how to run your application. </code></pre> <p>Yes there is a procfile in the directory though. Please help me deploy this website in heroku.</p>
0
2016-08-15T06:52:28Z
38,951,339
<p>It might be that you made a <code>.txt</code> file instead of a non-extension one or that you named it <code>procfile</code> and not <code>Procfile</code>. Heroku is sensitive about capitalisation.</p>
0
2016-08-15T07:58:48Z
[ "python", "django", "heroku" ]
Panda runtime warning Cannot compare type 'Timestamp' with type 'str', sort order is undefined for incomparable objects
38,950,570
<p>I am currently working on homework 2 for the coursera computational finance.</p> <p>While executing this line:</p> <pre><code>ep.eventprofiler(df_events, d_data, i_lookback=20, i_lookforward=20, s_filename=report_filename, b_market_neutral=True, b_errorbars=True, s_market_sym='SPY') </code></pre> <p>I get the error: </p> <pre><code>anaconda/lib/python2.7/site-packages/pandas/indexes/base.py:2397: RuntimeWarning: Cannot compare type 'Timestamp' with type 'str', sort order is undefined for incomparable objects return this.join(other, how=how, return_indexers=return_indexers) </code></pre> <p>Which creates the pdf file, shows the number of events occurred but not actually draw the events. I am not sure why this occurs. I am using pandas <strong>0.18.0</strong></p> <p>Any ideas? I appreciate the help.</p> <p>df_events.dtypes sample:</p> <pre><code>ALTR float64 ALXN float64 AMAT float64 AMD float64 AMGN float64 AMP float64 AMT float64 ... WDC float64 WEC float64 WFC float64 WFM float64 WHR float64 WIN float64 WLP float64 WM float64 WMB float64 WMT float64 XLNX float64 XOM float64 XRAY float64 XRX float64 XYL float64 YHOO float64 YUM float64 ZION float64 ZMH float64 SPY float64 dtype: object </code></pre> <p>Here is the d_data.dtypes log sample:</p> <pre><code> YHOO YUM ZION ZMH SPY 2008-01-02 16:00:00 23.72 37.88 45.29 66.29 144.93 2008-01-03 16:00:00 23.84 37.35 44.38 66.36 144.86 2008-01-04 16:00:00 23.16 36.82 42.40 66.50 141.31 2008-01-07 16:00:00 23.18 37.68 43.28 68.66 141.19 </code></pre> <p>I get </p> <pre><code> d_data.dtypes *** AttributeError: 'dict' object has no attribute 'dtypes' </code></pre> <p>when I try to print out the d_data dtypes. </p>
1
2016-08-15T06:55:49Z
39,002,578
<p>the trouble is caused by the line:</p> <pre><code>df_rets = df_rets - df_rets[s_market_sym] </code></pre> <p>in these couple of lines:</p> <pre><code>if b_market_neutral == True: df_rets = df_rets - df_rets[s_market_sym] del df_rets[s_market_sym] del df_events[s_market_sym] </code></pre> <p>in <code>eventprofiler(...)</code> function. Quite frankly I think the line is a bug and it should be put as a comment, to say at least - as the logic behind escapes my understanding. Others are just fine.</p> <p>If you set the argument <code>b_market_neutral</code> to <code>False</code>, it will give you a nice graph, but that also takes into account the SPY market data when calculating the mean return. So the workaround, in order to use a "proper" logic when calculating mean values, would be to comment this line and recompile QSTK with this modification. </p> <p>Hope this helps.</p> <p>Regards, Daniel</p>
2
2016-08-17T17:09:46Z
[ "python", "pandas", "computational-finance" ]
Panda runtime warning Cannot compare type 'Timestamp' with type 'str', sort order is undefined for incomparable objects
38,950,570
<p>I am currently working on homework 2 for the coursera computational finance.</p> <p>While executing this line:</p> <pre><code>ep.eventprofiler(df_events, d_data, i_lookback=20, i_lookforward=20, s_filename=report_filename, b_market_neutral=True, b_errorbars=True, s_market_sym='SPY') </code></pre> <p>I get the error: </p> <pre><code>anaconda/lib/python2.7/site-packages/pandas/indexes/base.py:2397: RuntimeWarning: Cannot compare type 'Timestamp' with type 'str', sort order is undefined for incomparable objects return this.join(other, how=how, return_indexers=return_indexers) </code></pre> <p>Which creates the pdf file, shows the number of events occurred but not actually draw the events. I am not sure why this occurs. I am using pandas <strong>0.18.0</strong></p> <p>Any ideas? I appreciate the help.</p> <p>df_events.dtypes sample:</p> <pre><code>ALTR float64 ALXN float64 AMAT float64 AMD float64 AMGN float64 AMP float64 AMT float64 ... WDC float64 WEC float64 WFC float64 WFM float64 WHR float64 WIN float64 WLP float64 WM float64 WMB float64 WMT float64 XLNX float64 XOM float64 XRAY float64 XRX float64 XYL float64 YHOO float64 YUM float64 ZION float64 ZMH float64 SPY float64 dtype: object </code></pre> <p>Here is the d_data.dtypes log sample:</p> <pre><code> YHOO YUM ZION ZMH SPY 2008-01-02 16:00:00 23.72 37.88 45.29 66.29 144.93 2008-01-03 16:00:00 23.84 37.35 44.38 66.36 144.86 2008-01-04 16:00:00 23.16 36.82 42.40 66.50 141.31 2008-01-07 16:00:00 23.18 37.68 43.28 68.66 141.19 </code></pre> <p>I get </p> <pre><code> d_data.dtypes *** AttributeError: 'dict' object has no attribute 'dtypes' </code></pre> <p>when I try to print out the d_data dtypes. </p>
1
2016-08-15T06:55:49Z
39,687,712
<p>@DanielTC thanks for pointing out where the issue was, I can confirm it.</p> <p>i think the logic is that market returns should be subtracted from the individual stocks daily returns, so you are left with just what the stock gained/lost</p> <p>I solved it like this:</p> <pre><code>if b_market_neutral is True: # it fails here: df_rets = df_rets - df_rets[s_market_sym] df_rets = df_rets.sub(df_rets[s_market_sym].values, axis=0) # this works del df_rets[s_market_sym] del df_events[s_market_sym] </code></pre>
1
2016-09-25T14:06:07Z
[ "python", "pandas", "computational-finance" ]
Have to use sleep with pyserial when opening com port for arduino nano
38,950,613
<p>I'm running pyserial (3.1.1) on Windows 10 with python 2.7</p> <p>Update - get the same issue running on Xubuntu 16 as well as Windows.</p> <p>I'm writing via serial to an arduino nano via usb / serial interface.</p> <p>I'm writing a simple character string (eg. '2+') and reading the output in the arduino. If I keep the first time.sleep at 2 seconds after opening the com port it works. If I change it to 1 or remove it the arduino seems to receive a different character / encoding and it does not work.</p> <p>Ideally I don't want any sleep so that it works quicker. Am I doing something wrong or is there a better way to do this so that I can remove the sleep or at least reduce it?</p> <p>Python Code:</p> <pre><code>import sys, getopt import time import serial ser = serial.Serial( port='COM3', baudrate=9600, parity=serial.PARITY_ODD, stopbits=serial.STOPBITS_TWO, bytesize=serial.SEVENBITS ) time.sleep(1) #change this to 2 and it works ser.write('2+') out = '' time.sleep(1) while ser.inWaiting() &gt; 0: out += ser.read(1) if out != '': print "&gt;&gt;" + out else: print "&gt;&gt; nothing!" time.sleep(1) ser.close() </code></pre> <p>Arduino code (I'm having some minor issues with the ASCII char numbers as well - I think it is the signing of the bytes but that is the least of my problems at the moment)</p> <pre><code>String inString = ""; int pinNumber = 0; void setup() { // initialize serial communication at 9600 bits per second: Serial.begin(9600); } void loop() { // expected input: 1+ //to change the digital pin to on // expected input: 2- //to change the digital pin to off while (Serial.available() &gt; 0) { //char inChar = char(int(Serial.read())); char inChar = Serial.read(); Serial.println(inChar); if (isDigit(inChar)) { inString += inChar; Serial.println(inString); } else { pinNumber = inString.toInt(); Serial.println(pinNumber); pinMode(pinNumber, OUTPUT); if (inChar == -85) { Serial.println("set high"); digitalWrite(pinNumber, HIGH); } else if (inChar == -83) { Serial.println("set low"); digitalWrite(pinNumber, LOW); } else { Serial.println("NO MATCH!!!"); } inString = ""; } } </code></pre> <p>}</p>
0
2016-08-15T07:00:03Z
38,955,216
<p>You're assuming that if there is data, it will be the full data. If there is buffering in how the serial port is handled on the transmitting part, you will get only partial data.</p> <p>You can try and add a <code>ser.flush()</code> in your python code, but you should also check that the data you received is complete. You can do that by making sure that your data terminates with a known character and checking that.</p> <p>Keep in mind that you should also have a timeout of some sort, so that you don't get stuck in some reading loop.</p> <p>Another problem is that you're reading a <code>char</code> type, but <code>Serial.read()</code> actually return an <code>int</code>, according to <a href="https://www.arduino.cc/en/Serial/Read" rel="nofollow">the documentation</a>. The <code>char</code> data type has a size of 1 byte, while <code>int</code> has a size of 2 bytes, so that's probably why you're getting weird stuff (there's a reference <a href="http://playground.arduino.cc/Code/DatatypePractices" rel="nofollow">here</a>).</p> <p>It also says that <code>read</code> will return only the first byte of the data. So, if you want the second byte, you need to read twice.</p>
1
2016-08-15T12:36:39Z
[ "python", "arduino", "pyserial" ]
Have to use sleep with pyserial when opening com port for arduino nano
38,950,613
<p>I'm running pyserial (3.1.1) on Windows 10 with python 2.7</p> <p>Update - get the same issue running on Xubuntu 16 as well as Windows.</p> <p>I'm writing via serial to an arduino nano via usb / serial interface.</p> <p>I'm writing a simple character string (eg. '2+') and reading the output in the arduino. If I keep the first time.sleep at 2 seconds after opening the com port it works. If I change it to 1 or remove it the arduino seems to receive a different character / encoding and it does not work.</p> <p>Ideally I don't want any sleep so that it works quicker. Am I doing something wrong or is there a better way to do this so that I can remove the sleep or at least reduce it?</p> <p>Python Code:</p> <pre><code>import sys, getopt import time import serial ser = serial.Serial( port='COM3', baudrate=9600, parity=serial.PARITY_ODD, stopbits=serial.STOPBITS_TWO, bytesize=serial.SEVENBITS ) time.sleep(1) #change this to 2 and it works ser.write('2+') out = '' time.sleep(1) while ser.inWaiting() &gt; 0: out += ser.read(1) if out != '': print "&gt;&gt;" + out else: print "&gt;&gt; nothing!" time.sleep(1) ser.close() </code></pre> <p>Arduino code (I'm having some minor issues with the ASCII char numbers as well - I think it is the signing of the bytes but that is the least of my problems at the moment)</p> <pre><code>String inString = ""; int pinNumber = 0; void setup() { // initialize serial communication at 9600 bits per second: Serial.begin(9600); } void loop() { // expected input: 1+ //to change the digital pin to on // expected input: 2- //to change the digital pin to off while (Serial.available() &gt; 0) { //char inChar = char(int(Serial.read())); char inChar = Serial.read(); Serial.println(inChar); if (isDigit(inChar)) { inString += inChar; Serial.println(inString); } else { pinNumber = inString.toInt(); Serial.println(pinNumber); pinMode(pinNumber, OUTPUT); if (inChar == -85) { Serial.println("set high"); digitalWrite(pinNumber, HIGH); } else if (inChar == -83) { Serial.println("set low"); digitalWrite(pinNumber, LOW); } else { Serial.println("NO MATCH!!!"); } inString = ""; } } </code></pre> <p>}</p>
0
2016-08-15T07:00:03Z
39,000,160
<p>I was not able to find any way around this sleep issue. The bytes were only received correctly on the arduino if at least 1.5 seconds was allowed - presumably for the serial connection to initialise.</p> <p>As a workaround I had to open the serial port once on startup and then accept and write data through a socket server. This worked as expected. It seems the issue is with the opening of the serial port.</p> <pre><code>import os, os.path import time import serial import socket import re def sendData(msg): if not ser.is_open: ser.open() ser.write(msg) ser.flush() out = '' time.sleep(0.5) while ser.inWaiting() &gt; 0: out += ser.read(1) if out != '': print "&gt;&gt;" + out else: print "&gt;&gt; nothing!" time.sleep(0.5) port='/dev/ttyUSB1', serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) serversocket.bind(('localhost', 9000)) serversocket.listen(1) # become a server socket, maximum 5 connections ser = serial.Serial( port=port, baudrate=9600, parity=serial.PARITY_ODD, stopbits=serial.STOPBITS_TWO, bytesize=serial.SEVENBITS ) while True: connection, address = serversocket.accept() buf = connection.recv(64) if len(buf) &gt; 0: print buf sendData(buf) </code></pre>
0
2016-08-17T15:00:30Z
[ "python", "arduino", "pyserial" ]
How to subtract Sunday from datetime range in python
38,950,676
<p>I have a datetime range in python that adds a bunch of dates to a range, but i can't for the life of me figure out how to subtract Sundays from that list. I know how to count business days and weekends separately, but how do i eliminate JUST Sundays? Here is my formula:</p> <pre><code>days = 100 i = 1 daterange= [] while i &lt; days: yesterday = datetime.now() - timedelta(days=i) daterange.append(yesterday.strftime('%m%d%y')) i +=1 print(daterange) </code></pre> <p>Any help on this stubborn issue is appreciated :) Thanks</p>
0
2016-08-15T07:07:19Z
38,950,753
<p>Use <code>datetime.weekday()</code> to exclude Sundays.</p> <pre><code>from datetime import datetime, timedelta days = 100 daterange = [] for i in range(1, 100): yesterday = datetime.now() - timedelta(days=i) if yesterday.weekday() != 6: daterange.append(yesterday.strftime('%m%d%y')) print(*daterange, sep='\n') </code></pre> <p>Also, I'd rather use a <code>for</code> loop instead of a <code>while</code> loop here.</p>
2
2016-08-15T07:13:34Z
[ "python", "datetime" ]
Send data through get method to a TemplateView in Django
38,950,713
<p>I am using <code>openpyxl</code> to download querysets into .xlsx files, and for that I need to use a TemplateView. I am calling the TemplateView by using JQuery-Ajax, I send a single variable that I need to use as a parameter in my queryset, but I don't know how to use the value of that variable in the TemplateView. </p> <p>By default <code>openpyxl</code> overrides <code>GET</code> method, using this:</p> <pre><code>def get(self, request, *args, **kwargs): </code></pre> <p>And I have tried to get the variable by this code:</p> <pre><code> context = self.get_context_data() valor=context["number"] </code></pre> <p>With that code I'm getting this error:</p> <pre><code>500: KeyError at /the_url/ 'numbers' </code></pre> <p>In the error show this:</p> <pre><code>Request URL: http://127.0.0.1:8000/the_url/?number=34 Request information: GET: number = '34' POST: No POST data FILES: No FILES data </code></pre> <p>Where number is the name of the <code>GET</code> variable that I'm sending trough Ajax.</p> <p>So, how can I get the <code>GET</code> variable value in a TemplateView?</p>
0
2016-08-15T07:11:04Z
38,950,946
<p>You should be able to access your variable via <code>self.request.GET.get('number')</code> in the <code>get_context_data</code> method.</p> <p>Example of template view (Python3 version)</p> <pre><code>class MyTemplateView(TemplateView): template_name = 'path/to/tempplate.html' def get_context_data(self, **kwargs): valor = self.request.GET.get('number') return super().get_context_data(**kwargs) </code></pre>
0
2016-08-15T07:28:48Z
[ "python", "ajax", "django" ]
Carriage return doesnt work properly when redirecting output to file python
38,950,877
<p>I have this simple code in which each iteration is overwriting the output of previous line:</p> <pre><code>import time for i in reversed(range (12)): print i, '\r', time.sleep(0.2) </code></pre> <p>when I run the script using the command: <code>python test.py</code> I see the output is replacing itself each iteration as expected. However when I redirect the output to a file using the command: </p> <pre><code>python test.py &gt;&gt; tmp.txt </code></pre> <p>I get a file containing all 12 numbers in 12 separate lines.</p> <p>How can I achieve the same final result in output file as if I ran the script from command line?</p> <p>I use python 2.6.5 on windows 10.</p>
0
2016-08-15T07:22:45Z
38,950,994
<p>You cannot do that because redirection appends data to the end of the file.</p> <p>What's written is written.</p> <p>Edit: BUT there are workarounds.</p> <p><H2>number one: change your python code</H2></p> <pre><code>import time,sys interactive = sys.stdout.isatty() for i in reversed(range (12)): if i==0 or interactive: print i, '\r', time.sleep(0.2) </code></pre> <p>When redirected to a file, it will only print <code>0</code>. If ran without redirection, it will perform like before.</p> <p><H2>number two: add a filter</H2></p> <p>If you're running Linux or Windows with MSYS installed, just pipe the output to a command like <code>cat</code></p> <pre><code>python test.py | cat &gt;&gt; tmp.txt </code></pre> <p>only <code>0</code> will be echoed to the file</p>
1
2016-08-15T07:31:54Z
[ "python", "command-line" ]
Carriage return doesnt work properly when redirecting output to file python
38,950,877
<p>I have this simple code in which each iteration is overwriting the output of previous line:</p> <pre><code>import time for i in reversed(range (12)): print i, '\r', time.sleep(0.2) </code></pre> <p>when I run the script using the command: <code>python test.py</code> I see the output is replacing itself each iteration as expected. However when I redirect the output to a file using the command: </p> <pre><code>python test.py &gt;&gt; tmp.txt </code></pre> <p>I get a file containing all 12 numbers in 12 separate lines.</p> <p>How can I achieve the same final result in output file as if I ran the script from command line?</p> <p>I use python 2.6.5 on windows 10.</p>
0
2016-08-15T07:22:45Z
38,952,824
<p>When you run your script from the command line, the terminal interprets the <code>\r</code> character and moves the cursor to the beginning of the line. The actual bytes in the output from your Python script is the same. You can use <code>cat tmp.txt</code> to "replay" the file through the terminal, to achieve much the same effect as when running the script interactively; but it appears that what you <em>really</em> want cannot be done so simply.</p> <p>To rewrite the bytes you have already written to the output file, close and reopen it, or <code>seek()</code> back to the beginning before the next write.</p> <p>Needless to say, if you currently don't have a file, just a file handle (like standard output), the required changes to your program are rather invasive.</p>
1
2016-08-15T09:47:35Z
[ "python", "command-line" ]
How to implement Swift's or Objective-C's mutable pointers in Python?
38,950,942
<p>The following function requires a "mutable pointer". How do I represent that in Python?</p> <p>Swift:</p> <pre><code>func CGPDFDocumentGetVersion( _ document: CGPDFDocument?, _ majorVersion: UnsafeMutablePointer&lt;Int32&gt;, _ minorVersion: UnsafeMutablePointer&lt;Int32&gt; ) </code></pre> <p>Objective-C:</p> <pre><code>void CGPDFDocumentGetVersion ( CGPDFDocumentRef document, int *majorVersion, int *minorVersion ); </code></pre> <p>Seems a bit mad that the function returns values in this way, nonetheless.</p> <p>I've tried just supplying variables, already assigned to empty values, but I get a segmentation fault. If the variables are undefined, I get:</p> <pre class="lang-none prettyprint-override"><code>NameError: name 'x' is not defined </code></pre> <p>Here's some code that causes a Sgmentation fault. It's very easy to get these if CoreGraphics doesn't like the input.</p> <pre><code>file = "/path/to/file.pdf" pdf = CGPDFDocumentCreateWithProvider(CGDataProviderCreateWithFilename(file)) x = None y = None version = CGPDFDocumentGetVersion(pdf, x, y) </code></pre>
0
2016-08-15T07:28:32Z
38,953,765
<p>You don't need mutable pointers at all. There are two common uses for pointers to <code>int</code> (or similar storage) in C-like code, and Python provides better ways to do both.</p> <h2>Case 1: Multiple return values</h2> <p>A C-like function can't return more than one value without defining a new <code>struct</code> and allocating memory for it. That's tedious enough the job is often foisted off onto the calling function, which provides pointers to the storage <em>it</em> has allocated in advance.</p> <p>In Python, you'd just return an object... in your case, a <code>tuple</code> or <a href="https://docs.python.org/3/library/collections.html#collections.namedtuple" rel="nofollow"><code>namedtuple</code></a>:</p> <pre><code>import collections Version = collections.namedtuple( 'Version', ('major', 'minor'), ) class PDFDocument: def __init__(self, ...): # Figure out major and minor version numbers, then... self.version = Version(major, minor) pdf_doc = PDFDocument(...) major, minor = pdf_doc.version ... </code></pre> <h2>Case 2: Announcing Errors</h2> <p>A C-like function that needs to signal that an error has occurred will typically return some "illegal" value. If there <em>is</em> no such value it can use, an alternative is to take a pointer to some storage the caller owns, where it will scribble its exit status on its way out.</p> <p>In Python, you'd just <code>raise</code> an exception, which is better in almost every way.</p>
1
2016-08-15T10:56:51Z
[ "python", "pointers" ]
Anyone successfully bundled data files into a single file with Pyinstaller?
38,951,047
<p>I have been combing Stack Overflow and the rest of the web on how to add data files into my python application:</p> <pre><code>import Tkinter class simpleapp_tk(Tkinter.Tk): def __init__(self,parent): Tkinter.Tk.__init__(self,parent) self.parent = parent self.initialize() def initialize(self): self.grid() --- Everything Fine Here --- self.B = Tkinter.Button(self, text = 'Create Document', command = self.OnButtonClick) self.B.grid(column = 0, row = 6) def OnButtonClick(self): createDoc() if __name__ == "__main__": app = simpleapp_tk(None) app.title('Receipt Form') app.iconbitmap(os.getcwd() + '/M.ico') app.mainloop() </code></pre> <p>I have tried using the .spec file with no luck</p> <p>Onedir works fine, however when I try to compile into a single executable, it gives an error that the file 'M.ico' isn't defined.</p> <p>If anyone was able to bundle data files with pyinstaller into a single file. Please help. Thanks. </p> <p>I am on a Windows 10 computer running Python 2.7 with PyInstaller 3.2</p>
2
2016-08-15T07:35:22Z
38,965,385
<p>You must specify every data file you want added in your pyinstaller .spec file, or via the command line options (.spec is much easier.) Below is my .spec file,with a "datas" section: </p> <pre><code># -*- mode: python -*- block_cipher = None a = Analysis(['pubdata.py'], pathex=['.', '/interface','/recommender'], binaries=None, datas=[('WordNet/*.txt','WordNet'), ('WordNet/*.json','WordNet'), ('WordNet/pdf_parsing/*.json','pdf_parsing'), ('WordNet/pdf_parsing/*.xml','pdf_parsing'), ('images/*.png','images'), ('database/all_meta/Flybase/*.txt','all_meta'), ('database/all_meta/Uniprot/*.txt','all_meta'), ('database/json_files/*.json','json_files'), ('Data.db','.')], hiddenimports=['interface','recommender'], hookspath=[], runtime_hooks=[], excludes=[], win_no_prefer_redirects=False, win_private_assemblies=False, cipher=block_cipher) pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher) exe = EXE(pyz, a.scripts, exclude_binaries=True, name='GUI', debug=False, strip=False, upx=True, console=True ) coll = COLLECT(exe, a.binaries, a.zipfiles, a.datas, strip=False, upx=True, name='GUI') app = BUNDLE(coll, name='App.app', icon=None) </code></pre> <p>After this, if you are trying to access any data file you specified in the .spec file, in your code, you must use Pyinstaller's _MEIPASS folder to reference your file. Here is how i did so with the file named Data.db: </p> <pre><code>import sys import os.path if hasattr(sys, "_MEIPASS"): datadir = os.path.join(sys._MEIPASS, 'Data.db') else: datadir = 'Data.db' conn = lite.connect(datadir) </code></pre> <p>This method above replaced this statement that was on its own:</p> <pre><code>conn = lite.connect("Data.db") </code></pre> <p>This link helped me a lot when i was going through the same thing: <a href="https://irwinkwan.com/2013/04/29/python-executables-pyinstaller-and-a-48-hour-game-design-compo/" rel="nofollow">https://irwinkwan.com/2013/04/29/python-executables-pyinstaller-and-a-48-hour-game-design-compo/</a></p> <p>Hope this helps! </p>
0
2016-08-16T01:32:23Z
[ "python", "windows", "python-2.7", "pyinstaller" ]
Custom Django aggregation for implementing distance method for the MySQL backend
38,951,049
<p>` Hello, everyone! I need to make a distance method for MySQL backend. I found a solution:</p> <pre><code>class DistanceSQL(Aggregate): sql_function = '' sql_template = "(6371 * acos(cos(radians(%(x)s)) * cos(radians(x(core_location.point))) * " \ "cos(radians(y(core_location.point)) - radians(%(y)s)) + sin( radians(%(x)s) ) * " \ "sin(radians(x(core_location.point)))))" def __init__(self, expression, **extra): super(DistanceSQL, self).__init__(expression, output_field=models.FloatField(), **extra) class MySQLDistance(models.Aggregate): name = 'MySQLDistance' def add_to_query(self, query, alias, col, source, is_summary): aggregate = DistanceSQL(col, source=source, is_summary=is_summary, **self.extra) query.aggregates[alias] = aggregate </code></pre> <p>And now I can use following code for calculating distance:</p> <pre><code>Location.objects.annotate(distance=MySQLDistance('pk', x=self.point.x, y=self.point.y)).order_by('distance')[:3] </code></pre> <p>But I got an error when tried to filter by distance:</p> <pre><code>Location.objects.annotate(distance=MySQLDistance('pk', x=self.point.x, y=self.point.y)).filter(distance__lt=5).order_by('distance')[:3] (1054, "Unknown column 'core_location.point' in 'having clause'") </code></pre> <p>As I investigated, Django makes query like this:</p> <pre><code>SELECT 'table'.'field'... (6371 * acos(cos(radians(36.379559)) *... AS 'distance' FROM 'table' WHERE 'table'.'kind' = 2 ORDER BY 'table'.'id' HAVING (6371 * acos(cos(radians(36.379559)) *... &lt; 5 ORDER BY `distance` ASC LIMIT 3 </code></pre> <p>I don't understand why Django puts <code>sql_template</code> again for the instruction <code>.filter(distance__lt=5)</code> instead a variable <code>distance</code>. And why I got an error above if that column exists.</p> <p>Please, help me, guys!</p>
0
2016-08-15T07:35:30Z
38,951,508
<p>You are basically writing a lot of code to reproduce a tested bit of django that does all this in one line</p> <p><a href="https://docs.djangoproject.com/en/1.10/ref/contrib/gis/geoquerysets/#within" rel="nofollow">within</a></p> <blockquote> <p>Availability: PostGIS, Oracle, MySQL, SpatiaLite, PGRaster (Bilateral)</p> <p>Tests if the geometry field is spatially within the lookup geometry.</p> <p>Example: Zipcode.objects.filter(poly__within=geom)</p> </blockquote> <p>In fact geodjango has a whole family of <a href="https://docs.djangoproject.com/en/1.10/ref/contrib/gis/geoquerysets/#distance-lookups" rel="nofollow">distance lookup function</a>. They are mapped to geospatial functions in your database and will be much faster than any home brewed efforts.</p>
0
2016-08-15T08:11:23Z
[ "python", "mysql", "django", "annotations", "aggregation" ]
Add items to the standard QWebView context menu
38,951,177
<p>The implementation of QWebView has a standard context menu. I want to change it and create my own - or add "Open in new tab" to the standard context menu, and then connect it to my application. How to do it?</p>
0
2016-08-15T07:44:53Z
38,955,525
<p>You can reimplement <code>QWebView.contextMenuEvent</code>:</p> <pre><code>class WebView(QtWebKit.QWebView): def __init__(self, parent=None): super(WebView, self).__init__(parent) self.newTabAction = QtGui.QAction('Open in new tab', self) self.newTabAction.triggered.connect(self.createNewTab) def createNewTab(self): url = self.newTabAction.data() print('create new tab:', url.toString()) def contextMenuEvent(self, event): menu = self.page().createStandardContextMenu() hit = self.page().currentFrame().hitTestContent(event.pos()) url = hit.linkUrl() if url.isValid(): self.newTabAction.setData(url) menu.addAction(self.newTabAction) menu.exec_(event.globalPos()) </code></pre> <p>If you don't want to use the standard context menu, just use <code>QtGui.QMenu()</code> to create your own.</p>
1
2016-08-15T12:56:03Z
[ "python", "qt4", "pyqt4", "contextmenu", "qwebview" ]
Numpy sum of values between arrays of indices with a wraparound condition
38,951,193
<p>Given a large numpy array of floats and 2 arrays of indices I'm looking for an elegant way to sum all the values contained between the given indices by following the following rules:</p> <ul> <li>when index1 > index0, summation happens in a straight forward fashion</li> <li>when index1 &lt; index0, summation "wraparounds" the values.</li> </ul> <p>so for example:</p> <pre><code>import numpy as np # Straight forward summation when index1 &gt; index0 values = np.array([0.,10.,20.,30.,40.,50.,60.,70.]) index0 = np.array([0,3]) index1 = np.array([2,6]) # Desired Result: np.array([30,180]) # (0+10+20),(30+40+50+60) # Wrap around condition when index1 &lt; index0 index0 = np.array([5]) index1 = np.array([1]) # Result: np.array([190]) # (50+60+70+0+10) </code></pre> <p>Because i'm dealing with rather large arrays, i'm looking for an elegant numpy-centric solution if possible.</p>
1
2016-08-15T07:46:03Z
38,951,435
<p>What about that:</p> <pre><code># store all cumulative sums (adding 0 at the start for the empty sum) cs = np.insert(np.cumsum(values), 0, 0) # then for each indexing get the result in constant time (linear in index0/1 size): result = np.where(index0 &lt; index1, 0, cs[-1]) + cs[index1+1]-cs[index0] </code></pre>
2
2016-08-15T08:06:12Z
[ "python", "arrays", "numpy" ]
How do I upgrade Stripe for TLS 1.2
38,951,194
<p>I am using the Stripe module for python (via <code>pip install stripe</code>), and I get the following error:</p> <pre><code>AuthenticationError: Request req_90h0QUDIec0Ej7: Stripe no longer supports API requests made with TLS 1.0. Please initiate HTTPS connections with TLS 1.2 or later. You can learn more about this at https://stripe.com/blog/upgrading-tls. </code></pre> <p>Following Stripe's docs, they say you should re-install Python (via <code>brew</code>) and upgrade to the latest version of the Stripe library (1.37.0 as of this writing). I've done both of these steps, but it doesn't make a difference. </p> <p>What else am I supposed to do? </p>
1
2016-08-15T07:46:15Z
39,033,241
<p>You can try this You can check the TLS verison running on your server at <a href="https://www.ssllabs.com/ssltest/" rel="nofollow">https://www.ssllabs.com/ssltest/</a></p> <p>if your result displays TLS version 1.2 as NO then you have to update it as per the server you are running. </p>
0
2016-08-19T07:19:40Z
[ "python", "stripe-payments", "tls1.2" ]
Serving number of requests using python HTTPServer
38,951,263
<p>I would like to serve only limited amount of requests using python HTTPServer.</p> <p>Here are a few things about my architecture: I have a client which goes to the server and asks for data. The server (pythonic HTTPServer) has a a list containing data. Each time the client asks for data it gets the next item in the list. I would like the server to stop whenever it has sent all the data in its list. The solution i've thought about is checking the number of data in list and serving only this number of times. I must note that there is only one client as I do it for testing purposes.</p> <p>How do I implement it? I thought about raising an event when all the commands are sent so some thread will kill the server but maybe you have an easier way.</p> <p>Thanks in advance</p>
0
2016-08-15T07:52:39Z
38,953,699
<p>So you may want to refer this <a href="https://docs.python.org/2/library/basehttpserver.html#more-examples" rel="nofollow">https://docs.python.org/2/library/basehttpserver.html#more-examples</a> You have to define your own <code>keep_running()</code> condition. Below is my sample:</p> <pre><code>import BaseHTTPServer httpd = BaseHTTPServer.HTTPServer(('', 8000), BaseHTTPServer.BaseHTTPRequestHandler) mylist = range(10) while mylist: httpd.handle_request() mylist.pop() # remove last item of `mylist` </code></pre> <p>When you run this code, it will listen on port <code>8000</code>. Each request you make to <code>localhost:8000</code> will remove an item from <code>mylist</code>. When <code>mylist</code> is empty, this server will be terminated.</p>
0
2016-08-15T10:52:15Z
[ "python", "httpserver" ]
How does Python interpreter allocate memory for different methods?
38,951,319
<p>Can anyone tell me how does Python interpreter or PVM manage memories for the following code?</p> <pre><code>class A(object): class_purpose = "template" def __init__(self): self.a = 0.0 self.b = 0.0 def getParams(self): return self.a, self.b @classmethod def getPurpose(cls): return cls.class_purpose @staticmethod def printout(): print "This is class A" </code></pre> <p>When I save this class and run some codes related to this class, how does PVM or Python interpreter store class variables, class/static functions and instance variables? I used to be a C++ programmer. I wonder where those "things" are stored (I know Python only uses Heap)? When are they stored, RunTime or before RunTime?</p> <p>For example, I run this code after initing this class:</p> <pre><code>a = A() a.getParams() A.getPurpose() A.printout() </code></pre> <p>How does Python interpreter allocate memory behind this code? </p>
1
2016-08-15T07:57:16Z
38,951,398
<p>Everything in your example is simply an object. All objects go on the heap. </p> <p>The class object is created at runtime and has a mapping from attribute name to objects, where all names you defined in the class body are simply attributes. The majority of those objects implement the <a href="https://docs.python.org/2/howto/descriptor.html" rel="nofollow">descriptor protocol</a> (the exception being the <code>class_purpose</code> attribute). The function objects that form the majority of the attributes are also created at runtime; all the compiler produces are code objects which store bytecode, some constants (anything immutable created by the code, including more code objects for nested scopes).</p> <p>See the <a href="https://docs.python.org/2/reference/datamodel.html" rel="nofollow"><em>datamodel</em> reference documentation</a> for more details on how these objects relate to one another.</p> <p>The vast majority of Python developers don't have to worry about memory management. If you develop against the <a href="https://docs.python.org/2/c-api/" rel="nofollow">Python C API</a>, you may want to read up on the <a href="https://docs.python.org/2/c-api/memory.html" rel="nofollow"><em>Memory Management</em> section</a>, which does state:</p> <blockquote> <p>It is important to understand that the management of the Python heap is performed by the interpreter itself and that the user has no control over it, even if she regularly manipulates object pointers to memory blocks inside that heap. The allocation of heap space for Python objects and other internal buffers is performed on demand by the Python memory manager through the Python/C API functions listed in this document.</p> </blockquote>
4
2016-08-15T08:03:24Z
[ "python", "python-2.7", "python-internals" ]
How to get rid of multilevel index after using pivot table pandas?
38,951,345
<p>I had following data frame (the real data frame is much more larger than this one ) :</p> <pre><code>sale_user_id sale_product_id count 1 1 1 1 8 1 1 52 1 1 312 5 1 315 1 </code></pre> <p>Then reshaped it to move the values in sale_product_id as column headers using the following code:</p> <pre><code>reshaped_df=id_product_count.pivot(index='sale_user_id',columns='sale_product_id',values='count') </code></pre> <p>and the resulting data frame is:</p> <pre><code>sale_product_id -1057 1 2 3 4 5 6 8 9 10 ... 98 980 981 982 983 984 985 986 987 99 sale_user_id 1 NaN 1.0 NaN NaN NaN NaN NaN 1.0 NaN NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN 3 NaN 1.0 NaN NaN NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN 4 NaN NaN 1.0 NaN NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN </code></pre> <p>as you can see we have a multililevel index , what i need is to have sale_user_is in the first column without multilevel indexing:</p> <p>i take the following approach : </p> <pre><code>reshaped_df.reset_index() </code></pre> <p>the the result would be like this i still have the sale_product_id column , but i do not need it anymore:</p> <pre><code>sale_product_id sale_user_id -1057 1 2 3 4 5 6 8 9 ... 98 980 981 982 983 984 985 986 987 99 0 1 NaN 1.0 NaN NaN NaN NaN NaN 1.0 NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN 1 3 NaN 1.0 NaN NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN 2 4 NaN NaN 1.0 NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN </code></pre> <p>i can subset this data frame to get rid of sale_product_id but i don't think it would be efficient.I am looking for an efficient way to get rid of multilevel indexing while reshaping the original data frame</p>
1
2016-08-15T07:59:27Z
38,951,373
<p>You need remove only <code>index name</code>, use <a href="http://pandas.pydata.org/pandas-docs/stable/whatsnew.html#changes-to-rename" rel="nofollow"><code>rename_axis</code></a> (new in <code>pandas</code> <code>0.18.0</code>):</p> <pre><code>print (reshaped_df) sale_product_id 1 8 52 312 315 sale_user_id 1 1 1 1 5 1 print (reshaped_df.index.name) sale_user_id print (reshaped_df.rename_axis(None)) sale_product_id 1 8 52 312 315 1 1 1 1 5 1 </code></pre> <p>Another solution working in pandas below <code>0.18.0</code>:</p> <pre><code>reshaped_df.index.name = None print (reshaped_df) sale_product_id 1 8 52 312 315 1 1 1 1 5 1 </code></pre> <hr> <p>If need remove <code>columns name</code> also:</p> <pre><code>print (reshaped_df.columns.name) sale_product_id print (reshaped_df.rename_axis(None).rename_axis(None, axis=1)) 1 8 52 312 315 1 1 1 1 5 1 </code></pre> <p>Another solution:</p> <pre><code>reshaped_df.columns.name = None reshaped_df.index.name = None print (reshaped_df) 1 8 52 312 315 1 1 1 1 5 1 </code></pre> <p>EDIT by comment:</p> <p>You need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html" rel="nofollow"><code>reset_index</code></a> with parameter <code>drop=True</code>:</p> <pre><code>reshaped_df = reshaped_df.reset_index(drop=True) print (reshaped_df) sale_product_id 1 8 52 312 315 0 1 1 1 5 1 #if need reset index nad remove column name reshaped_df = reshaped_df.reset_index(drop=True).rename_axis(None, axis=1) print (reshaped_df) 1 8 52 312 315 0 1 1 1 5 1 </code></pre> <p>Of if need remove only column name:</p> <pre><code>reshaped_df = reshaped_df.rename_axis(None, axis=1) print (reshaped_df) 1 8 52 312 315 sale_user_id 1 1 1 1 5 1 </code></pre> <p>Edit1:</p> <p>So if need create new column from <code>index</code> and remove <code>columns names</code>:</p> <pre><code>reshaped_df = reshaped_df.rename_axis(None, axis=1).reset_index() print (reshaped_df) sale_user_id 1 8 52 312 315 0 1 1 1 1 5 1 </code></pre>
2
2016-08-15T08:01:26Z
[ "python", "pandas", "dataframe", "pivot-table", "data-analysis" ]
Baudline : $\tt stdin$ is very slow
38,951,377
<p>I built a radar system with two radars each with I/Q channels. I wrote a nice python script to read in the data from the serial port. The data is interleaved like so:</p> <pre><code>2.4,2.5,2.3,2.7, 2.2,2.1,2.9,3.1, ... </code></pre> <p>The python code is:</p> <pre><code>import serial import binascii import struct #import sys ser = serial.Serial('/dev/tty.usbserial-FTT86COK', 9600, bytesize=8, timeout=None) data_in=ser.read(1) for x in range(0, 50000): while (data_in!=b'\x2A'): data_in = ser.read(1) data_in = ser.read(80); d = struct.unpack('&lt;HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH', data_in) i=0 for i in range(0,10): j=i*4 print str((d[j]/4096.0*5.0)) + ',' print str((d[j+1]-4096)/4096.0*5.0) + ',' print str(d[j+2]/4096.0*5.0) + ',' print str((d[j+3]-4096)/4096.0*5.0) + ',' </code></pre> <p>I then pipe this data to a tool called <a href="http://www.baudline.com" rel="nofollow">baudline</a>. </p> <pre><code>python sensor_in.py | /Applications/baudline.app/Contents/Resources/baudline -reset -samplerate 96000 -channels 4 -quadrature -stdin </code></pre> <p>For some reason the baudline tool updates very slowly and I can't see the signal in "real time". It might be my sample rate but I have played around with this number and I get the same result. I don't know how to get my sample rate, but I don't think this is the problem or main problem. </p> <p>I also tried writing to a file and reading in from baud line but same result. </p> <p>Any help would be great.</p>
0
2016-08-15T06:03:11Z
38,955,107
<p>what is "very slow"?</p> <blockquote> <p>ser = serial.Serial('/dev/tty.usbserial-FTT86COK', 9600, bytesize=8, timeout=None)</p> </blockquote> <p>Remember, your input baud rate is 9600, so you're only getting 9600 bytes per second. </p> <p>You seem to use a complex short integer format, i.e. your sample has 4 bytes.</p> <p>So you get a 9600/4 = 2400 complex samples per second at most, through your serial interface.</p> <p>But: for some reason, you seem to skip half of your samples (what about <code>j+2</code> and <code>j+3</code>? Also, <code>i=0</code> is not necessary; that's not how Python <code>for</code> loops or <code>range</code> work):</p> <pre><code>for i in range(0,10): j=i*4 print str((d[j]/4096.0*5.0)) + ',' print str((d[j+1]-4096)/4096.0*5.0) + ',' </code></pre> <p>So that leaves you with 1200 complex samples per second leaving your script <em>at most</em>.</p> <pre><code>baudline -reset -samplerate 96000 -channels 2 -quadrature -stdin </code></pre> <p>There's quite some things wrong with this:</p> <ul> <li><code>-samplerate</code> obviously can't reflect what comes in through your serial line</li> <li><code>-channels 2</code> implies that these 1200 samples per second belong to two different channels, so that's 600 S/s per channel. </li> </ul> <p>I don't know which FFT size you're using, but let's go with the (for radar purposes) rather conservative value of 1024; this means you get one transform worth of data roughly every 1.6 s.</p> <p>So, I don't think there's anything wrong with baudline; you might not have thought your script through, mathematically.</p> <p>Also: Radar with a 600 Hz bandwidth? Are you sure? What does your radar theory say about the range resolution of a radar system of that bandwidth? (Hint: in my head, a monostatic chirp radar with that bandwidth would have a best-case resolution of 250 thousand kilometers; so, your resolution would be significantly worse than the earth's circumference)</p>
1
2016-08-15T12:28:40Z
[ "python" ]
Baudline : $\tt stdin$ is very slow
38,951,377
<p>I built a radar system with two radars each with I/Q channels. I wrote a nice python script to read in the data from the serial port. The data is interleaved like so:</p> <pre><code>2.4,2.5,2.3,2.7, 2.2,2.1,2.9,3.1, ... </code></pre> <p>The python code is:</p> <pre><code>import serial import binascii import struct #import sys ser = serial.Serial('/dev/tty.usbserial-FTT86COK', 9600, bytesize=8, timeout=None) data_in=ser.read(1) for x in range(0, 50000): while (data_in!=b'\x2A'): data_in = ser.read(1) data_in = ser.read(80); d = struct.unpack('&lt;HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH', data_in) i=0 for i in range(0,10): j=i*4 print str((d[j]/4096.0*5.0)) + ',' print str((d[j+1]-4096)/4096.0*5.0) + ',' print str(d[j+2]/4096.0*5.0) + ',' print str((d[j+3]-4096)/4096.0*5.0) + ',' </code></pre> <p>I then pipe this data to a tool called <a href="http://www.baudline.com" rel="nofollow">baudline</a>. </p> <pre><code>python sensor_in.py | /Applications/baudline.app/Contents/Resources/baudline -reset -samplerate 96000 -channels 4 -quadrature -stdin </code></pre> <p>For some reason the baudline tool updates very slowly and I can't see the signal in "real time". It might be my sample rate but I have played around with this number and I get the same result. I don't know how to get my sample rate, but I don't think this is the problem or main problem. </p> <p>I also tried writing to a file and reading in from baud line but same result. </p> <p>Any help would be great.</p>
0
2016-08-15T06:03:11Z
38,957,848
<p>Add <code>sys.stdout.flush()</code> as the last line in your for loop, like so:</p> <pre><code> import sys ... for i in range(0,10): j=i*4 print str((d[j]/4096.0*5.0)) + ',' print str((d[j+1]-4096)/4096.0*5.0) + ',' print str(d[j+2]/4096.0*5.0) + ',' print str((d[j+3]-4096)/4096.0*5.0) + ',' sys.stdout.flush() </code></pre>
0
2016-08-15T15:12:05Z
[ "python" ]
Reading a numpy saved file to a list
38,951,460
<p>from an earlier numpy process I save a list which contains an array. Like this,</p> <pre><code>np.savetxt('CHARS.out', chars, delimiter=',', fmt="%s") </code></pre> <p>And when I try to read the file to a list for a later use using this code,</p> <pre><code>chars = open('chars.out', 'r') chars = np.loadtxt(chars, delimiter=',') </code></pre> <p>I get the following error,</p> <blockquote> <p>ValueError: could not convert string to float: b'L'</p> </blockquote> <p>Also using the following way to read it to list works but the output is not as expected</p> <pre><code>chars = open('chars.out', 'r') chars = chars.readlines() </code></pre> <p>The output of the following is like this,</p> <pre><code>['L\n', '3\n', 'b\n', 'p\n',...... </code></pre> <p>It has the new line character appended to the end of each character. How can I read the numpy savetxt file to a list or array in python?</p> <p>Thank</p>
0
2016-08-15T08:08:23Z
38,951,589
<p>You could strip the newline characters:</p> <p>For Python 2.x:</p> <pre><code>strippedChars = map(lambda string: string.strip(), chars) </code></pre> <p>For Python 3.x</p> <pre><code>strippedChars = list(map(lambda string: string.strip(), chars)) </code></pre> <p>Example with your code:</p> <pre><code>np.savetxt('CHARS.out', chars, delimiter=',', fmt="%s") chars = open('chars.out', 'r') chars = chars.readlines() strippedChars = list(map(lambda string: string.strip(), chars)) </code></pre>
1
2016-08-15T08:16:51Z
[ "python", "numpy" ]
Reading a numpy saved file to a list
38,951,460
<p>from an earlier numpy process I save a list which contains an array. Like this,</p> <pre><code>np.savetxt('CHARS.out', chars, delimiter=',', fmt="%s") </code></pre> <p>And when I try to read the file to a list for a later use using this code,</p> <pre><code>chars = open('chars.out', 'r') chars = np.loadtxt(chars, delimiter=',') </code></pre> <p>I get the following error,</p> <blockquote> <p>ValueError: could not convert string to float: b'L'</p> </blockquote> <p>Also using the following way to read it to list works but the output is not as expected</p> <pre><code>chars = open('chars.out', 'r') chars = chars.readlines() </code></pre> <p>The output of the following is like this,</p> <pre><code>['L\n', '3\n', 'b\n', 'p\n',...... </code></pre> <p>It has the new line character appended to the end of each character. How can I read the numpy savetxt file to a list or array in python?</p> <p>Thank</p>
0
2016-08-15T08:08:23Z
38,951,979
<p>If you just want to avoid the <code>\n</code> you can use <a class='doc-link' href="http://stackoverflow.com/documentation/python/5265/list-comprehensions#t=201608150846186286074">list comprehension</a> together with <a class='doc-link' href="http://stackoverflow.com/documentation/python/1494/list-slicing-selecting-parts-of-lists#t=201608150847158520459">string slicing</a>:</p> <pre><code>chars = [line[:-1] for line in open('chars.out', 'r')] </code></pre>
0
2016-08-15T08:45:38Z
[ "python", "numpy" ]
Reading a numpy saved file to a list
38,951,460
<p>from an earlier numpy process I save a list which contains an array. Like this,</p> <pre><code>np.savetxt('CHARS.out', chars, delimiter=',', fmt="%s") </code></pre> <p>And when I try to read the file to a list for a later use using this code,</p> <pre><code>chars = open('chars.out', 'r') chars = np.loadtxt(chars, delimiter=',') </code></pre> <p>I get the following error,</p> <blockquote> <p>ValueError: could not convert string to float: b'L'</p> </blockquote> <p>Also using the following way to read it to list works but the output is not as expected</p> <pre><code>chars = open('chars.out', 'r') chars = chars.readlines() </code></pre> <p>The output of the following is like this,</p> <pre><code>['L\n', '3\n', 'b\n', 'p\n',...... </code></pre> <p>It has the new line character appended to the end of each character. How can I read the numpy savetxt file to a list or array in python?</p> <p>Thank</p>
0
2016-08-15T08:08:23Z
38,952,108
<p>First, <code>savetxt</code> saves an array. If you pass a list that contains an array it effectively saves only the array.</p> <p>Second, to read the array back you don't need to open a file but rather supply the file name to <code>genfromtxt</code>, like so:</p> <pre><code>chars = np.genfromtxt('chars.out', delimiter=',') </code></pre> <p>This puts the array in <code>chars</code>, and if you want an array inside a list, simply do <code>[chars]</code>.</p> <p><strong>EDIT</strong></p> <p>If you need to read the array as an array of strings, and also each string ends with a newline, which we can consider as a delimiter, then you read the array:</p> <pre><code>chars = np.genfromtxt('chars.out', delimiter='\n', dtype=str) </code></pre>
1
2016-08-15T08:55:37Z
[ "python", "numpy" ]
Results Change On Repeated Applications Of PyCluster's K-Medoids
38,951,482
<pre><code>import Pycluster as PC matrix=([ 0. , 1.47, 2.43, 3.44, 1.08], [ 1.47, 0. , 1.5 , 2.39, 2.11], [ 2.43, 1.5 , 0. , 1.22, 2.69], [ 3.44, 2.39, 1.22, 0. , 3.45], [ 1.08, 2.11, 2.69, 3.45, 0.]) cluster,medoids,error=PC.kmedoids(matrix,3) print(cluster) </code></pre> <p>i apply kmedoids on my distance matrix. when i print the cluster label of my data, it show a combination number within a list 25 times. Sometimes is 2,25,26. Sometimes is 2,64,66. For example: (Assume this is the statistic of one of the output)</p> <pre><code>2: 10 items 25:10 items 26:5 items </code></pre> <p>So, i wonder why the label number and number of item keep changing every time i run my program.</p>
-1
2016-08-15T08:09:23Z
38,962,617
<p>K-medoids is a randomized algorithm, so you get different results every time.</p> <p>The cluster number is probably the index of the medoid. Did you look at the source code of pycluster?</p>
0
2016-08-15T20:34:21Z
[ "python", "cluster-analysis" ]
reStructuredText link in Python
38,951,484
<p>If I have the following function in Python:</p> <pre><code>def _add_parameter(self, a): # do something </code></pre> <p>And I want to add a docstring to link to the above function using reStructuredText, I just need to add an underscore at the end of the function name like the following:</p> <pre><code>""" The _add_parameter_ adds parameters. """ </code></pre> <p>But instead of linking it to the function, I get a <code>cannot find declaration to go to</code> warning. How do I fix this?</p>
1
2016-08-15T08:09:32Z
38,958,291
<p>The autodoc extension only documents non private members, i.e. members where the name does not start with an underscore. From the documentation:</p> <pre><code>.. autoclass:: Noodle :members: will document all non-private member functions and properties (that is, those whose name doesn’t start with _). </code></pre> <p>So, when autodoc tries to find the place to link to, it doesn't find it.</p> <p>To override not documenting private members you can use <code>:private-members:</code>, but I cannot tell from experience if that works.However, it is generally preferred to only document the public interface.</p>
0
2016-08-15T15:41:16Z
[ "python", "python-2.7", "python-3.x", "restructuredtext", "docstring" ]
django rest return result that combines filters
38,951,498
<p>I'm new to Django rest and i'm trying to return response that have to use two query sets: The first one is for the specific project and the second one is only for specific users inside this project:</p> <p>serializers.py</p> <pre><code>class ProjectFiltersSerializer(serializers.ModelSerializer): class Meta: model= Project fields = ('id', 'title','users') </code></pre> <p>views.py</p> <pre><code>class FiltersDetail(APIView): """ Retrieve filters instance. """ def get_project(self, project_pk): try: return models.Project.objects.filter(pk=project_pk) except Snippet.DoesNotExist: raise Http404 def get_returning_customers(self, project_pk): return [(u.pk, u"%s %s" % (u.first_name, u.last_name)) for u in User.objects.filter(return=1)] def get(self, request, project_pk, format=None): snippet = self.get_project(project_pk) | self.get_returning_customers(project_pk) serializer = ProjectFiltersSerializer(snippet, many=True) return Response(serializer.data) </code></pre> <p>I'm getting "Cannot combine queries on two different base models". Is this the right way to do this?</p> <p>Thanks</p>
0
2016-08-15T08:10:34Z
38,952,392
<p>You can use Nested Serializer. For more information: <a href="http://www.django-rest-framework.org/api-guide/relations/#nested-relationships" rel="nofollow">http://www.django-rest-framework.org/api-guide/relations/#nested-relationships</a></p>
1
2016-08-15T09:17:10Z
[ "python", "django", "django-models", "django-views", "django-rest-framework" ]
django rest return result that combines filters
38,951,498
<p>I'm new to Django rest and i'm trying to return response that have to use two query sets: The first one is for the specific project and the second one is only for specific users inside this project:</p> <p>serializers.py</p> <pre><code>class ProjectFiltersSerializer(serializers.ModelSerializer): class Meta: model= Project fields = ('id', 'title','users') </code></pre> <p>views.py</p> <pre><code>class FiltersDetail(APIView): """ Retrieve filters instance. """ def get_project(self, project_pk): try: return models.Project.objects.filter(pk=project_pk) except Snippet.DoesNotExist: raise Http404 def get_returning_customers(self, project_pk): return [(u.pk, u"%s %s" % (u.first_name, u.last_name)) for u in User.objects.filter(return=1)] def get(self, request, project_pk, format=None): snippet = self.get_project(project_pk) | self.get_returning_customers(project_pk) serializer = ProjectFiltersSerializer(snippet, many=True) return Response(serializer.data) </code></pre> <p>I'm getting "Cannot combine queries on two different base models". Is this the right way to do this?</p> <p>Thanks</p>
0
2016-08-15T08:10:34Z
38,978,252
<p>create a nested serializer (notice it's not a Model Serializer)</p> <pre><code>class ProjectCustomerSerializer(serializers.Serializer): users = UserSerializer(many=True) project = ProjectSerializer() </code></pre> <p>the UserSerializer and ProjectSerializer can be ModelSerializers however. Then in the view:</p> <pre><code>def get(....): serializer = ProjectCustomerSerializer(data={ 'users': self.get_returning_customers(project_pk), 'project': self.get_project(project_pk), }) return Response(serializer.data) </code></pre> <p>there's another way. You could add a method on the project model (get_returning_customers()) and then add a field on the ProjectSerializer called <code>returning_customers = serializer.ListField(source='get_returning_customers')</code> </p> <p>Hope this helps</p>
0
2016-08-16T14:58:15Z
[ "python", "django", "django-models", "django-views", "django-rest-framework" ]
Search CSV for matching field and use initial date
38,951,638
<p>I am attempting to search a CSV file for rows with duplicate device names. The output should record the date from the 1st matching row and also record the date from the last row found. I need some assistance with the logic of removing duplicate device names from the CSV file, whilst also keeping a record of when a device was first and last seen.</p> <pre><code>import time as epoch # AlertTime, DeviceName, Status Input = [['14/08/2016 13:00', 'device-A', 'UP'], ['14/08/2016 13:15', 'device-B', 'DOWN'], ['15/08/2016 17:30', 'device-A', 'UP']] # FirstSeen, LastSeen, DeviceName, Status Output = [] # Last 48 hours now = epoch.time() cutoff = now - (172800) for i in Input: AlertTime = epoch.mktime(epoch.strptime(i[0], '%d/%m/%Y %H:%M')) if AlertTime &gt; cutoff: Result = [i[0], i[0], i[1], i[2]] Output.append(Result) print(Output) </code></pre> <p>Output (3 entries):</p> <pre><code>[['14/08/2016 13:00', '14/08/2016 13:00', 'device-A', 'UP'], ['14/08/2016 13:15', '14/08/2016 13:15', 'device-B', 'DOWN'], ['15/08/2016 17:30', '15/08/2016 17:30', 'device-A', 'UP']] </code></pre> <p>Wanted Output (2 entries):</p> <pre><code>[['14/08/2016 13:15', '14/08/2016 13:15', 'device-B', 'DOWN'], ['14/08/2016 13:00', '15/08/2016 17:30', 'device-A', 'UP']] </code></pre>
1
2016-08-15T08:20:39Z
38,952,084
<p>As Vedang Mehta said in the comments, you could use a dict to store the data.</p> <pre><code> my_dict = {} for i in Input: AlertTime = epoch.mktime(epoch.strptime(i[0], '%d/%m/%Y %H:%M')) if AlertTime &gt; cutoff: #if we have seen this device before, update it if i[1] in my_dict: my_dict[i[1]] = (my_dict[i[1]][0], i[0], i[2]) #if we haven't seen it, add it else: my_dict[i[1]] = (i[0],i[0],i[2]) </code></pre> <p>After this, all your devices will be stored in <code>my_dict</code> containing (<code>first_seen</code>, <code>last_seen</code> and <code>status</code>).</p>
1
2016-08-15T08:53:32Z
[ "python", "csv", "duplicates" ]
Search CSV for matching field and use initial date
38,951,638
<p>I am attempting to search a CSV file for rows with duplicate device names. The output should record the date from the 1st matching row and also record the date from the last row found. I need some assistance with the logic of removing duplicate device names from the CSV file, whilst also keeping a record of when a device was first and last seen.</p> <pre><code>import time as epoch # AlertTime, DeviceName, Status Input = [['14/08/2016 13:00', 'device-A', 'UP'], ['14/08/2016 13:15', 'device-B', 'DOWN'], ['15/08/2016 17:30', 'device-A', 'UP']] # FirstSeen, LastSeen, DeviceName, Status Output = [] # Last 48 hours now = epoch.time() cutoff = now - (172800) for i in Input: AlertTime = epoch.mktime(epoch.strptime(i[0], '%d/%m/%Y %H:%M')) if AlertTime &gt; cutoff: Result = [i[0], i[0], i[1], i[2]] Output.append(Result) print(Output) </code></pre> <p>Output (3 entries):</p> <pre><code>[['14/08/2016 13:00', '14/08/2016 13:00', 'device-A', 'UP'], ['14/08/2016 13:15', '14/08/2016 13:15', 'device-B', 'DOWN'], ['15/08/2016 17:30', '15/08/2016 17:30', 'device-A', 'UP']] </code></pre> <p>Wanted Output (2 entries):</p> <pre><code>[['14/08/2016 13:15', '14/08/2016 13:15', 'device-B', 'DOWN'], ['14/08/2016 13:00', '15/08/2016 17:30', 'device-A', 'UP']] </code></pre>
1
2016-08-15T08:20:39Z
38,953,681
<p>You can use an <code>OrderedDict</code> to preserve the order that devices are seen in the CSV file. A dictionary is used to automatically remove duplicates. </p> <p>The following works by attempting to update an existing dictionary entry, if it not already present, Python generates a <code>KeyError</code> exception. In this case a new entry can be added with an identical start and end alert time. When updating an entry, the existing <code>first_seen</code> is used to update the entry with the latest found <code>alert_time</code> and <code>status</code>. At the end, the dictionary is parsed to create your required output format:</p> <pre><code>from collections import OrderedDict # AlertTime, DeviceName, Status input_data = [['14/08/2016 13:00', 'device-A', 'UP'], ['14/08/2016 13:15', 'device-B', 'DOWN'], ['15/08/2016 17:30', 'device-A', 'UP']] entries = OrderedDict() for alert_time, device_name, status in input_data: try: entries[device_name] = [entries[device_name][0], alert_time, status] except KeyError as e: entries[device_name] = [alert_time, alert_time, status] # Convert the dictionary of entries into the required format output_data = [[device_name, first_seen, last_seen, status] for device_name, [first_seen, last_seen, status] in entries.items()] print(output_data) </code></pre> <p>Giving you output as:</p> <pre><code>[['device-A', '14/08/2016 13:00', '15/08/2016 17:30', 'UP'], ['device-B', '14/08/2016 13:15', '14/08/2016 13:15', 'DOWN']] </code></pre>
1
2016-08-15T10:50:19Z
[ "python", "csv", "duplicates" ]
How can python drive selenium to use browser find something in the page(ctrl + F) or hightlight keywords
38,951,717
<p>Now my task is getting some WebPage screen shot . I use python &amp; selenium to achieve it. ShootScreen is finished, but the question is how to highlight keyword, in order to make shootScreen clear. </p> <p>One of my idea is using browser itself function of finding in the page(<kbd>ctrl</kbd> + <kbd>F</kbd>), which can highlight keyword automatically. So who can help me?</p>
0
2016-08-15T08:27:18Z
38,952,025
<p>An expansion of my comment, a sample Python code:</p> <pre><code>from selenium import webdriver broswer = webdriver.Chrome(executable_path='path/to/chromedriver') broswer.get('www.example.com') element = broswer.find_element_by_xpath(r'path/to/required/element') # Or any other selection method available in selenium broswer.execute_script("arguments[0].setAttribute('style', arguments[1]);", element, "color: Red;") </code></pre> <p>This will change the color of the selected element to red. You can use the appropriate CSS to highlight the element instead according to your needs (you may want to use <code>"background-color: yellow"</code>).</p>
0
2016-08-15T08:49:19Z
[ "python", "selenium", "browser", "highlight" ]
python send email global name 'msg' is not defined
38,951,891
<p>I have a code snippet to send an email in Python. I am getting the error NameError: global name 'msg' is not defined:</p> <pre><code> Traceback (most recent call last): File "E:/test_runners 2 edit project in progress add more tests/selenium_regression_test_5_1_1/Email/email_selenium_report.py", line 32, in &lt;module&gt; report.send_report_summary_from_htmltestrunner_selenium_report() File "E:\test_runners 2 edit project in progress add more tests\selenium_regression_test_5_1_1\Email\report.py", line 516, in send_report_summary_from_htmltestrunner_selenium_report msg['Subject'] = "ClearCore 5_1_1 Automated GUI Test" NameError: global name 'msg' is not defined </code></pre> <p>My code is:</p> <pre><code>def send_report_summary_from_htmltestrunner_selenium_report(): print extract_only_header_from_summary_from_report_htmltestrunner() print extract_header_count__from_summary_from_report_htmltestrunner() all_testcases = list(extract_testcases_from_report_htmltestrunner()) # print all_data pprint.pprint(all_testcases) msg['Subject'] = "ClearCore 5_1_1 Automated GUI Test" msg['body'] = "\n ClearCore 5_1_1 Automated GUI Test_IE11_Selenium_VM \n " + extract_only_header_from_summary_from_report_htmltestrunner() + "\n extract_header_count__from_summary_from_report_htmltestrunner() \n" + list( extract_testcases_from_report_htmltestrunner()) + "\n Report location = : \\storage-1\Testing\Selenium_Test_Report_Results\ClearCore_5_1_1\Selenium VM\IE11 \n" msg['to'] = "cc4_server_dev@company.onmicrosoft.com", "riazladhani@company.com" msg['From'] = "system@company.com" s = smtplib.SMTP() s.connect(host=SMTP_SERVER) s.sendmail(msg['From'], msg['To'], msg['body'], msg.as_string()) s.close() def extract_only_header_from_summary_from_report_htmltestrunner(): filename = (r"E:\test_runners 2 edit project\selenium_regression_test_5_1_1\TestReport\ClearCore501_Automated_GUI_TestReport.html") html_report_part = open(filename,'r') soup = BeautifulSoup(html_report_part, "html.parser") table = soup.select_one("#result_table") #Create list here... results = [] headers = [td.text for td in table.select_one("#header_row").find_all("td")[1:-1]] # print(" ".join(headers)) #Don't forget to append header (if you want) results.append(headers) return results def extract_header_count__from_summary_from_report_htmltestrunner(): filename = (r"E:\test_runners 2 edit project\selenium_regression_test_5_1_1\TestReport\ClearCore501_Automated_GUI_TestReport.html") html_report_part = open(filename,'r') soup = BeautifulSoup(html_report_part, "html.parser") table = soup.select_one("#result_table") #Create list here... results = [] for row in table.select("tr.passClass"): #Store row string in variable and append before printing row_str = " ".join([td.text for td in row.find_all("td")[1:-1]]) results.append(row_str) # print(row_str) return results def extract_testcases_from_report_htmltestrunner(): filename = (r"E:\test_runners 2 edit project\selenium_regression_test_5_1_1\TestReport\ClearCore501_Automated_GUI_TestReport.html") html_report_part = open(filename,'r') soup = BeautifulSoup(html_report_part, "html.parser") for div in soup.select("#result_table tr div.testcase"): yield div.text.strip().encode('utf-8'), div.find_next("a").text.strip().encode('utf-8') </code></pre> <p>How do I solve this error? I tried to put msg = MIMEText(text, "html") above the msg['Subject'] It does not like that.</p> <p>Thanks, Riaz</p>
0
2016-08-15T08:40:00Z
38,952,224
<p>it seems like you haven't declared your variable <code>msg</code> correctly. I assume you declare it somewhere off the code we're seeing here. but make sure you assign some value to it, even None, in this case though it should be <code>MIMEText(content, "html")</code> for example. as explained in this <a href="http://stackoverflow.com/a/11297548/2860157">answer</a>.</p> <p>if that doesn't help please post the new exception you're getting even after you define <code>msg</code></p>
-1
2016-08-15T09:04:54Z
[ "python", "python-2.7" ]
python send email global name 'msg' is not defined
38,951,891
<p>I have a code snippet to send an email in Python. I am getting the error NameError: global name 'msg' is not defined:</p> <pre><code> Traceback (most recent call last): File "E:/test_runners 2 edit project in progress add more tests/selenium_regression_test_5_1_1/Email/email_selenium_report.py", line 32, in &lt;module&gt; report.send_report_summary_from_htmltestrunner_selenium_report() File "E:\test_runners 2 edit project in progress add more tests\selenium_regression_test_5_1_1\Email\report.py", line 516, in send_report_summary_from_htmltestrunner_selenium_report msg['Subject'] = "ClearCore 5_1_1 Automated GUI Test" NameError: global name 'msg' is not defined </code></pre> <p>My code is:</p> <pre><code>def send_report_summary_from_htmltestrunner_selenium_report(): print extract_only_header_from_summary_from_report_htmltestrunner() print extract_header_count__from_summary_from_report_htmltestrunner() all_testcases = list(extract_testcases_from_report_htmltestrunner()) # print all_data pprint.pprint(all_testcases) msg['Subject'] = "ClearCore 5_1_1 Automated GUI Test" msg['body'] = "\n ClearCore 5_1_1 Automated GUI Test_IE11_Selenium_VM \n " + extract_only_header_from_summary_from_report_htmltestrunner() + "\n extract_header_count__from_summary_from_report_htmltestrunner() \n" + list( extract_testcases_from_report_htmltestrunner()) + "\n Report location = : \\storage-1\Testing\Selenium_Test_Report_Results\ClearCore_5_1_1\Selenium VM\IE11 \n" msg['to'] = "cc4_server_dev@company.onmicrosoft.com", "riazladhani@company.com" msg['From'] = "system@company.com" s = smtplib.SMTP() s.connect(host=SMTP_SERVER) s.sendmail(msg['From'], msg['To'], msg['body'], msg.as_string()) s.close() def extract_only_header_from_summary_from_report_htmltestrunner(): filename = (r"E:\test_runners 2 edit project\selenium_regression_test_5_1_1\TestReport\ClearCore501_Automated_GUI_TestReport.html") html_report_part = open(filename,'r') soup = BeautifulSoup(html_report_part, "html.parser") table = soup.select_one("#result_table") #Create list here... results = [] headers = [td.text for td in table.select_one("#header_row").find_all("td")[1:-1]] # print(" ".join(headers)) #Don't forget to append header (if you want) results.append(headers) return results def extract_header_count__from_summary_from_report_htmltestrunner(): filename = (r"E:\test_runners 2 edit project\selenium_regression_test_5_1_1\TestReport\ClearCore501_Automated_GUI_TestReport.html") html_report_part = open(filename,'r') soup = BeautifulSoup(html_report_part, "html.parser") table = soup.select_one("#result_table") #Create list here... results = [] for row in table.select("tr.passClass"): #Store row string in variable and append before printing row_str = " ".join([td.text for td in row.find_all("td")[1:-1]]) results.append(row_str) # print(row_str) return results def extract_testcases_from_report_htmltestrunner(): filename = (r"E:\test_runners 2 edit project\selenium_regression_test_5_1_1\TestReport\ClearCore501_Automated_GUI_TestReport.html") html_report_part = open(filename,'r') soup = BeautifulSoup(html_report_part, "html.parser") for div in soup.select("#result_table tr div.testcase"): yield div.text.strip().encode('utf-8'), div.find_next("a").text.strip().encode('utf-8') </code></pre> <p>How do I solve this error? I tried to put msg = MIMEText(text, "html") above the msg['Subject'] It does not like that.</p> <p>Thanks, Riaz</p>
0
2016-08-15T08:40:00Z
38,952,353
<p>You forgot to declare <code>msg</code> variable inside <code>send_report_summary_from_htmltestrunner_selenium_report</code> function. You can do it e.g. like this:</p> <pre><code>from email.mime.text import MIMEText msg = MIMEText('body of your message') </code></pre>
1
2016-08-15T09:14:33Z
[ "python", "python-2.7" ]
How to make an option 'All' in django filters when filtering data
38,952,015
<p>I am developing a django application in which I can filter ingredients based on recipes. I am using django filters to give my user filtration options. My filtration dropdown works perfectly fine but I want to add an option 'All', upon submitting which all ingredients should be listed regardless of their recipe.</p> <p>Here is my code:</p> <pre><code>#models.py class Recipe(models.Model): user = models.ForeignKey('auth.User') title = models.CharField(max_length=500) description = models.TextField(max_length=500) rules = models.TextField(max_length=500,blank=True) def __str__(self): return self.title class Ingredient(models.Model): user = models.ForeignKey('auth.User') recipe_id = models.ForeignKey(Recipe, on_delete=models.CASCADE) title = models.CharField(max_length=500) instructions = models.CharField(max_length=500) rules = models.TextField(max_length=500,blank=True) primal = models.CharField(default='0',max_length=500,blank=True) def __str__(self): return self.title #forms.py class RecipeFilter(django_filters.FilterSet): class Meta: model = Ingredient fields = ['recipe_id'] #views.py def ingredient_list(request): ingredientfilter = IngredientFilter( queryset=Recipe.objects.filter(user = request.user)) if request.method == 'GET' and 'recipe_id' in request.GET: recipe_id=request.GET['recipe_id']; ingredients = Ingredient.objects.filter(recipe_id= recipe_id) selected_combo_value = Recipe.objects.get(pk=recipe_id) return render(request, 'ingredient_list.html',{'ingredients':ingredients, 'ingredientfilter': ingredientfilter,'selected_combo_value':selected_combo_value }) else: ingredients = Ingredient.objects.filter(user = request.user) return render(request, 'ingredient_list.html',{'ingredients':ingredients, 'ingredientfilter': ingredientfilter }) </code></pre> <p>Any idea how to do it?</p>
1
2016-08-15T08:48:37Z
39,086,095
<p>This is a known <a href="https://github.com/carltongibson/django-filter/issues/261" rel="nofollow">issue</a>. The workaround is to override the choices for the filter.</p> <pre class="lang-py prettyprint-override"><code>class RecipeFilter(django_filters.FilterSet): def __init__(self, *args, **kwargs): super(RecipeFilter, self).__init__(*args, **kwargs) self.filters['recipe_id'].field.choices.insert(0, ('', u'---------')) </code></pre>
0
2016-08-22T18:11:41Z
[ "python", "django", "django-filter" ]
Program doesn't work beyond py2exe
38,952,059
<p>My code is worked well, when I used the raw py file. But when I compiled with py2exe, it will drop an AttributeError:</p> <pre><code>File "test.py", line 1, in &lt;module&gt; import wmi File "&lt;frozen importlib._bootstrap&gt;", line 2237, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 2226, in _find_and_load_unlocked File "&lt;frozen importlib._bootstrap&gt;", line 1191, in _load_unlocked File "&lt;frozen importlib._bootstrap&gt;", line 1161, in _load_backward_compatible File "C:\Python34\lib\site-packages\zipextimporter.py", line 86, in load_module return zipimport.zipimporter.load_module(self, fullname) File "C:\Python34\lib\wmi.py", line 88, in &lt;module&gt; from win32com.client import GetObject, Dispatch File "&lt;frozen importlib._bootstrap&gt;", line 2237, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 2226, in _find_and_load_unlocked File "&lt;frozen importlib._bootstrap&gt;", line 1191, in _load_unlocked File "&lt;frozen importlib._bootstrap&gt;", line 1161, in _load_backward_compatible File "C:\Python34\lib\site-packages\zipextimporter.py", line 86, in load_module return zipimport.zipimporter.load_module(self, fullname) File "C:\Python34\lib\site-packages\win32com\__init__.py", line 6, in &lt;module&gt; import pythoncom File "&lt;frozen importlib._bootstrap&gt;", line 2237, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 2226, in _find_and_load_unlocked File "&lt;frozen importlib._bootstrap&gt;", line 1191, in _load_unlocked File "&lt;frozen importlib._bootstrap&gt;", line 1161, in _load_backward_compatible File "C:\Python34\lib\site-packages\zipextimporter.py", line 86, in load_module return zipimport.zipimporter.load_module(self, fullname) File "C:\Python34\lib\site-packages\pythoncom.py", line 3, in &lt;module&gt; pywintypes.__import_pywin32_system_module__("pythoncom", globals()) AttributeError: 'module' object has no attribute '__import_pywin32_system_module__' </code></pre> <p>When I backported my code to 2.7, It will worked well, but on on winpe10 (Windows Preinstallation Environment, very thin version of win10) drop same error. On winpe 5 (it is thin version of win8.1) work as well.<br/> My example code:</p> <pre><code>import wmi def getWmiData(wmiProperty, wmiClass, wmiNamespace='cimv2'): """Return array of strings.""" wmiValues = [] wmiCursore = wmi.GetObject('winmgmts:\\root\\' + wmiNamespace) wmiQuery = 'SELECT ' + wmiProperty + ' FROM ' + wmiClass for item in wmiCursore.ExecQuery(wmiQuery): wmiValues.append(str(item.__getattr__(wmiProperty))) return wmiValues print(getWmiData('SystemSKU', 'MS_systeminformation', 'wmi')[0]) </code></pre> <p>Basic py2exe settings:</p> <pre><code>from distutils.core import setup import py2exe, sys, os sys.argv.append('py2exe') setup( options = {'py2exe': {'compressed': True},}, console = ['test.py'], ) </code></pre> <p>Tried versions:</p> <ul> <li>python 2.7.11, 2.7.12, 3.4.4</li> <li>py2xe: 0.6.9, 0.9.2.2</li> <li>pywin32: 219, 220</li> <li>wmi: 1.4.9</li> </ul> <p>Summary: <strong>How can I use wmi module with py2exe on the right way?</strong></p>
0
2016-08-15T08:51:14Z
39,052,807
<p>Since I did clearly reinstall python 2.7 (and of course the necessary modules), everything works on my windows 10, however on the winpe 10 still did not!</p> <p>I had to add wmi packages to the winpe image, the previous winpe version contains it by default! Now It works on winpe as well. <br/> (I can't understand it. If I know well, wmi is one of the most used tool on winpe!)</p> <p>With this two lines commands:</p> <pre><code>Dism /Add-Package /Image:"C:\WinPE_amd64\mount" /PackagePath:"C:\Program Files\Windows Kits\8.1\Assessment and Deployment Kit\Windows Preinstallation Environment\amd64\WinPE_OCs\WinPE-WMI.cab" Dism /Add-Package /Image:"C:\WinPE_amd64\mount" /PackagePath:"C:\Program Files\Windows Kits\8.1\Assessment and Deployment Kit\Windows Preinstallation Environment\amd64\WinPE_OCs\en-us\WinPE-WMI_en-us.cab" </code></pre>
0
2016-08-20T09:59:43Z
[ "python", "python-2.7", "wmi", "py2exe", "winpe" ]
Why is scrapy crawling a different facebook page?
38,952,089
<p>This is a scrapy spider.This spider is supposed to collect the names of all div nodes with class attribute=5d-5 essentially making a list of all people with x name from y location.</p> <pre><code>import scrapy from scrapy.selector import Selector from scrapy.http import HtmlResponse class fb_spider(scrapy.Spider): name="fb" allowed_domains = ["facebook.com"] start_urls = [ "https://www.facebook.com/search/people/?q=jaslyn%20california"] def parse(self,response): x=response.xpath('//div[@class="_5d-5"]'.extract()) with open("asdf.txt",'wb') as f: f.write(u"".join(x).encode("UTF-8")) </code></pre> <p>But the scrapy crawls a web page different from the one specified.I got this on the command prompt:</p> <pre><code>2016-08-15 14:00:14 [scrapy] ERROR: Spider error processing &lt;GET https://www.facebook.com/search/top/?q=jaslyn%20california&gt; (referer: None) </code></pre> <p>but the URL I specified is:</p> <pre><code>https://www.facebook.com/search/people/?q=jaslyn%20california </code></pre>
-2
2016-08-15T08:53:56Z
38,952,155
<p>Facebook is redirecting the request to the new url. </p>
0
2016-08-15T08:59:56Z
[ "python", "facebook", "scrapy" ]
Why is scrapy crawling a different facebook page?
38,952,089
<p>This is a scrapy spider.This spider is supposed to collect the names of all div nodes with class attribute=5d-5 essentially making a list of all people with x name from y location.</p> <pre><code>import scrapy from scrapy.selector import Selector from scrapy.http import HtmlResponse class fb_spider(scrapy.Spider): name="fb" allowed_domains = ["facebook.com"] start_urls = [ "https://www.facebook.com/search/people/?q=jaslyn%20california"] def parse(self,response): x=response.xpath('//div[@class="_5d-5"]'.extract()) with open("asdf.txt",'wb') as f: f.write(u"".join(x).encode("UTF-8")) </code></pre> <p>But the scrapy crawls a web page different from the one specified.I got this on the command prompt:</p> <pre><code>2016-08-15 14:00:14 [scrapy] ERROR: Spider error processing &lt;GET https://www.facebook.com/search/top/?q=jaslyn%20california&gt; (referer: None) </code></pre> <p>but the URL I specified is:</p> <pre><code>https://www.facebook.com/search/people/?q=jaslyn%20california </code></pre>
-2
2016-08-15T08:53:56Z
38,952,168
<p>it seems as though you are missing some headers in your request.</p> <pre><code>2016-08-15 14:00:14 [scrapy] ERROR: Spider error processing &lt;GET https://www.facebook.com/search/top/?q=jaslyn%20california&gt; (referer: None) </code></pre> <p>as you can see the referer is None, I would advise you add some headers manually, <a href="http://doc.scrapy.org/en/latest/topics/request-response.html#request-objects" rel="nofollow">namely the referer</a>.</p>
0
2016-08-15T09:00:42Z
[ "python", "facebook", "scrapy" ]
Why is scrapy crawling a different facebook page?
38,952,089
<p>This is a scrapy spider.This spider is supposed to collect the names of all div nodes with class attribute=5d-5 essentially making a list of all people with x name from y location.</p> <pre><code>import scrapy from scrapy.selector import Selector from scrapy.http import HtmlResponse class fb_spider(scrapy.Spider): name="fb" allowed_domains = ["facebook.com"] start_urls = [ "https://www.facebook.com/search/people/?q=jaslyn%20california"] def parse(self,response): x=response.xpath('//div[@class="_5d-5"]'.extract()) with open("asdf.txt",'wb') as f: f.write(u"".join(x).encode("UTF-8")) </code></pre> <p>But the scrapy crawls a web page different from the one specified.I got this on the command prompt:</p> <pre><code>2016-08-15 14:00:14 [scrapy] ERROR: Spider error processing &lt;GET https://www.facebook.com/search/top/?q=jaslyn%20california&gt; (referer: None) </code></pre> <p>but the URL I specified is:</p> <pre><code>https://www.facebook.com/search/people/?q=jaslyn%20california </code></pre>
-2
2016-08-15T08:53:56Z
38,952,587
<p>Scraping is not allowed on Facebook: <a href="https://www.facebook.com/apps/site_scraping_tos_terms.php" rel="nofollow">https://www.facebook.com/apps/site_scraping_tos_terms.php</a></p> <p>If you want to get data from Facebook, you have to use their Graph API. For example, this would be the API to search for users: <a href="https://developers.facebook.com/docs/graph-api/using-graph-api#search" rel="nofollow">https://developers.facebook.com/docs/graph-api/using-graph-api#search</a></p> <p>It is not as powerful as the Graph Search on facebook.com though.</p>
1
2016-08-15T09:30:50Z
[ "python", "facebook", "scrapy" ]
How to trasfer a string to DataFrame
38,952,135
<p>I have a list like the below following:</p> <pre><code>a= [['LSJW26760ES050487,2016-04-29,00:40:1,3'],['LSJW26760ES050487,2016-04-29,00:40:1,2'],['LSJW26760ES050487,2016-04-29,00:45:1,3'],['LSJW26760ES050487,2016-04-29,00:40:1,4'],.....] </code></pre> <p>how can I read it in pandas as DataFrame:</p> <pre><code> type(str) Data(date.time) Time(time.timedelta) flag(int) 0 LSJW26760ES050487,2016-04-29,00:40:1,3 1 LSJW26760ES050487,2016-04-29,00:40:1,2 2 LSJW26760ES050487,2016-04-29,00:45:1,3 4 LSJW26760ES050487,2016-04-29,00:40:1,4 </code></pre>
0
2016-08-15T08:57:44Z
38,952,208
<p><code>pandas.DataFrame()</code> can construct a dataframe from a list of lists. The only preprocessing step you need to do is to convert the string into a list, you can do that using <code>"string".split(",")</code>. Here is a working example: </p> <pre><code>&gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; a= [['LSJW26760ES050487,2016-04-29,00:40:1,3'],['LSJW26760ES050487,2016-04-29,00:40:1,2'],['LSJW26760ES050487,2016-04-29,00:45:1,3'],['LSJW26760ES050487,2016-04-29,00:40:1,4']] &gt;&gt;&gt; &gt;&gt;&gt; &gt;&gt;&gt; a = [i[0].split(",") for i in a] &gt;&gt;&gt; df = pd.DataFrame(a) &gt;&gt;&gt; df.head() 0 1 2 3 0 LSJW26760ES050487 2016-04-29 00:40:1 3 1 LSJW26760ES050487 2016-04-29 00:40:1 2 2 LSJW26760ES050487 2016-04-29 00:45:1 3 3 LSJW26760ES050487 2016-04-29 00:40:1 4 &gt;&gt;&gt; </code></pre> <p>As a final step you can add column names as follows: </p> <pre><code>&gt;&gt;&gt; df.columns = ["type","date", "time", "flag"] &gt;&gt;&gt; df.head() type date time flag 0 LSJW26760ES050487 2016-04-29 00:40:1 3 1 LSJW26760ES050487 2016-04-29 00:40:1 2 2 LSJW26760ES050487 2016-04-29 00:45:1 3 3 LSJW26760ES050487 2016-04-29 00:40:1 4 &gt;&gt;&gt; </code></pre>
0
2016-08-15T09:03:46Z
[ "python", "pandas", "dataframe" ]
How to trasfer a string to DataFrame
38,952,135
<p>I have a list like the below following:</p> <pre><code>a= [['LSJW26760ES050487,2016-04-29,00:40:1,3'],['LSJW26760ES050487,2016-04-29,00:40:1,2'],['LSJW26760ES050487,2016-04-29,00:45:1,3'],['LSJW26760ES050487,2016-04-29,00:40:1,4'],.....] </code></pre> <p>how can I read it in pandas as DataFrame:</p> <pre><code> type(str) Data(date.time) Time(time.timedelta) flag(int) 0 LSJW26760ES050487,2016-04-29,00:40:1,3 1 LSJW26760ES050487,2016-04-29,00:40:1,2 2 LSJW26760ES050487,2016-04-29,00:45:1,3 4 LSJW26760ES050487,2016-04-29,00:40:1,4 </code></pre>
0
2016-08-15T08:57:44Z
38,952,213
<p>You need first <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.split.html" rel="nofollow"><code>str.split</code></a> for spliting by <code>,</code> and then convert columns:</p> <pre><code>import pandas as pd a= [['LSJW26760ES050487,2016-04-29,00:40:1,3'], ['LSJW26760ES050487,2016-04-29,00:40:1,2'], ['LSJW26760ES050487,2016-04-29,00:45:1,3'], ['LSJW26760ES050487,2016-04-29,00:40:1,4']] df = pd.DataFrame(a, columns=['col']) df = df.col.str.split(',', expand=True) df.columns = ['type','data','time','flag'] df['data'] = pd.to_datetime(df.data) df['time'] = pd.to_timedelta(df.time) df['flag'] = df.flag.astype(int) print (df) type data time flag 0 LSJW26760ES050487 2016-04-29 00:40:01 3 1 LSJW26760ES050487 2016-04-29 00:40:01 2 2 LSJW26760ES050487 2016-04-29 00:45:01 3 3 LSJW26760ES050487 2016-04-29 00:40:01 4 print (df.dtypes) type object data datetime64[ns] time timedelta64[ns] flag int32 dtype: object </code></pre> <p>Another solution, if in data are no <code>NaN</code>:</p> <pre><code>import pandas as pd a= [['LSJW26760ES050487,2016-04-29,00:40:1,3'], ['LSJW26760ES050487,2016-04-29,00:40:1,2'], ['LSJW26760ES050487,2016-04-29,00:45:1,3'], ['LSJW26760ES050487,2016-04-29,00:40:1,4']] df = pd.DataFrame([x[0].split(',') for x in a], columns=['type', 'data', 'time', 'flag']) df['data'] = pd.to_datetime(df.data) df['time'] = pd.to_timedelta(df.time) df['flag'] = df.flag.astype(int) print (df) type data time flag 0 LSJW26760ES050487 2016-04-29 00:40:01 3 1 LSJW26760ES050487 2016-04-29 00:40:01 2 2 LSJW26760ES050487 2016-04-29 00:45:01 3 3 LSJW26760ES050487 2016-04-29 00:40:01 4 print (df.dtypes) type object data datetime64[ns] time timedelta64[ns] flag int32 dtype: object </code></pre>
0
2016-08-15T09:04:13Z
[ "python", "pandas", "dataframe" ]
How to trasfer a string to DataFrame
38,952,135
<p>I have a list like the below following:</p> <pre><code>a= [['LSJW26760ES050487,2016-04-29,00:40:1,3'],['LSJW26760ES050487,2016-04-29,00:40:1,2'],['LSJW26760ES050487,2016-04-29,00:45:1,3'],['LSJW26760ES050487,2016-04-29,00:40:1,4'],.....] </code></pre> <p>how can I read it in pandas as DataFrame:</p> <pre><code> type(str) Data(date.time) Time(time.timedelta) flag(int) 0 LSJW26760ES050487,2016-04-29,00:40:1,3 1 LSJW26760ES050487,2016-04-29,00:40:1,2 2 LSJW26760ES050487,2016-04-29,00:45:1,3 4 LSJW26760ES050487,2016-04-29,00:40:1,4 </code></pre>
0
2016-08-15T08:57:44Z
38,952,435
<p>This is a Python 3 code, using <code>np.genfromtxt</code> to create an array using a comma delimiter:</p> <pre><code>import numpy as np import pandas as pd from io import BytesIO a= [['LSJW26760ES050487,2016-04-29,00:40:1,3'],['LSJW26760ES050487,2016-04- 29,00:40:1,2']] data = [np.genfromtxt(BytesIO(item[0].encode()), delimiter=',', dtype=str) for item in a] d = pd.DataFrame(data, columns='type date time flag'.split()) d.date = pd.to_datetime(d.date) d.time = pd.to_timedelta(d.time) d.flag = pd.to_numeric(d.flag) print(d) </code></pre> <p>Output:</p> <pre><code> type date time flag 0 LSJW26760ES050487 2016-04-29 00:40:01 3 1 LSJW26760ES050487 2016-04-29 00:40:01 2 </code></pre>
1
2016-08-15T09:19:42Z
[ "python", "pandas", "dataframe" ]
How to share an instance variable among different classes in Python
38,952,287
<p>Suppose I have a class <code>Game</code> with attributes <code>player1</code>, <code>player2</code>, and <code>Q</code>. <code>player1</code> and <code>player2</code> are themselves instances of the class <code>Player</code> which also has an attribute called <code>Q</code>. I would like to make it such that when I instantiate a <code>Game</code>, it shares its <code>Q</code> with the instances of <code>Player</code> it was instantiated with.</p> <p>To illustrate what I mean, consider this code:</p> <pre><code>class Game: def __init__(self, player1, player2): self.player1 = player1 self.player2 = player2 self.Q = {} class Player: def __init__(self, mark): self.mark = mark self.Q = {} player1 = Player(mark="X") player2 = Player(mark="O") game = Game(player1, player2) # Instantiate a game with player 1 and player 2 game.Q["some key"] = "some value" # I would like this to happen automatically player1.Q = game.Q player2.Q = game.Q </code></pre> <p>I'd like <code>player1</code> and <code>player2</code>'s <code>Q</code> variable to get updated automatically to <code>game.Q</code> whenever it changes. How can I achieve this?</p>
0
2016-08-15T09:10:07Z
38,952,461
<p>You can introduce base class with <code>Q</code> as a class attribute:</p> <pre><code>class Base(object): Q = {} class Player(Base): def __init__(self, mark): self.mark = mark class Game(Base): def __init__(self, player1, player2): self.player1 = player1 self.player2 = player2 player1 = Player(mark="X") player2 = Player(mark="O") game = Game(player1, player2) # Instantiate a game with player 1 and player 2 game.Q["some key"] = "some value" </code></pre> <p>But this works only if you want to have one instance of game with players because if you create next <code>Game</code> it will have same <code>Q</code> as the previous one.</p>
0
2016-08-15T09:21:58Z
[ "python" ]
How to share an instance variable among different classes in Python
38,952,287
<p>Suppose I have a class <code>Game</code> with attributes <code>player1</code>, <code>player2</code>, and <code>Q</code>. <code>player1</code> and <code>player2</code> are themselves instances of the class <code>Player</code> which also has an attribute called <code>Q</code>. I would like to make it such that when I instantiate a <code>Game</code>, it shares its <code>Q</code> with the instances of <code>Player</code> it was instantiated with.</p> <p>To illustrate what I mean, consider this code:</p> <pre><code>class Game: def __init__(self, player1, player2): self.player1 = player1 self.player2 = player2 self.Q = {} class Player: def __init__(self, mark): self.mark = mark self.Q = {} player1 = Player(mark="X") player2 = Player(mark="O") game = Game(player1, player2) # Instantiate a game with player 1 and player 2 game.Q["some key"] = "some value" # I would like this to happen automatically player1.Q = game.Q player2.Q = game.Q </code></pre> <p>I'd like <code>player1</code> and <code>player2</code>'s <code>Q</code> variable to get updated automatically to <code>game.Q</code> whenever it changes. How can I achieve this?</p>
0
2016-08-15T09:10:07Z
38,952,708
<p>Following <a href="http://stackoverflow.com/users/1222951/rawing">Rawing</a>'s comment, I used <code>self.Q = self.player1.Q = self.player2.Q = {}</code> in the <code>__init__</code> of <code>Game</code>:</p> <pre><code>class Game: def __init__(self, player1, player2): self.player1 = player1 self.player2 = player2 self.Q = self.player1.Q = self.player2.Q = {} class Player: def __init__(self, mark): self.mark = mark self.Q = {} player1 = Player(mark="X") player2 = Player(mark="O") game = Game(player1, player2) # Instantiate a game with player 1 and player 2 game.Q["some key"] = "some value" </code></pre> <p>As a result, <code>player1.Q</code> now yields <code>{'some key': 'some value'}</code> without having to 'update' it manually.</p>
0
2016-08-15T09:40:03Z
[ "python" ]
Create zipfile: TypeError: object of type 'ElementTree' has no len()
38,952,412
<p>I'm writing a xml data to the zip.</p> <pre><code>from xml.etree.ElementTree import Element, SubElement, ElementTree from zipfile import ZipFile def create_tree(): root = Element("root") doc = SubElement(root, "doc") SubElement(doc, "field", name="blah").text = "text" return ElementTree(root) def test(): """ Create zip """ with ZipFile("xml.zip", 'w') as ziparc: element_tree = create_tree() ziparc.writestr("file.xml", element_tree) if __name__ == "__main__": test() </code></pre> <p>An error:</p> <pre><code>File "main_test2_2.py", line 168, in test ziparc.writestr('file.xml', element_tree) File "/usr/lib/python2.7/zipfile.py", line 1127, in writestr zinfo.file_size = len(bytes) # Uncompressed size TypeError: object of type 'ElementTree' has no len() </code></pre> <p>Tell me please, how can I write xml data to the archive?</p>
-1
2016-08-15T09:18:26Z
38,952,521
<p>Write the element into a fake file (a buffer)</p> <pre><code>from xml.etree.ElementTree import Element, SubElement, ElementTree from zipfile import ZipFile from io import BytesIO def create_tree(): root = Element("root") doc = SubElement(root, "doc") SubElement(doc, "field", name="blah").text = "text" return ElementTree(root) def test(): """ Create zip """ with ZipFile("xml.zip", 'w') as ziparc: element_tree = create_tree() outbuf = BytesIO() element_tree.write(outbuf) ziparc.writestr("file.xml", outbuf.getvalue()) if __name__ == "__main__": test() </code></pre> <p>Edit: another user tried to suggest <code>tostring</code> method, but it was not complete &amp; not working probably because first the argument has to be an <code>Element</code> not an <code>ElementTree</code> and second because of the imports (<code>ElementTree</code> being a package and a sub-class, there was an ambiguity).</p> <p>However, I reworked the full source and it also works, I think it's even a better solution (cheers to this other user who deleted his post!)</p> <pre><code>from xml.etree.ElementTree import Element, SubElement from zipfile import ZipFile import xml.etree.ElementTree def create_tree(): root = Element("root") doc = SubElement(root, "doc") SubElement(doc, "field", name="blah").text = "text" return root def test(): """ Create zip """ with ZipFile("xml.zip", 'w') as ziparc: element_tree = create_tree() ziparc.writestr("file.xml", xml.etree.ElementTree.tostring(element_tree)) if __name__ == "__main__": test() </code></pre>
1
2016-08-15T09:26:08Z
[ "python", "xml", "elementtree", "zipfile" ]
Paypal Rest API keeps returning malformed json error
38,952,451
<p>I am trying to create payment using <code>paypal</code> Rest API, but I keep getting this error response:</p> <pre><code>{"name":"MALFORMED_REQUEST","message":"The request JSON is not well formed.","information_link":"https://developer.paypal.com/webapps/developer/docs/api/#MALFORMED_REQUEST","debug_id":"262cbdc417df7"} </code></pre> <p>here with my code:</p> <pre><code>payment_url = 'https://api.sandbox.paypal.com/v1/payments/payment' headers = {"Content-Type": "application/json", "Authorization": "Bearer %s" % access_token} data = { "intent": "sale", "redirect_urls": { "return_url": "http://localhost:8080/index.html", "cancel_url": "http://localhost:8080/index.html" }, "payer": { "payment_method": "paypal" }, "transactions": [ { "amount": { "total": "7.47", "currency": "USD" }, "details": { "subtotal": "7.41", "tax": "0.03", "shipping": "0.03" }, "description": "This is the payment transaction description.", "item_list": { "items": [ { "quantity": "1", "name": "item", "price": "7.41", "currency": "USD", "sku": "item" }] } } ] } print headers print data r = requests.post(payment_url, headers=headers, data=data) print 'payment res', r.text </code></pre> <p>And I only get the response like this:</p> <pre><code>{"name":"MALFORMED_REQUEST","message":"The request JSON is not well formed.","information_link":"https://developer.paypal.com/webapps/developer/docs/api/#MALFORMED_REQUEST","debug_id":"262cbdc417df7"} </code></pre> <p>I have seen quite a few questions regarding this kind of error, but none of them have solution yet. :( The json formated post data is obviously valid. Otherwise, requests post method would raise exceptions. And the response is returned from paypal server, but I can't find any information from the link it gave. I have checked Rest API documentation, and I think I made the request exactly as the samples. What did I miss? </p> <p>Any kind advice or solution would be appreciated.</p>
1
2016-08-15T09:21:28Z
38,961,784
<p>Your <em>return_url</em> and <em>cancel_url</em> values need to have quotes around them. As the message says, your JSON is malformed.</p> <p>Try this - <a href="http://jsonlint.com/" rel="nofollow">http://jsonlint.com/</a> to see your errors.</p>
0
2016-08-15T19:33:49Z
[ "python", "api", "rest", "paypal" ]
pycharm project files have disappeared
38,952,539
<p>I was working on a python project in <a href="https://www.jetbrains.com/pycharm/" rel="nofollow">JetBrains PyCharm 2016.2</a> on Lubuntu and all of a sudden, all my project files have disappeared from the IDE.</p> <p>I have tried the following with no success:</p> <ol> <li><p>Exit PyCharm, navigate to project root, delete the .idea file, open PyCharm, create a new project from the current projects source. <strong><em>Result: seems to load fine, but cannot see any project files in either "Project" view or individually load and view any files.</em></strong></p></li> <li><p>Fresh download and run of PyCharm, repeating the above step. <strong><em>Result: Same as option 1.</em></strong></p></li> <li><p>Using <code>File &gt; Open</code> to open the project again. <strong><em>Result: Same as option 1.</em></strong></p></li> </ol> <p>I can do a search by file or class name within PyCharm and the search does find the files. But on selecting one to load from the search results, the search dialogue just closes and the file is not loaded.</p> <p>Also to clarify, I still have the files on disk in the project root physically. But PyCharm is not displaying them in the IDE.</p>
0
2016-08-15T09:27:43Z
38,956,261
<p>Try this: Go to <code>File -&gt; Open recent</code> you should see a list of your recent projects there. If you still don't see it there then just reopen the project by going to <code>File -&gt; Open</code> and go to the location where you saved your project. </p>
1
2016-08-15T13:44:50Z
[ "python", "linux", "ide", "pycharm" ]
pycharm project files have disappeared
38,952,539
<p>I was working on a python project in <a href="https://www.jetbrains.com/pycharm/" rel="nofollow">JetBrains PyCharm 2016.2</a> on Lubuntu and all of a sudden, all my project files have disappeared from the IDE.</p> <p>I have tried the following with no success:</p> <ol> <li><p>Exit PyCharm, navigate to project root, delete the .idea file, open PyCharm, create a new project from the current projects source. <strong><em>Result: seems to load fine, but cannot see any project files in either "Project" view or individually load and view any files.</em></strong></p></li> <li><p>Fresh download and run of PyCharm, repeating the above step. <strong><em>Result: Same as option 1.</em></strong></p></li> <li><p>Using <code>File &gt; Open</code> to open the project again. <strong><em>Result: Same as option 1.</em></strong></p></li> </ol> <p>I can do a search by file or class name within PyCharm and the search does find the files. But on selecting one to load from the search results, the search dialogue just closes and the file is not loaded.</p> <p>Also to clarify, I still have the files on disk in the project root physically. But PyCharm is not displaying them in the IDE.</p>
0
2016-08-15T09:27:43Z
38,969,749
<p>Ok so I have found the issue, which turned out to be indirect in the end. I just installed the latest updates for Lubuntu, restarted the PC, then opened PyCharm and like magic all my project files are now visible!</p> <p>I know it was not just the restart because I had already tried that. So it must have been one or more of the updates. I'm not going to list all the updates here, there were a lot, but this solved my issue anyway.</p>
0
2016-08-16T08:13:14Z
[ "python", "linux", "ide", "pycharm" ]
How to load csv files in a tensorflow program?
38,952,554
<p>I am working on a deep neural network by following the tensorflow tutorial on convolutional neural nets. But the dataset i have is in the form of csv files. I have 4 csv files 2 for training(xtrain.csv and ytrain.csv) and 2 for testing(xtest.csv and ytest.csv). xtrain.csv and xtest.csv contain the inputs with 1280 rows and 4096 columns and 320 rows and 4096 columns respectively. Here each row represents an image of dimension 1x4096. Therefore the input layer will have 4096 neurons. now the ytrain.csv and ytest.csv contain the output with 32 rows and 1280 columns and 32 rows 320 columns respectively where each column represents the output for a particular image in the form of a one hot vector. so there are going to be 32 neurons in the output layer. Can someone please guide me on how to load the csv files for input and output(label) into my program? </p>
0
2016-08-15T09:29:24Z
38,958,349
<p>Tensorflow has a function below that seems like would do it.</p> <pre><code>tf.decode_csv(records, record_defaults, field_delim=None, name=None) </code></pre> <p>You can use this to load your data into a tensor. From there you just need to convert the tensor to the correct shape.</p> <pre><code>imgs = tf.decode_csv(csv_file, tf.float32) imgs = tf.reshape(imgs,shape=(num_of_imgs,64,64)) </code></pre> <p>keep in mind that tf.decode_csv each column will be a tensor. You can do something similar for the labels. </p>
0
2016-08-15T15:45:24Z
[ "python", "csv", "image-processing", "tensorflow", "conv-neural-network" ]
Avoid `logger=logging.getLogger(__name__)` without loosing way to filter logs
38,952,681
<p>I am lazy and want to avoid this line in every python file which uses logging:</p> <pre><code>logger = logging.getLogger(__name__) </code></pre> <p>In january I asked how this could be done, and found an answer: <a href="http://stackoverflow.com/questions/34726515/avoid-logger-logging-getlogger-name">Avoid `logger=logging.getLogger(__name__)`</a></p> <p>Unfortunately the answer there has the drawback, that you loose the ability to filter.</p> <p>I really want to avoid this useless and redundant line.</p> <p>Example:</p> <pre><code>import logging def my_method(foo): logging.info() </code></pre> <p>Unfortunately I think it is impossible do <code>logger = logging.getLogger(__name__)</code> implicitly if <code>logging.info()</code> gets called for the first time in this file.</p> <p>Is there anybody out there who knows how to do impossible stuff?</p> <p><strong>Update</strong></p> <p>I like <a href="https://en.wikipedia.org/wiki/Don&#39;t_repeat_yourself" rel="nofollow">Don't Repeat Yourself</a>. If most files contain the same line at the top, I think this is a repetition. It looks like <a href="https://en.wikipedia.org/wiki/Don&#39;t_repeat_yourself#DRY_vs_WET_solutions" rel="nofollow">WET</a>. The python interpreter in my head needs to skip this line every time I look there. My subjective feeling: this line is useless bloat. The line should be the implicit default. </p>
-3
2016-08-15T09:38:16Z
38,967,311
<p>Think well if you really want to do this.</p> <p>Create a Module e.g. <code>magiclog.py</code> like this:</p> <pre><code>import logging import inspect def L(): # FIXME: catch indexing errors callerframe = inspect.stack()[1][0] name = callerframe.f_globals["__name__"] # avoid cyclic ref, see https://docs.python.org/2/library/inspect.html#the-interpreter-stack del callerframe return logging.getLogger(name) </code></pre> <p>Then you can do:</p> <pre><code>from magiclog import L L().info("it works!") </code></pre>
1
2016-08-16T05:37:54Z
[ "python", "logging" ]
Avoid `logger=logging.getLogger(__name__)` without loosing way to filter logs
38,952,681
<p>I am lazy and want to avoid this line in every python file which uses logging:</p> <pre><code>logger = logging.getLogger(__name__) </code></pre> <p>In january I asked how this could be done, and found an answer: <a href="http://stackoverflow.com/questions/34726515/avoid-logger-logging-getlogger-name">Avoid `logger=logging.getLogger(__name__)`</a></p> <p>Unfortunately the answer there has the drawback, that you loose the ability to filter.</p> <p>I really want to avoid this useless and redundant line.</p> <p>Example:</p> <pre><code>import logging def my_method(foo): logging.info() </code></pre> <p>Unfortunately I think it is impossible do <code>logger = logging.getLogger(__name__)</code> implicitly if <code>logging.info()</code> gets called for the first time in this file.</p> <p>Is there anybody out there who knows how to do impossible stuff?</p> <p><strong>Update</strong></p> <p>I like <a href="https://en.wikipedia.org/wiki/Don&#39;t_repeat_yourself" rel="nofollow">Don't Repeat Yourself</a>. If most files contain the same line at the top, I think this is a repetition. It looks like <a href="https://en.wikipedia.org/wiki/Don&#39;t_repeat_yourself#DRY_vs_WET_solutions" rel="nofollow">WET</a>. The python interpreter in my head needs to skip this line every time I look there. My subjective feeling: this line is useless bloat. The line should be the implicit default. </p>
-3
2016-08-15T09:38:16Z
39,064,783
<blockquote> <p>I am lazy and want to avoid this line in every python file which uses logging:</p> <pre><code>logger = logging.getLogger(__name__) </code></pre> </blockquote> <p>Well, it's the recommended way:</p> <blockquote> <p>A good convention to use when naming loggers is to use a module-level logger, in each module which uses logging, named as follows:</p> <pre><code>logger = logging.getLogger(__name__) </code></pre> <p>This means that logger names track the package/module hierarchy, and it’s intuitively obvious where events are logged just from the logger name.</p> </blockquote> <p>That's a quote from the official <a href="https://docs.python.org/2/howto/logging.html#advanced-logging-tutorial" rel="nofollow">howto</a>.</p> <blockquote> <p>I like Don't Repeat Yourself. If most files contain the same line at the top, I think this is a repetition. It looks like WET. The python interpreter in my head needs to skip this line every time I look there. My subjective feeling: this line is useless bloat. The line should be the implicit default.</p> </blockquote> <p>It follows "Explicit is better than implicit". Anyway you can easily change a python template in many IDEs to always include this line or make a new template file.</p>
1
2016-08-21T13:34:34Z
[ "python", "logging" ]
Python pandas extract, how to extract remaining part of string
38,952,809
<p>I have looked for hours and this should be simple. I am trying to extract all the letters from a string with a mixture or digits and letters. Here is an example:</p> <pre><code>df = pd.Series(['ENGLANDSR11SW']) df = df.to_frame('column') df['ValueAfterExtract'] = df['column'].str.extract("(?P&lt;letter&gt;[a-zA-Z]+)") print(df) </code></pre> <p>From the string value <code>ENGLANDSR11SW</code> in the dataframe, the result is <code>ENGLANDSR</code> but i want to bring even the last letters of the string which is the <code>SW</code> which should result in <code>ENGLANDSRSW</code> , meaning only the digits <code>11</code> would be removed.</p> <p>How can i do this?</p>
0
2016-08-15T09:46:38Z
38,952,846
<p>Replace all digits (<code>\d</code>) with empty strings:</p> <pre><code>In [6]: df['column'].str.replace(r'\d', '') Out[10]: 0 ENGLANDSRSW Name: column, dtype: object </code></pre> <p>Or, to remove everything which is not in <code>[a-zA-Z]</code> use the regexp <code>[^a-zA-Z]</code>. This would remove, for instance, whitespace and punctuation marks as well as digits:</p> <pre><code>In [20]: df['column'].str.replace(r'[^a-zA-Z]', '') Out[20]: 0 ENGLANDSRSW Name: column, dtype: object </code></pre>
3
2016-08-15T09:49:00Z
[ "python", "pandas", "extract" ]
how to convert a 1-dimensional image array to PIL image in Python
38,952,853
<p>My question is related to a <a href="https://www.kaggle.com/c/digit-recognizer/data" rel="nofollow">Kaggle data science competition</a>. I'm trying to read an image from a one-dimensional array containing <strong>1-bit grayscale</strong> pixel information (<strong>0 to 255)</strong> for an <strong>28x28 image</strong>. So the array is from <strong>0 to 783</strong> where each pixel is encoded as x = i * 28 + j.</p> <p>Converted into a two-dimensional 28x28 matrix this:</p> <pre><code>000 001 002 003 ... 026 027 028 029 030 031 ... 054 055 056 057 058 059 ... 082 083 | | | | ... | | 728 729 730 731 ... 754 755 756 757 758 759 ... 782 783 </code></pre> <p>For reasons of image manipulation (resizing, skewing) I would like to read that array into an in-memory PIL image. I did some research on the <a href="http://matplotlib.org/users/image_tutorial.html" rel="nofollow">Matplotlib image function</a>, which I think is most promising. Another idea is the <a href="https://pythonhosted.org/pypng/ex.html#numpy" rel="nofollow">Numpy image functions</a>.</p> <p><strong>What I'm looking for</strong>, is a code example that shows me how to load that 1-dimensional array via Numpy or Matplotlib or anything else. Or how to convert that array into a 2-dimensional image using for instance Numpy.vstack and then read it as an image.</p>
1
2016-08-15T09:49:29Z
38,953,115
<p>You can convert a NumPy array to PIL image using <code>Image.fromarray</code>:</p> <pre><code>import numpy as np from PIL import Image arr = np.random.randint(255, size=(28*28)) img = Image.fromarray(arr.reshape(28,28), 'L') </code></pre> <p><code>L</code> mode indicates the array values represent luminance. The result will be a gray-scale image.</p>
2
2016-08-15T10:07:27Z
[ "python", "image", "numpy", "matplotlib", "python-imaging-library" ]
Python string concatenation and equivalent of bash parameter expansion
38,952,979
<p>I'm kind of new to python, but something I find myself doing in bash a lot is prepending and appending strings to filenames with parameter expansion.</p> <p>e.g.</p> <pre><code>for file in *.txt ; do mkdir ${file%.*} ; mv $file ${file%.*}/ ; done </code></pre> <p>Would be an example for stripping off the extension of a load of files, making directories based on those names, and then moving the files inside their namesake folders now.</p> <p>If I want to achieve a similar thing, such as rename the output of a function based on the input file name (below is an example of a Biopython function), I've seen a few ways to do it with string concatenation etc, but without bracketing and so on, it looks confusing and like it might create parsing errors with spaces, quotes and so on being all over the place potentially.</p> <pre><code>SeqIO.convert(genbank, 'genbank', genbank[:-3]+'tmp', 'fasta') </code></pre> <p>There are other threads on here about using rsplit, string concatenation and so on, but is one of these more 'correct' than another?</p> <p>String concatenation is really nice and works great in simple commands like <code>print()</code>, but when adding to commands that are expecting separated values, it strikes me as a little messy?</p>
0
2016-08-15T09:58:05Z
38,953,177
<p>You can use <code>os.path.splitext</code> which is build especially for file names:</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; &gt;&gt;&gt; fname = '/tmp/foo/bar.baz' &gt;&gt;&gt; sp = os.path.splitext(fname) &gt;&gt;&gt; sp ('/tmp/foo/bar', '.baz') </code></pre> <p>Extracting the name of the file without extension:</p> <pre><code>&gt;&gt;&gt; os.path.basename(sp[0]) 'bar' </code></pre> <p>And formatting a new file name:</p> <pre><code>&gt;&gt;&gt; "{}.txt".format(os.path.basename(sp[0])) 'bar.txt' </code></pre> <p>In general, when manipulating file names and paths I try to just use <code>os.path</code>, since it already handles edge cases, can normalize paths from things like <code>/..//./././</code>, etc.</p>
1
2016-08-15T10:11:20Z
[ "python", "string", "bash", "biopython" ]
Connect to a Bluetooth LE device using bluez python dbus interface
38,953,175
<p>I would like to connect to a Bluetooth LE device and receive notifications from it in python. I would like to use the Bluez dbus API, but can't find an example I can understand. :-)</p> <p>With gatttool, I can use the following command:</p> <p>gatttool -b C4:8D:EE:C8:D2:D8 --char-write-req -a 0x001d -n 0100 –listen</p> <p>How can I do the same in python, using the dbus API of Bluez?</p>
1
2016-08-15T10:11:17Z
38,997,649
<p>See 'test/example-gatt-client' from bluez package</p>
1
2016-08-17T13:11:13Z
[ "python", "dbus", "bluez", "gatt" ]
How to integrate django countries in to an existing model
38,953,242
<p>I have an existing countries class in a database in production but would like to use the Django_Countries model to update all the countries I use.</p> <p>Here is the existing model. It allows users create a country and upload a flag of their country</p> <pre><code>class Country(models.Model): name = models.CharField(_("Name")) icon = models.ImageField(_("Icon"),upload_to=os.path.join('images', 'flags')) </code></pre> <p>I want to remove the option of a user creating a country and just have select a country.</p> <p>I cant really change the existing model as there is a lot of dependencies on it. I just want to add the name and flag to the existing model.</p>
0
2016-08-15T10:17:12Z
38,971,232
<p>Finally ended up just doing a dump of the countries in to a json file and writing a migration to update the database. </p> <pre><code>def forwards(apps, schema_editor): Country = apps.get_model('country', 'Country') Region = apps.get_model('country', 'Region') Region.objects.filter(id=45).delete() with codecs.open(os.path.join(os.path.dirname(__file__), 'countries.json'), encoding='utf-8') as cfile: data = json.load(cfile) for country, regions in data.items(): country, created = Country.objects.get_or_create(name=country) class Migration(migrations.Migration): dependencies = [ ('country', 'previous_migration'), ] operations = [ migrations.RunPython(forwards), ] </code></pre>
0
2016-08-16T09:28:48Z
[ "python", "django", "django-models", "django-countries" ]
Django Filter Objects and Get First Corresponding Values
38,953,245
<p>I have two models.</p> <pre><code>class House(models.Model): name= models.Charfield(max_length=100) city= models.Charfield(max_length=100) area= models.CharField(max_length=200) country=models.CharField(max_length=30) class HouseRooms(models.Model): room_name=models.Charfield(max_length=200) house= models.ForeignKey(House, related_name='house_hr') room_price=models.PositiveIntegerField() </code></pre> <p>When a user run a keyword search, I want to return the name of each 'House' and the first room_price of the corresponding 'HouseRooms'. See my views below.</p> <pre><code>def my_house_search(request): query_string= '' rms= None sms=None if ('q' in request.GET) and request.GET['q'].strip(): query_string = request.GET['q'] entry_query= get_query(query_string, ['city','country',]) rms= House.objects.filter(entry_query).order_by('-pub_date') sms= HouseRooms.objects.filter(house_id__in=rms) return render(request, 'search/my_house_search.html',{'rms':rms, 'sms':sms, 'query_string':query_string}) </code></pre> <p>Template:</p> <pre><code> {% if query_string %} &lt;p&gt; Results &lt;/p&gt; {% if rms %} {% for m in rms %} &lt;p&gt; Name: {{ m.name }} &lt;/p&gt; {% empty %} &lt;p&gt; No house found &lt;/p&gt; {% endfor %} {% for sd in sms %} &lt;p&gt; price: {{ sd.room_price }} for {{sd.room_name}}&lt;/p&gt; {% empty %} &lt;p&gt; no price found &lt;/p&gt; {% endfor %} {% endif %} {% endif %} </code></pre> <p>With the code I wrote, it will return the name of each house and show all prices to all houses like this:</p> <pre><code>Coker House Klopp House $50/day for small room $100/day for medium room $200/day for big room $200/day for quack room $400/day for master room $500/day for big room </code></pre> <p>I just want it to return the result like this.</p> <pre><code>Coker House $50/day for small room Klopp House $200/day for quack room </code></pre> <p>What am I missing? How do I go about this?</p>
0
2016-08-15T10:17:25Z
38,954,126
<p>You shouldn't query HouseRooms explicitly in the view. Instead, you can use the reverse relationship accessor inside your iteration in the template itself.</p> <pre><code>{% for m in rms %} &lt;p&gt; Name: {{ m.name }} &lt;/p&gt; {% with m.house_hr.first as sd %} {% if sd %} &lt;p&gt; price: {{ sd.room_price }} for {{sd.room_name}}&lt;/p&gt; {% else %} &lt;p&gt; no price found &lt;/p&gt; {% endif %} {% endwith %} {% empty %} &lt;p&gt; No house found &lt;/p&gt; {% endfor %} </code></pre>
2
2016-08-15T11:21:36Z
[ "python", "django" ]
Certbot fails to run on CentOS 6 server
38,953,248
<p>I'm having some issues running the <code>certbot-auto</code> application on a CentOS 6 server, which has both Python 2.6 (<code>/usr/bin/python</code>) and 2.7 (<code>/usr/bin/python2.7</code>) installed.</p> <p>A copy of the output from running <code>./certbot-auto</code> with no arguments can be found in this paste: <a href="http://pastebin.com/g7WaZUra" rel="nofollow">http://pastebin.com/g7WaZUra</a></p> <p>The error code output is <em>similiar</em> to <a href="http://stackoverflow.com/questions/38597326/letsencrypt-certbot-error">this question</a> but my issue is almost certainly not memory related as this is a dedicated server with 32GB RAM and just a few low-traffic sites on it.</p>
-1
2016-08-15T10:17:36Z
38,953,568
<p>Managed to solve the issue, the development dependencies for Python 2.7 were missing. Fix by running <code>yum install python27-devel</code>.</p>
0
2016-08-15T10:41:29Z
[ "python", "linux", "centos", "centos6", "lets-encrypt" ]
What’s the equivalent of rsplit() with re.split()?
38,953,278
<p><a href="https://docs.python.org/2/library/stdtypes.html#str.rsplit" rel="nofollow"><code>rsplit()</code></a> starts splitting at the end of the string. How can I start splitting at the end of the string when using <a href="https://docs.python.org/2/library/re.html#re.split" rel="nofollow"><code>re.split()</code></a>?</p> <p>Example:</p> <pre><code>import re splitme = "a!b?c!d" re.split(r"[!\?]", splitme, maxsplit = 1) </code></pre> <p>Returns:</p> <pre><code>a </code></pre> <p>But I want:</p> <pre><code>d </code></pre> <p>While I was writing this question, I realized I could use</p> <pre><code>re.split(r"[!\?]", splitme)[-1] </code></pre> <p>But that doesn’t seem like the most effective way since this splits the entire string, while we could stop after the first match (from the right).</p>
2
2016-08-15T10:19:49Z
38,953,526
<p>There is no need to split if you just want the last one.</p> <pre><code>match = re.search(r'[^!?]*$', splitme) if match: return match.group(0) </code></pre>
0
2016-08-15T10:38:17Z
[ "python", "regex" ]
How do you plot the total summation of harmonics in python
38,953,369
<p>I am using the below manual method so as to plot the summation of harmonics. The below method is working fine.Please refer the image below.When the same thing implemented in for loop,it is not working as desired.The for loop is meant to take care of n number of harmonic values.Could any help me in this?</p> <pre><code>import numpy as np import matplotlib.pyplot as plt # omega =2*pi x=np.linspace(0,2*np.pi,2000) y1=np.sin(1*2*np.pi*x)/1 y2=np.sin(3*2*np.pi*x)/3 y3=np.sin(5*2*np.pi*x)/5 y4=np.sin(7*2*np.pi*x)/7 y5=np.sin(9*2*np.pi*x)/9 Y=y1+y2+y3+y4+y5 plt.plot(x,Y) plt.grid() plt.show() #Implementation in for loop is not working def Harmonic(i): y = [] for n in range(0,i): y=np.sin((2*n+1)*(2*np.pi)*(x))/(2*n+1) y += y plt.plot(x,y) plt.grid() plt.show() </code></pre> <p><a href="http://i.stack.imgur.com/y0pQ4.png" rel="nofollow"><img src="http://i.stack.imgur.com/y0pQ4.png" alt="Harmonics"></a></p>
0
2016-08-15T10:26:25Z
38,953,504
<p>Do you mean something like that?</p> <pre><code>import numpy as np import matplotlib.pyplot as plt x=np.linspace(0,2*np.pi,2000) y = [0 for _ in x] def Harmonic(i): global y global x for n in range(0,i): y += np.sin((2*n+1)*(2*np.pi)*(x))/(2*n+1) Harmonic(5) plt.plot(x,y) plt.grid() plt.show() </code></pre> <p>Or, if you want to have the function the make the plot:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt def Harmonic(i): x=np.linspace(0,2*np.pi,2000) y = [0 for _ in x] for n in range(0,i): y += np.sin((2*n+1)*(2*np.pi)*(x))/(2*n+1) plt.plot(x,y) plt.grid() plt.show() Harmonic(5) </code></pre>
1
2016-08-15T10:36:23Z
[ "python", "numpy", "matplotlib" ]
How do you plot the total summation of harmonics in python
38,953,369
<p>I am using the below manual method so as to plot the summation of harmonics. The below method is working fine.Please refer the image below.When the same thing implemented in for loop,it is not working as desired.The for loop is meant to take care of n number of harmonic values.Could any help me in this?</p> <pre><code>import numpy as np import matplotlib.pyplot as plt # omega =2*pi x=np.linspace(0,2*np.pi,2000) y1=np.sin(1*2*np.pi*x)/1 y2=np.sin(3*2*np.pi*x)/3 y3=np.sin(5*2*np.pi*x)/5 y4=np.sin(7*2*np.pi*x)/7 y5=np.sin(9*2*np.pi*x)/9 Y=y1+y2+y3+y4+y5 plt.plot(x,Y) plt.grid() plt.show() #Implementation in for loop is not working def Harmonic(i): y = [] for n in range(0,i): y=np.sin((2*n+1)*(2*np.pi)*(x))/(2*n+1) y += y plt.plot(x,y) plt.grid() plt.show() </code></pre> <p><a href="http://i.stack.imgur.com/y0pQ4.png" rel="nofollow"><img src="http://i.stack.imgur.com/y0pQ4.png" alt="Harmonics"></a></p>
0
2016-08-15T10:26:25Z
38,953,660
<p>Here's a working example for you with a little bit of refactoring:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt def first_solution(N=2000): w = 2 * np.pi x = np.linspace(0, w, N) y1 = np.sin(1 * w * x) / 1 y2 = np.sin(3 * w * x) / 3 y3 = np.sin(5 * w * x) / 5 y4 = np.sin(7 * w * x) / 7 y5 = np.sin(9 * w * x) / 9 y = y1 + y2 + y3 + y4 + y5 plt.plot(x, y) def second_solution(i, N=2000): w = 2 * np.pi x, y = np.linspace(0, w, N), [] harmonics = [np.sin((n * 2 + 1) * w * x) / (n * 2 + 1) for n in range(i)] plt.plot(x, sum(harmonics)) plt.figure(1) plt.subplot(211) first_solution() plt.grid() plt.subplot(212) second_solution(5) plt.grid() plt.show() </code></pre> <p>I've called first_solution to your working method and second_solution to your buggy one. Hope it helps</p>
2
2016-08-15T10:48:46Z
[ "python", "numpy", "matplotlib" ]
How do you plot the total summation of harmonics in python
38,953,369
<p>I am using the below manual method so as to plot the summation of harmonics. The below method is working fine.Please refer the image below.When the same thing implemented in for loop,it is not working as desired.The for loop is meant to take care of n number of harmonic values.Could any help me in this?</p> <pre><code>import numpy as np import matplotlib.pyplot as plt # omega =2*pi x=np.linspace(0,2*np.pi,2000) y1=np.sin(1*2*np.pi*x)/1 y2=np.sin(3*2*np.pi*x)/3 y3=np.sin(5*2*np.pi*x)/5 y4=np.sin(7*2*np.pi*x)/7 y5=np.sin(9*2*np.pi*x)/9 Y=y1+y2+y3+y4+y5 plt.plot(x,Y) plt.grid() plt.show() #Implementation in for loop is not working def Harmonic(i): y = [] for n in range(0,i): y=np.sin((2*n+1)*(2*np.pi)*(x))/(2*n+1) y += y plt.plot(x,y) plt.grid() plt.show() </code></pre> <p><a href="http://i.stack.imgur.com/y0pQ4.png" rel="nofollow"><img src="http://i.stack.imgur.com/y0pQ4.png" alt="Harmonics"></a></p>
0
2016-08-15T10:26:25Z
38,953,774
<p>If the goal was to see the impact of increasing the number of harmonics in "real time", you should use <code>FuncAnimation</code></p> <pre><code>fig,ax = plt.subplots() x=np.linspace(0,2*np.pi,2000) y=np.zeros((2000,)) l, = ax.plot(x,y) def initPlot(): ax.set_xlim(0,2*np.pi) ax.set_ylim(-1,1) l, = ax.plot(x,y) return l, def Harmonic(i): y=l.get_ydata() y += np.sin((2*i+1)*(2*np.pi)*(x))/(2*i+1) l.set_ydata(y) return l, anim = animation.FuncAnimation(fig, Harmonic, init_func=initPlot, frames=150, interval=100, blit=True) </code></pre>
3
2016-08-15T10:57:29Z
[ "python", "numpy", "matplotlib" ]
Python - self-referencing class (Vector addition using magic operators)
38,953,411
<p>I'm having trouble understanding how the self-reference for this class works in this code:</p> <pre><code>class Vector2D: def __init__(self, x, y): self.x = x self.y = y def __add__(self, other): return Vector2D(self.x + other.x, self.y + other.y) first = Vector2D(5, 7) second = Vector2D(3, 9) result = first + second print(result.x) print(result.y) </code></pre> <p>-- Just to check if I'm understanding how magic methods work, in <code>result = first + second</code>, the argument <code>other</code> refers to <code>second</code> right?</p> <p>--Edit: Thanks, I guess that clears up my confusions regarding <code>other</code>. I still don't get how this line works though: <code>return Vector2D(self.x + other.x, self.y + other.y)</code> i.e. the class <code>Vector2D</code> being referenced inside it</p>
2
2016-08-15T10:29:21Z
38,953,461
<blockquote> <p>the argument <code>other</code> refers to <code>second</code>, right?</p> </blockquote> <p>Correct. You can verify that with a <code>print</code> inside <code>__add__</code>:</p> <pre><code>class Vector2D: def __init__(self, x, y): self.x = x self.y = y def __add__(self, other): print(other.x, other.y) return Vector2D(self.x + other.x, self.y + other.y) first = Vector2D(5, 7) second = Vector2D(3, 9) result = first + second &gt;&gt; 3 9 </code></pre>
1
2016-08-15T10:32:50Z
[ "python", "class", "python-3.x", "magic-methods" ]
Python - self-referencing class (Vector addition using magic operators)
38,953,411
<p>I'm having trouble understanding how the self-reference for this class works in this code:</p> <pre><code>class Vector2D: def __init__(self, x, y): self.x = x self.y = y def __add__(self, other): return Vector2D(self.x + other.x, self.y + other.y) first = Vector2D(5, 7) second = Vector2D(3, 9) result = first + second print(result.x) print(result.y) </code></pre> <p>-- Just to check if I'm understanding how magic methods work, in <code>result = first + second</code>, the argument <code>other</code> refers to <code>second</code> right?</p> <p>--Edit: Thanks, I guess that clears up my confusions regarding <code>other</code>. I still don't get how this line works though: <code>return Vector2D(self.x + other.x, self.y + other.y)</code> i.e. the class <code>Vector2D</code> being referenced inside it</p>
2
2016-08-15T10:29:21Z
38,953,467
<p>Yes, this is equivalent to:</p> <pre><code>result = first.__add__(second) </code></pre> <p>so:</p> <ol> <li><code>self</code> is <code>first</code></li> <li><code>other</code> is <code>second</code></li> <li><code>result</code> is the new <code>Vector2D</code></li> </ol>
3
2016-08-15T10:33:09Z
[ "python", "class", "python-3.x", "magic-methods" ]
Python - self-referencing class (Vector addition using magic operators)
38,953,411
<p>I'm having trouble understanding how the self-reference for this class works in this code:</p> <pre><code>class Vector2D: def __init__(self, x, y): self.x = x self.y = y def __add__(self, other): return Vector2D(self.x + other.x, self.y + other.y) first = Vector2D(5, 7) second = Vector2D(3, 9) result = first + second print(result.x) print(result.y) </code></pre> <p>-- Just to check if I'm understanding how magic methods work, in <code>result = first + second</code>, the argument <code>other</code> refers to <code>second</code> right?</p> <p>--Edit: Thanks, I guess that clears up my confusions regarding <code>other</code>. I still don't get how this line works though: <code>return Vector2D(self.x + other.x, self.y + other.y)</code> i.e. the class <code>Vector2D</code> being referenced inside it</p>
2
2016-08-15T10:29:21Z
38,953,468
<p>Yes, <code>other</code> is the right-hand-side expression result, <code>second</code> in your case.</p> <p>From the <a href="https://docs.python.org/3/reference/datamodel.html#object.__add__" rel="nofollow"><code>object.__add__()</code> documentation</a>:</p> <blockquote> <p>For instance, to evaluate the expression <code>x + y</code>, where <code>x</code> is an instance of a class that has an <code>__add__()</code> method, <code>x.__add__(y)</code> is called.</p> </blockquote> <p>The expression <code>Vector2D(self.x + other.x, self.y + other.y)</code> creates a new instance of the class with new values for <code>x</code> and <code>y</code>, which here are constructed from the sum of the current instance <code>x</code> and <code>y</code> and the same attributes on the right-hand side instance.</p> <p>A new instance is created because the normal semantics of <code>+</code> are to return a new instance, leaving the operands themselves untouched. Compare this to adding up two lists (<code>['foo', 'bar'] + ['bar', 'baz']</code>); there too a new list object is returned.</p>
1
2016-08-15T10:33:10Z
[ "python", "class", "python-3.x", "magic-methods" ]
CSV.Reader importing a list of lists
38,953,527
<p>I am running the following on a csv of UIDs:</p> <pre><code>with open('C:/uid_sample.csv',newline='') as f: reader = csv.reader(f,delimiter=' ') uidlist = list(reader) </code></pre> <p>but the list returned is actually a list of lists:</p> <pre><code>[['27465307'], ['27459855'], ['27451353']...] </code></pre> <p>I'm using this workaround to get individual strings within one list:</p> <pre><code>for r in reader: print(' '.join(r)) </code></pre> <p>i.e.</p> <pre><code>['27465307','27459855','27451353',...] </code></pre> <p>Am I missing something where I can't do this automatically with the csv.reader or is there an issue with the formatting of my csv perhaps?</p>
0
2016-08-15T10:38:17Z
38,957,305
<p>A CSV file is a file where each line, or row, contains columns that are usually delimited by commas. In your case, you told <code>csv.reader()</code> that your columns are delimited by a space. Since there aren't any spaces in any of the lines, each row of the <code>csv.reader</code> object has only one item. The problem here is that you aren't looking for a row with a single column; you are looking for a single item.</p> <p>Really, you just want a list of the lines in the file. You could use <code>f.readlines()</code>, but that would include the newline character in each line. That actually isn't a problem if all you need to do with each line is convert it to an integer, but you might want to remove those characters. That can be done quite easily with a list comprehension:</p> <pre><code>newlist = [line.strip() for line in f] </code></pre> <p>If you are merely iterating through the lines (with a<code>for</code> loop, for example), you probably don't need a list. If you don't mind the newline characters, you can iterate through the file object directly:</p> <pre><code>for line in f: uid = int(line) print(uid) </code></pre> <p>If the newline characters need to go, you could either take them out per line:</p> <pre><code>for line in f: line = line.strip() ... </code></pre> <p>or create a generator object:</p> <pre><code>uids = (line.strip() for line in f) </code></pre> <p>Note that reading a file is like reading a book: you can't read it again until you turn back to the first page, so remember to use <code>f.seek(0)</code> if you want to read the file more than once.</p>
1
2016-08-15T14:42:16Z
[ "python", "list", "csv" ]
Why does value_counts not show all values present?
38,953,532
<p>I am using pandas 0.18.1 on a large dataframe. I am confused by the behaviour of <code>value_counts()</code>. This is my code:</p> <pre><code>print df.phase.value_counts() def normalise_phase(x): print x return int(str(x).split('/')[0]) df['phase_normalised'] = df['phase'].apply(normalise_phase) </code></pre> <p>This prints the following:</p> <pre><code>2 35092 3 26248 1 24646 4 22189 1/2 8295 2/3 4219 0 1829 dtype: int64 1 nan </code></pre> <p>Two questions:</p> <ul> <li>Why is <code>nan</code> printing as an output of <code>normalise_phase</code>, when <code>nan</code> is not listed as a value in <code>value_counts</code>? </li> <li>Why does <code>value_counts</code> show <code>dtype</code> as <code>int64</code> if it has string values like <code>1/2</code> and <code>nan</code> in it too?</li> </ul>
1
2016-08-15T10:38:44Z
38,953,589
<p>You need to pass <code>dropna=False</code> for NaNs to be tallied (see the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.value_counts.html" rel="nofollow">docs</a>). <code>int64</code> is the dtype of the series (counts of the values). The values themselves are the index. dtype of the index will be object, if you check. </p> <pre><code>ser = pd.Series([1, '1/2', '1/2', 3, np.nan, 5]) ser.value_counts(dropna=False) Out: 1/2 2 5 1 3 1 1 1 NaN 1 dtype: int64 ser.value_counts(dropna=False).index Out: Index(['1/2', 5, 3, 1, nan], dtype='object') </code></pre>
3
2016-08-15T10:42:49Z
[ "python", "pandas" ]
codecs.open create txt file in specific path Python
38,953,533
<p>i have this code but it saves the files in the same path of .py file, how can i do to create txt files in specific folder?</p> <pre><code>f = codecs.open("gabili" + '.txt', mode="w", encoding="utf-16") reload(sys) sys.setdefaultencoding('utf8') f.write(u"[HELLO] *ASDASD* /(&amp;) \n") </code></pre>
0
2016-08-15T10:38:50Z
38,953,726
<p>The <a href="https://docs.python.org/3/library/codecs.html?#codecs.open" rel="nofollow"><code>codecs.open</code></a> fonction takes a <em>filename</em> parameter. This <em>filename</em> can be a file name or a full path. So, you can use <code>"/full/path/to/gabili.txt"</code>.</p> <p>To build a full path, you can use <code>os.path</code> package, like this.</p> <pre><code>import os fullpath = os.path.join("/full", "path", "to", "gabili.txt) </code></pre> <p>Then use it in <code>codecs.open</code> parameters:</p> <pre><code>with codecs.open(fullpath, mode="w", encoding="utf-16") as f: f.write(u"[HELLO] *ASDASD* /(&amp;) \n") </code></pre> <p><em>NOTE1: the recommanded way to open a file is by using a <code>with</code> statement</em></p> <p><em>NOTE2: to be portable Py2/Py3, you should use <code>io.open</code> instead of <code>codecs.open</code></em></p> <pre><code>import io with io.open(fullpath, mode="w", encoding="utf-16") as f: f.write(u"[HELLO] *ASDASD* /(&amp;) \n") </code></pre>
1
2016-08-15T10:54:27Z
[ "python", "file", "text" ]
Plotting 2 variables with a heat map
38,953,668
<p>I'm on the python 3 and I have two variables x and y, where x ranges from 1 to 5 and y from 0.03 to 0.7 and I then have a method that takes x and y and generates a scalar number. I want to create a heat map type plot with x as the x-axis and y as the y axis and a colour key to represent the method f(x,y). How is this done? I've tried using heatmaps but cans seem to get it to work due to ranges not being able to get agreeable ranges of x and y. Here's an example I found and that is close to what I'm looking for</p> <pre><code>import numpy as np import numpy.random import matplotlib.pyplot as plt x = np.random.randn(8873) y = np.random.randn(8873) heatmap, xedges, yedges = np.histogram2d(x, y, bins=50) extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]] plt.clf() plt.imshow(heatmap, extent=extent) plt.show() </code></pre> <p>But I want the colour to represent f(x,y) with a key</p>
2
2016-08-15T10:49:09Z
39,917,631
<p>Lets say <code>z = f(x, y)</code>. Your heatmap's key is able to represent one dimension only (usually that would be <em>z</em>). What do you mean by </p> <blockquote> <p>represent the method f(x,y)</p> </blockquote> <p>For 2-dimensional plotting, you would need a 3-dimensional heatmap.</p>
0
2016-10-07T12:44:18Z
[ "python", "plot", "heatmap" ]
Plotting 2 variables with a heat map
38,953,668
<p>I'm on the python 3 and I have two variables x and y, where x ranges from 1 to 5 and y from 0.03 to 0.7 and I then have a method that takes x and y and generates a scalar number. I want to create a heat map type plot with x as the x-axis and y as the y axis and a colour key to represent the method f(x,y). How is this done? I've tried using heatmaps but cans seem to get it to work due to ranges not being able to get agreeable ranges of x and y. Here's an example I found and that is close to what I'm looking for</p> <pre><code>import numpy as np import numpy.random import matplotlib.pyplot as plt x = np.random.randn(8873) y = np.random.randn(8873) heatmap, xedges, yedges = np.histogram2d(x, y, bins=50) extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]] plt.clf() plt.imshow(heatmap, extent=extent) plt.show() </code></pre> <p>But I want the colour to represent f(x,y) with a key</p>
2
2016-08-15T10:49:09Z
39,919,592
<p>If you start with 2 mono-dimensional vectors, <code>x</code> and <code>y</code> to compute a function of <code>x</code> and <code>y</code> on a grid of 2D points you have first to generate said 2D grid, using <code>numpy.meshgrid</code>.</p> <pre><code>from numpy import linspace, meshgrid x, y = linspace(1, 5, 41), linspace(0.03, 0.70, 68) X, Y = meshgrid(x, y) </code></pre> <p>It's somehow a surprise to see that you get <strong>two</strong> grids... one contains only the <code>x</code> values and the other only the <code>y</code> values (you have just to print <code>X</code> and <code>Y</code> to see for yourself).</p> <p>With these two grids available, you can compute a grid of results, but this works only when you use <code>numpy</code>'s <code>ufuncs</code>... e.g.</p> <pre><code>def f(x, y): from numpy import sin, sqrt return sin(sqrt(x*x+y*y)) </code></pre> <p>and eventually you can plot your results, the <code>pyplot</code> method that you want to use is <code>pcolor</code>, and to add a colorbar you have to use, always from <code>pyplot</code>, the <code>colorbar</code> method...</p> <pre><code>from matplotlib.pyplot import colorbar, pcolor, show Z = f(X, Y) pcolor(X, Y, Z) colorbar() show() </code></pre> <p>When this point is eventually reached, tradition asks for a sample output <a href="https://i.stack.imgur.com/2u2nE.png" rel="nofollow"><img src="https://i.stack.imgur.com/2u2nE.png" alt="enter image description here"></a> That's all</p>
1
2016-10-07T14:24:49Z
[ "python", "plot", "heatmap" ]
Convert list of NaNs and strings to int?
38,953,704
<p>I have the following list in Python:</p> <pre><code>mylist = [float('NaN'), u'2', u'3', u'1', u'4', u'1/2', u'2/3', u'0'] </code></pre> <p>I want to convert everything to an int. I want the strings with a slash in to take the first value.</p> <p>This is what I've tried:</p> <pre><code>newlist = [int(str(x).split('/')[0]) for x in mylist] </code></pre> <p>But this doesn't work on the <code>NaN</code> value. What is the best way to handle both the strings and the <code>NaN</code> value?</p>
1
2016-08-15T10:52:28Z
38,953,967
<p>You can use the isnan function in the maths library to check if a float is NaN, however it takes float as an argument, so you'll have to first convert your items into float. You can choose whether to skip the NaN, or save them as some default value. In the code below the NaN's are saved as int 0</p> <pre><code>import math mylist = [float('NaN'), u'2', u'3', u'1', u'4', u'1/2', u'2/3', u'0'] newlist = [] for item in mylist: x = float(str(item).split('/')[0]) if not math.isnan(x): newlist.append(int(x)) else: newlist.append(0) print newlist </code></pre>
1
2016-08-15T11:09:49Z
[ "python" ]
Convert list of NaNs and strings to int?
38,953,704
<p>I have the following list in Python:</p> <pre><code>mylist = [float('NaN'), u'2', u'3', u'1', u'4', u'1/2', u'2/3', u'0'] </code></pre> <p>I want to convert everything to an int. I want the strings with a slash in to take the first value.</p> <p>This is what I've tried:</p> <pre><code>newlist = [int(str(x).split('/')[0]) for x in mylist] </code></pre> <p>But this doesn't work on the <code>NaN</code> value. What is the best way to handle both the strings and the <code>NaN</code> value?</p>
1
2016-08-15T10:52:28Z
38,954,085
<p>We know, that <strong>NaN is always != NaN</strong>.<br> Use the following approach <em>to convert everything to integer</em>:</p> <pre><code>mylist = [float('NaN'), u'2', u'3', u'1', u'4', u'1/2', u'2/3', u'0'] newList = [0 if (not item or (item != item)) else int(str(item).split('/')[0]) for item in mylist] print(newList) </code></pre> <p>The output:</p> <pre><code>[0, 2, 3, 1, 4, 1, 2, 0] </code></pre>
0
2016-08-15T11:18:39Z
[ "python" ]
Convert list of NaNs and strings to int?
38,953,704
<p>I have the following list in Python:</p> <pre><code>mylist = [float('NaN'), u'2', u'3', u'1', u'4', u'1/2', u'2/3', u'0'] </code></pre> <p>I want to convert everything to an int. I want the strings with a slash in to take the first value.</p> <p>This is what I've tried:</p> <pre><code>newlist = [int(str(x).split('/')[0]) for x in mylist] </code></pre> <p>But this doesn't work on the <code>NaN</code> value. What is the best way to handle both the strings and the <code>NaN</code> value?</p>
1
2016-08-15T10:52:28Z
38,954,158
<p>Another solution with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.isnull.html" rel="nofollow"><code>pandas.isnull</code></a>:</p> <pre><code>import pandas as pd import numpy as np mylist = [np.nan, u'2', u'3', u'1', u'4', u'1/2', u'2/3', u'0'] newList = [0 if pd.isnull(item) else int(str(item).split('/')[0]) for item in mylist] print(newList) [0, 2, 3, 1, 4, 1, 2, 0] </code></pre> <p>Pandas solution with replace <code>NaN</code> to <code>'0'</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.fillna.html" rel="nofollow"><code>Series.fillna</code></a>, spliting by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.split.html" rel="nofollow"><code>str.split</code></a>, get first element of lists by <code>str[0]</code> and casting by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.astype.html" rel="nofollow"><code>astype</code></a>:</p> <pre><code>mylist = [np.nan, u'2', u'3', u'1', u'4', u'1/2', u'2/3', u'0'] newList = pd.Series(mylist).fillna('0').str.split('/').str[0].astype(int) print(newList) 0 0 1 2 2 3 3 1 4 4 5 1 6 2 7 0 dtype: int32 print(newList.tolist()) [0, 2, 3, 1, 4, 1, 2, 0] </code></pre>
0
2016-08-15T11:24:12Z
[ "python" ]
Python - Best way to lookup values in a table-like scheme
38,953,748
<p>I have a client who wants a way to calculate shipping costs. It's calculated by weight and kilometer (not linear unfortunately). It looks like this:</p> <pre><code>| | To 50km | To 100km | To 150km | To 200km | |------- |--------- |---------- |---------- |---------- | | 10kg | 84€ | 95€ | 104.45€ | 116€ | | 20kg | 98€ | 108.50€ | 117.10€ | 127.20€ | | 30kg | 112.40€ | 121.20€ | 129.95€ | 149.30€ | </code></pre> <p>I'd love to lookup a value by calling a function like this <code>calc_shipping_costs(range, weight)</code>, so for example <code>calc_shipping_costs(100, 20)</code> and then receive <strong>108.50€</strong></p> <p>What's the best method to do so?</p>
-3
2016-08-15T10:56:04Z
38,956,266
<p>So if anyone is wondering. I did it like this:</p> <pre><code>def calc_shipping_cost(weight, kilometer): WEIGHT_BREAKPOINTS = [10, 20, 40, 60, 80, 100, 500] KILOMETER_BREAKPOINTS = [50, 100, 150, 200, 999] prices = [ [84.85, 95.15, 104.45, 116.70, 122.25], [98.65, 108.45, 117.20, 127.95, 134.60], [112.40, 121.70, 129.95, 149.30, 153.10], [139.95, 148.20, 155.45, 173.10, 177.80], [153.70, 167.50, 168.20, 193.20, 196.30], [181.25, 188.00, 193.70, 225.85, 227.15], [208.80, 214.50, 219.20, 281.00, 282.70], ] row = WEIGHT_BREAKPOINTS.index(weight) col = KILOMETER_BREAKPOINTS.index(kilometer) return prices[row][col] </code></pre>
0
2016-08-15T13:45:01Z
[ "python" ]
Python - Best way to lookup values in a table-like scheme
38,953,748
<p>I have a client who wants a way to calculate shipping costs. It's calculated by weight and kilometer (not linear unfortunately). It looks like this:</p> <pre><code>| | To 50km | To 100km | To 150km | To 200km | |------- |--------- |---------- |---------- |---------- | | 10kg | 84€ | 95€ | 104.45€ | 116€ | | 20kg | 98€ | 108.50€ | 117.10€ | 127.20€ | | 30kg | 112.40€ | 121.20€ | 129.95€ | 149.30€ | </code></pre> <p>I'd love to lookup a value by calling a function like this <code>calc_shipping_costs(range, weight)</code>, so for example <code>calc_shipping_costs(100, 20)</code> and then receive <strong>108.50€</strong></p> <p>What's the best method to do so?</p>
-3
2016-08-15T10:56:04Z
38,962,163
<p>I agree that this question can be considered off-topic, but, for once, it's a real-world problem to solve, not a student question.</p> <p>Unfortunately, the solution you gave is wrong: you only consider that you could havethe “breakpoints” values. If you give different <em>weight</em> (for instance 21) or <em>kilometer</em> (for instance 55), the function raise un exception:</p> <pre><code>&gt;&gt;&gt; calc_shipping_cost(20, 50) 98.65 &gt;&gt;&gt; calc_shipping_cost(21, 55) Traceback (most recent call last): File "python", line 1, in &lt;module&gt; File "python", line 16, in calc_shipping_cost ValueError: 21 is not in list </code></pre> <p>The table says “To 50km”, “To 100km”, etc. So you need a more tolerant function and consider intervals: eg.: [0, 50[, [50, 100[, etc.</p> <p>To choose the index of a value in an ordered list of intervals, you can consider the Array bisection algorithm. Python has an efficient implementation of this algorithm in the <a href="https://docs.python.org/2/library/bisect.html" rel="nofollow">bisect</a> module. It is usually used to calculate the insertion point of an item in an ordered array.</p> <p>For instance:</p> <pre><code>&gt;&gt;&gt; import bisect &gt;&gt;&gt; WEIGHT_BREAKPOINTS = [10, 20, 40, 60, 80, 100, 500] &gt;&gt;&gt; bisect.bisect_left(WEIGHT_BREAKPOINTS, 10) 0 &gt;&gt;&gt; bisect.bisect_left(WEIGHT_BREAKPOINTS, 40) 2 &gt;&gt;&gt; bisect.bisect_left(WEIGHT_BREAKPOINTS, 25) 2 </code></pre> <p>For the last example, the insertion point of 25 is index 2 (to be inserted before 40 which index is 2 also).</p> <p>In case of “out of range”, you can raise your own exception or simply a <code>ValueError</code>.</p> <p>Here is a better implementation:</p> <pre><code>import bisect def calc_shipping_cost(weight, kilometer): WEIGHT_BREAKPOINTS = [10, 20, 40, 60, 80, 100, 500] KILOMETER_BREAKPOINTS = [50, 100, 150, 200, 999] prices = [ [84.85, 95.15, 104.45, 116.70, 122.25], [98.65, 108.45, 117.20, 127.95, 134.60], [112.40, 121.70, 129.95, 149.30, 153.10], [139.95, 148.20, 155.45, 173.10, 177.80], [153.70, 167.50, 168.20, 193.20, 196.30], [181.25, 188.00, 193.70, 225.85, 227.15], [208.80, 214.50, 219.20, 281.00, 282.70], ] row = bisect.bisect_left(WEIGHT_BREAKPOINTS, weight) col = bisect.bisect_left(KILOMETER_BREAKPOINTS, kilometer) try: return prices[row][col] except IndexError: raise ValueError(weight, kilometer) </code></pre> <p>With the following behavior:</p> <pre><code>&gt;&gt;&gt; calc_shipping_cost(10, 50) 84.85 &gt;&gt;&gt; calc_shipping_cost(10.0, 50) 84.85 &gt;&gt;&gt; calc_shipping_cost(20, 50) 98.65 &gt;&gt;&gt; calc_shipping_cost(21, 55) 121.7 &gt;&gt;&gt; calc_shipping_cost(10.0, 50) 84.85 &gt;&gt;&gt; calc_shipping_cost(500, 50) 208.8 &gt;&gt;&gt; calc_shipping_cost(1000, 50) Traceback (most recent call last): File "python", line 1, in &lt;module&gt; File "python", line 24, in calc_shipping_cost ValueError: (1000, 50) </code></pre>
0
2016-08-15T19:59:32Z
[ "python" ]
returning the element in one list based on the index and maximum value of an element in another list
38,953,807
<p>I have a list of lists which I converted into a numpy array:</p> <pre><code>lsts = ([[1,2,3], ['a','b','a']], [[4,5,6,7], ['a','a','b','b']], [[1,2,3],['b','a','b']]) np_lsts = np.array(lsts) </code></pre> <p>I want to return the largest element in the first list where a 'b' occurs in the second list. I think I have to use indexes but am stuck!</p> <p>i.e. I want to return (2, 7, 3) in this case</p>
0
2016-08-15T10:58:47Z
38,953,901
<p>That will do:</p> <pre><code>[max(u for u,v in zip(x,y) if v=='b') for x,y in lsts if 'b' in y] </code></pre> <p>Using <a href="https://docs.python.org/3.5/library/functions.html#zip" rel="nofollow"><code>zip()</code></a> and <a href="https://docs.python.org/3.5/library/functions.html#max" rel="nofollow"><code>max()</code></a> in a nested <a class='doc-link' href="http://stackoverflow.com/documentation/python/196/comprehensions/737/list-comprehensions#t=20160815124037351908">list comprehension</a></p>
1
2016-08-15T11:05:58Z
[ "python", "numpy" ]
returning the element in one list based on the index and maximum value of an element in another list
38,953,807
<p>I have a list of lists which I converted into a numpy array:</p> <pre><code>lsts = ([[1,2,3], ['a','b','a']], [[4,5,6,7], ['a','a','b','b']], [[1,2,3],['b','a','b']]) np_lsts = np.array(lsts) </code></pre> <p>I want to return the largest element in the first list where a 'b' occurs in the second list. I think I have to use indexes but am stuck!</p> <p>i.e. I want to return (2, 7, 3) in this case</p>
0
2016-08-15T10:58:47Z
38,953,940
<p>One possible solution to your problem:</p> <pre><code>lsts = ([[1, 2, 3], ['a', 'b', 'a']], [[4, 5, 6, 7], ['a', 'a', 'b', 'b']], [[1, 2, 3], ['b', 'a', 'b']], [[1, 2, 3], ['a']] ) result = [] for l in lsts: indices = [l[0][index] for index, v in enumerate(l[1]) if v == 'b'] if indices: result.append(max(indices)) print result </code></pre>
1
2016-08-15T11:08:21Z
[ "python", "numpy" ]
returning the element in one list based on the index and maximum value of an element in another list
38,953,807
<p>I have a list of lists which I converted into a numpy array:</p> <pre><code>lsts = ([[1,2,3], ['a','b','a']], [[4,5,6,7], ['a','a','b','b']], [[1,2,3],['b','a','b']]) np_lsts = np.array(lsts) </code></pre> <p>I want to return the largest element in the first list where a 'b' occurs in the second list. I think I have to use indexes but am stuck!</p> <p>i.e. I want to return (2, 7, 3) in this case</p>
0
2016-08-15T10:58:47Z
38,953,999
<pre><code>def get_max(l): first = True for e1, e2 in zip(l[0], l[1]): if e2 == 'b' and first: max = e1 first = False elif e2 == 'b' and e1 &gt; max: max = e1 return max result = () for l in lsts: if 'b' in l[1]: result += (get_max(l),) print(result) </code></pre>
0
2016-08-15T11:12:01Z
[ "python", "numpy" ]
returning the element in one list based on the index and maximum value of an element in another list
38,953,807
<p>I have a list of lists which I converted into a numpy array:</p> <pre><code>lsts = ([[1,2,3], ['a','b','a']], [[4,5,6,7], ['a','a','b','b']], [[1,2,3],['b','a','b']]) np_lsts = np.array(lsts) </code></pre> <p>I want to return the largest element in the first list where a 'b' occurs in the second list. I think I have to use indexes but am stuck!</p> <p>i.e. I want to return (2, 7, 3) in this case</p>
0
2016-08-15T10:58:47Z
38,954,070
<p>The following function returns a <code>result</code> list. If needed, you could return a tuple instead of a list.</p> <pre><code>def maxNum(lsts, character): result = [] for entry in lsts: if character in entry[1]: result.append(max(entry[0])) return result # lsts = ... # (put lsts here) print maxNum(lsts, 'b') </code></pre>
1
2016-08-15T11:17:37Z
[ "python", "numpy" ]