title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
listlengths
1
5
Converting list Dict's to DataFrame: Pandas
38,624,151
<p>I'm doing some web-scraping and I'm storing the variables of interest in form of:</p> <pre><code>a = {'b':[100, 200],'c':[300, 400]} </code></pre> <p>This is for one page, where there were two <code>b</code>'s and two <code>c</code>'s. The next page could have three of each, where I'd store them as:</p> <pre><code>b = {'b':[300, 400, 500],'c':[500, 600, 700]} </code></pre> <p>When I go to create a <code>DataFrame</code> from the list of <code>dict</code>'s, I get:</p> <pre><code>import pandas as pd df = pd.DataFrame([a, b]) df b c 0 [100, 200] [300, 400] 1 [300, 400, 500] [500, 600, 700] </code></pre> <p>What I'm expecting is:</p> <pre><code>df b c 0 100 300 1 200 400 2 300 500 3 400 600 4 500 700 </code></pre> <p>I could create a <code>DataFrame</code> each time I store a page and <code>concat</code> the list of <code>DataFrame</code>'s at the end. However, based on experience, this is very expensive because the construction of thousands of <code>DataFrame</code>'s is much more expensive than creating one <code>DataFrame</code> from a lower-level constructor (i.e., list of <code>dict</code>'s).</p>
2
2016-07-27T22:21:25Z
38,625,256
<p>Comprehensions FTW (maybe not the fastest, but can you get any more pythonic?):</p> <pre><code>import pandas as pd list_of_dicts = [{'b': [100, 200], 'c': [300, 400]}, {'b': [300, 400, 500], 'c': [500, 600, 700]}] def extract(key): return [item for x in list_of_dicts for item in x[key]] df = pd.DataFrame({k: extract(k) for k in ['b', 'c']}) </code></pre> <p>EDIT:</p> <p>I stand corrected. It is just as fast as some of the other approaches.</p> <pre><code>import pandas as pd import toolz list_of_dicts = [{'b': [100, 200], 'c': [300, 400]}, {'b': [300, 400, 500], 'c': [500, 600, 700]}] def extract(key): return [item for x in list_of_dicts for item in x[key]] def merge_dicts(trg, src): for k, v in src.items(): trg[k].extend(v) def approach_AlbertoGarciaRaboso(): df = pd.DataFrame({k: extract(k) for k in ['b', 'c']}) def approach_root(): df = pd.DataFrame(toolz.merge_with(lambda x: list(toolz.concat(x)), list_of_dicts)) def approach_Merlin(): dd = {} for x in list_of_dicts: for k in list_of_dicts[0].keys(): try: dd[k] = dd[k] + x[k] except: dd[k] = x[k] df = pd.DataFrame(dd) def approach_MichaelHoff(): merge_dicts(list_of_dicts[0], list_of_dicts[1]) df = pd.DataFrame(list_of_dicts[0]) %timeit approach_AlbertoGarciaRaboso() # 1000 loops, best of 3: 501 µs per loop %timeit approach_root() # 1000 loops, best of 3: 503 µs per loop %timeit approach_Merlin() # 1000 loops, best of 3: 516 µs per loop %timeit approach_MichaelHoff() # 100 loops, best of 3: 2.62 ms per loop </code></pre>
1
2016-07-28T00:26:22Z
[ "python", "pandas", "dictionary", "dataframe" ]
Kivy and Matplotlib trying to update plot on button callback
38,624,168
<p>I can generate a 2D surface plot very nicely with Kivy and Matplotlib. I am trying to update the Z values on a button click. How may this be accomplished?</p> <p>I noticed that I can issue a plt.clf() which will clear the plot but doing the plt.gcf() to display the current plot doesn't work.</p> <p>Any suggestions would be really appreciated.</p> <pre><code>import matplotlib matplotlib.use('module://kivy.garden.matplotlib.backend_kivy') from matplotlib.figure import Figure from numpy import arange, sin, pi from kivy.app import App import numpy as np from matplotlib.mlab import griddata from kivy.garden.matplotlib.backend_kivy import FigureCanvas,\ NavigationToolbar2Kivy # from backend_kivy import FigureCanvasKivy as FigureCanvas from kivy.uix.floatlayout import FloatLayout from kivy.uix.boxlayout import BoxLayout from matplotlib.transforms import Bbox from kivy.uix.button import Button from kivy.graphics import Color, Line, Rectangle import matplotlib.pyplot as plt from matplotlib import cm from mpl_toolkits.mplot3d import Axes3D fig, ax = plt.subplots() X = np.arange(-508, 510, 203.2) Y = np.arange(-508, 510, 203.2) X, Y = np.meshgrid(X, Y) Z = np.random.rand(6, 6) plt.contourf(X, Y, Z, 100, zdir='z', offset=1.0, cmap=cm.hot) plt.colorbar() ax.set_ylabel('Y [mm]') ax.set_title('NAILS surface') ax.set_xlabel('X [mm]') canvas = fig.canvas def callback(instance): fig, ax = plt.subplots() X = np.arange(-508, 510, 203.2) Y = np.arange(-508, 510, 203.2) X, Y = np.meshgrid(X, Y) Z = np.random.rand(6, 6) plt.contourf(X, Y, Z, 100, zdir='z', offset=1.0, cmap=cm.hot) plt.colorbar() ax.set_ylabel('Y [mm]') ax.set_title('NAILS surface') ax.set_xlabel('X [mm]') canvas = fig.canvas canvas.draw() class MatplotlibTest(App): title = 'Matplotlib Test' def build(self): fl = BoxLayout(orientation="vertical") a = Button(text="press me", height=40, size_hint_y=None) a.bind(on_press=callback) fl.add_widget(canvas) fl.add_widget(a) return fl if __name__ == '__main__': MatplotlibTest().run() </code></pre>
0
2016-07-27T22:23:20Z
38,630,095
<p>Line 45 of your code:</p> <pre><code>fig, ax = plt.subplots() </code></pre> <p>creates a new figure and hence a new canvas. This canvas is never added to the <code>BoxLayout</code> and hence never shown. It's probably a better idea to re-use the old canvas. Change the callback function to this:</p> <pre><code>def callback(instance): # Clear the existing figure and re-use it plt.clf() X = np.arange(-508, 510, 203.2) Y = np.arange(-508, 510, 203.2) X, Y = np.meshgrid(X, Y) Z = np.random.rand(6, 6) plt.contourf(X, Y, Z, 100, zdir='z', offset=1.0, cmap=cm.hot) plt.colorbar() ax.set_ylabel('Y [mm]') ax.set_title('NAILS surface') ax.set_xlabel('X [mm]') canvas.draw_idle() </code></pre>
0
2016-07-28T07:45:08Z
[ "python", "matplotlib", "kivy" ]
Kivy and Matplotlib trying to update plot on button callback
38,624,168
<p>I can generate a 2D surface plot very nicely with Kivy and Matplotlib. I am trying to update the Z values on a button click. How may this be accomplished?</p> <p>I noticed that I can issue a plt.clf() which will clear the plot but doing the plt.gcf() to display the current plot doesn't work.</p> <p>Any suggestions would be really appreciated.</p> <pre><code>import matplotlib matplotlib.use('module://kivy.garden.matplotlib.backend_kivy') from matplotlib.figure import Figure from numpy import arange, sin, pi from kivy.app import App import numpy as np from matplotlib.mlab import griddata from kivy.garden.matplotlib.backend_kivy import FigureCanvas,\ NavigationToolbar2Kivy # from backend_kivy import FigureCanvasKivy as FigureCanvas from kivy.uix.floatlayout import FloatLayout from kivy.uix.boxlayout import BoxLayout from matplotlib.transforms import Bbox from kivy.uix.button import Button from kivy.graphics import Color, Line, Rectangle import matplotlib.pyplot as plt from matplotlib import cm from mpl_toolkits.mplot3d import Axes3D fig, ax = plt.subplots() X = np.arange(-508, 510, 203.2) Y = np.arange(-508, 510, 203.2) X, Y = np.meshgrid(X, Y) Z = np.random.rand(6, 6) plt.contourf(X, Y, Z, 100, zdir='z', offset=1.0, cmap=cm.hot) plt.colorbar() ax.set_ylabel('Y [mm]') ax.set_title('NAILS surface') ax.set_xlabel('X [mm]') canvas = fig.canvas def callback(instance): fig, ax = plt.subplots() X = np.arange(-508, 510, 203.2) Y = np.arange(-508, 510, 203.2) X, Y = np.meshgrid(X, Y) Z = np.random.rand(6, 6) plt.contourf(X, Y, Z, 100, zdir='z', offset=1.0, cmap=cm.hot) plt.colorbar() ax.set_ylabel('Y [mm]') ax.set_title('NAILS surface') ax.set_xlabel('X [mm]') canvas = fig.canvas canvas.draw() class MatplotlibTest(App): title = 'Matplotlib Test' def build(self): fl = BoxLayout(orientation="vertical") a = Button(text="press me", height=40, size_hint_y=None) a.bind(on_press=callback) fl.add_widget(canvas) fl.add_widget(a) return fl if __name__ == '__main__': MatplotlibTest().run() </code></pre>
0
2016-07-27T22:23:20Z
38,642,936
<p>Need to make the fig and ax variables global. Call plt.clf() to clear the current figure and re-plot with appropriate colorbar.</p> <pre><code>import matplotlib matplotlib.use('module://kivy.garden.matplotlib.backend_kivy') from matplotlib.figure import Figure from numpy import arange, sin, pi from kivy.app import App import numpy as np from matplotlib.mlab import griddata from kivy.garden.matplotlib.backend_kivy import FigureCanvas,\ NavigationToolbar2Kivy # from backend_kivy import FigureCanvasKivy as FigureCanvas from kivy.uix.floatlayout import FloatLayout from kivy.uix.boxlayout import BoxLayout from matplotlib.transforms import Bbox from kivy.uix.button import Button from kivy.graphics import Color, Line, Rectangle import matplotlib.pyplot as plt from matplotlib import cm from mpl_toolkits.mplot3d import Axes3D # fig, ax = plt.subplots() fig, ax = plt.subplots() X = np.arange(-508, 510, 203.2) Y = np.arange(-508, 510, 203.2) X, Y = np.meshgrid(X, Y) Z = np.random.rand(6, 6) plt.contourf(X, Y, Z, 100, zdir='z', offset=1.0, cmap=cm.hot) plt.colorbar() ax.set_ylabel('Y [mm]') ax.set_title('NAILS surface') ax.set_xlabel('X [mm]') canvas = fig.canvas def callback(instance): global fig, ax # fig, ax = plt.subplots() X = np.arange(-508, 510, 203.2) Y = np.arange(-508, 510, 203.2) X, Y = np.meshgrid(X, Y) Z = 1000*np.random.rand(6, 6) plt.clf() plt.contourf(X, Y, Z, 100, zdir='z', offset=1.0, cmap=cm.hot) plt.colorbar() # ax.set_ylabel('Y [mm]') # ax.set_title('NAILS surface') # ax.set_xlabel('X [mm]') # canvas = fig.canvas canvas.draw() class MatplotlibTest(App): title = 'Matplotlib Test' def build(self): fl = BoxLayout(orientation="vertical") a = Button(text="press me", height=40, size_hint_y=None) a.bind(on_press=callback) fl.add_widget(canvas) fl.add_widget(a) return fl if __name__ == '__main__': MatplotlibTest().run() </code></pre>
0
2016-07-28T17:22:11Z
[ "python", "matplotlib", "kivy" ]
variable that is set to True in if statement never becomes False
38,624,188
<p>I have a list of rectangles coordinates, that I'm iterating over to test for collisions with each one. The list is Like so: <code>self.rectangle_list = [(200, 30, 100, 10), (200, 60, 100, 10), (200, 90, 100, 10), (200, 120, 100, 10), (200, 150, 100, 10)]</code>. My code for the for loop is below.</p> <pre><code> mouse_x, mouse_y = event_obj.pos # mouse_x, mouse_y are the coordinates of the mouse. for rects in self.rectangle_list: x, y, w, h = rects if x &lt;= mouse_x &lt;= x + w and y &lt;= mouse_y &lt;= y + h: self.hovering = True else: self.hovering = False print(self.hovering) </code></pre> <p>When I print out <code>self.hovering</code>, The only time It changes to True is when The mouse cursor is in the coordinates of the very last rectangle in the list.</p> <p>When I move <code>self.hovering</code> under the <code>if</code> statement it works, but never sets <code>self.hovering</code> back to False while the <code>if</code> condition is not meet.</p> <p>example code to reproduce the problem is bellow:</p> <pre><code>import pygame as pg class RenderRects: def __init__(self, surface, rects_to_render=0): self.surface = surface self.rects_to_render = rects_to_render self.rectangle_list = [] self.hovering = False def render_rects(self): y_padding = 0 for rects in range(self.rects_to_render): y_padding += 30 menu_items_rect = (200, y_padding, 100, 10) pg.draw.rect(self.surface, (255, 0, 0), menu_items_rect) if len(self.rectangle_list) &gt; 5: del self.rectangle_list[4:] self.rectangle_list.append(menu_items_rect) def check_for_rect_collision(self, event_obj): #-----------------Where problem is-----------# mx, my = event_obj.pos for rects in self.rectangle_list: x, y, w, h = rects if x &lt;= mx &lt;= x + w and y &lt;= my &lt;= y + h: self.hovering = True else: self.hovering = False print(self.hovering) #-----------------Where problem is-----------# def update_rects(self, event_obj): if event_obj.type == pg.MOUSEMOTION: self.check_for_rect_collision(event_obj) def main(): WIDTH = 800 HEIGHT = 600 display = pg.display.set_mode((WIDTH, HEIGHT)) R = RenderRects(display, rects_to_render=5) running = True while running: for e in pg.event.get(): if e.type == pg.QUIT: running = False pg.quit() quit() R.update_rects(e) display.fill((255, 255, 255)) R.render_rects() pg.display.flip() if __name__ == '__main__': main() </code></pre>
0
2016-07-27T22:25:23Z
38,624,229
<p>Your <code>if</code> statement has a problem:</p> <pre><code>if x &lt;= mouse_x &lt;= x + w and y &lt;= mouse_y &lt;= y + h: self.hovering = True </code></pre> <p>You can't chain less than/greater than as you do in: <code>x &lt;= mouse_x &lt;= x + w</code>. This really gets translated to:</p> <pre><code>if x &lt;= (mouse_x &lt;= x + w) .... </code></pre> <p>And since <code>True == 1</code> and <code>False == 0</code>, this means that if <code>mouse_x &lt;= x + w</code> is <code>True</code>, <code>x &lt;= (mouse_x &lt;= x + w)</code> really becomes <code>x &lt;= 1</code></p> <p><br/></p> <p><strong><em>Edit -- Added additional problem explanation</em></strong> (credit to <a href="http://stackoverflow.com/users/6525140/michael-hoff">Michael Hoff</a> for the suggestion)</p> <p>You also have a problem with your loop. In the loop, <em>for every rectangle pair</em>, you set the variable <code>self.hovering</code>. This means that you are continuously overwriting the value of <code>self.hovering</code> with the status of the <em>current</em> rectangle --- not if <em>any</em> of the rectangles are hovering.</p> <p>Instead, since you care if <code>self.hovering</code> is <em>ever</em> <code>True</code>, you should only set the value in the <code>True</code> case:</p> <pre><code>self.hovering = False # assume it's not hovering at first for rects in self.rectangle_list: x, y, w, h = rects if x &lt;= mouse_x and mouse_x &lt;= x + w and y &lt;= mouse_y and mouse_y &lt;= y + h: self.hovering = True # now it will always be True </code></pre> <p>While this solves the loop issue, it's still a little bit inefficient, as it will continue looping over the pairs even after you find one that makes <code>self.hovering = True</code>. To stop looping when you find a "good" pair, you can use <code>break</code>, which just prematurely ends a loop.</p> <pre><code>self.hovering = False # assume it's not hovering at first for rects in self.rectangle_list: x, y, w, h = rects if x &lt;= mouse_x and mouse_x &lt;= x + w and y &lt;= mouse_y and mouse_y &lt;= y + h: self.hovering = True # now it will always be True break # exit the loop, since we've found what we're looking for </code></pre>
2
2016-07-27T22:28:58Z
[ "python", "list", "pygame", "iteration" ]
variable that is set to True in if statement never becomes False
38,624,188
<p>I have a list of rectangles coordinates, that I'm iterating over to test for collisions with each one. The list is Like so: <code>self.rectangle_list = [(200, 30, 100, 10), (200, 60, 100, 10), (200, 90, 100, 10), (200, 120, 100, 10), (200, 150, 100, 10)]</code>. My code for the for loop is below.</p> <pre><code> mouse_x, mouse_y = event_obj.pos # mouse_x, mouse_y are the coordinates of the mouse. for rects in self.rectangle_list: x, y, w, h = rects if x &lt;= mouse_x &lt;= x + w and y &lt;= mouse_y &lt;= y + h: self.hovering = True else: self.hovering = False print(self.hovering) </code></pre> <p>When I print out <code>self.hovering</code>, The only time It changes to True is when The mouse cursor is in the coordinates of the very last rectangle in the list.</p> <p>When I move <code>self.hovering</code> under the <code>if</code> statement it works, but never sets <code>self.hovering</code> back to False while the <code>if</code> condition is not meet.</p> <p>example code to reproduce the problem is bellow:</p> <pre><code>import pygame as pg class RenderRects: def __init__(self, surface, rects_to_render=0): self.surface = surface self.rects_to_render = rects_to_render self.rectangle_list = [] self.hovering = False def render_rects(self): y_padding = 0 for rects in range(self.rects_to_render): y_padding += 30 menu_items_rect = (200, y_padding, 100, 10) pg.draw.rect(self.surface, (255, 0, 0), menu_items_rect) if len(self.rectangle_list) &gt; 5: del self.rectangle_list[4:] self.rectangle_list.append(menu_items_rect) def check_for_rect_collision(self, event_obj): #-----------------Where problem is-----------# mx, my = event_obj.pos for rects in self.rectangle_list: x, y, w, h = rects if x &lt;= mx &lt;= x + w and y &lt;= my &lt;= y + h: self.hovering = True else: self.hovering = False print(self.hovering) #-----------------Where problem is-----------# def update_rects(self, event_obj): if event_obj.type == pg.MOUSEMOTION: self.check_for_rect_collision(event_obj) def main(): WIDTH = 800 HEIGHT = 600 display = pg.display.set_mode((WIDTH, HEIGHT)) R = RenderRects(display, rects_to_render=5) running = True while running: for e in pg.event.get(): if e.type == pg.QUIT: running = False pg.quit() quit() R.update_rects(e) display.fill((255, 255, 255)) R.render_rects() pg.display.flip() if __name__ == '__main__': main() </code></pre>
0
2016-07-27T22:25:23Z
38,624,256
<p>You set <code>self.hovering</code> inside the loop for <em>every</em> rectangle in the list. This means, after the loop the value of <code>self.hovering</code> corresponds to the "hovering state" of only the <em>last</em> rectangle.</p> <p>I think you want to set <code>self.hovering = False</code> before the loop and in the loop set it to <code>True</code> if one of the rectangles matches your condition. This way, <code>self.hovering == True</code> holds only if at least one of your rectangles matches your condition.</p> <p>This is a simplistic example for your problem:</p> <pre><code>numbers = [2,3,4] contains_odd = False for number in numbers: if number % 2 == 0: contains_odd = False # this is wrong! else: contains_odd = True # contains_odd == (numbers[2] % 2 == 1) == False </code></pre> <p>The solution would be:</p> <pre><code>numbers = [2,3,4] contains_odd = False for number in numbers: if number % 2 == 1: contains_odd = True # contains_odd == True </code></pre>
4
2016-07-27T22:30:41Z
[ "python", "list", "pygame", "iteration" ]
variable that is set to True in if statement never becomes False
38,624,188
<p>I have a list of rectangles coordinates, that I'm iterating over to test for collisions with each one. The list is Like so: <code>self.rectangle_list = [(200, 30, 100, 10), (200, 60, 100, 10), (200, 90, 100, 10), (200, 120, 100, 10), (200, 150, 100, 10)]</code>. My code for the for loop is below.</p> <pre><code> mouse_x, mouse_y = event_obj.pos # mouse_x, mouse_y are the coordinates of the mouse. for rects in self.rectangle_list: x, y, w, h = rects if x &lt;= mouse_x &lt;= x + w and y &lt;= mouse_y &lt;= y + h: self.hovering = True else: self.hovering = False print(self.hovering) </code></pre> <p>When I print out <code>self.hovering</code>, The only time It changes to True is when The mouse cursor is in the coordinates of the very last rectangle in the list.</p> <p>When I move <code>self.hovering</code> under the <code>if</code> statement it works, but never sets <code>self.hovering</code> back to False while the <code>if</code> condition is not meet.</p> <p>example code to reproduce the problem is bellow:</p> <pre><code>import pygame as pg class RenderRects: def __init__(self, surface, rects_to_render=0): self.surface = surface self.rects_to_render = rects_to_render self.rectangle_list = [] self.hovering = False def render_rects(self): y_padding = 0 for rects in range(self.rects_to_render): y_padding += 30 menu_items_rect = (200, y_padding, 100, 10) pg.draw.rect(self.surface, (255, 0, 0), menu_items_rect) if len(self.rectangle_list) &gt; 5: del self.rectangle_list[4:] self.rectangle_list.append(menu_items_rect) def check_for_rect_collision(self, event_obj): #-----------------Where problem is-----------# mx, my = event_obj.pos for rects in self.rectangle_list: x, y, w, h = rects if x &lt;= mx &lt;= x + w and y &lt;= my &lt;= y + h: self.hovering = True else: self.hovering = False print(self.hovering) #-----------------Where problem is-----------# def update_rects(self, event_obj): if event_obj.type == pg.MOUSEMOTION: self.check_for_rect_collision(event_obj) def main(): WIDTH = 800 HEIGHT = 600 display = pg.display.set_mode((WIDTH, HEIGHT)) R = RenderRects(display, rects_to_render=5) running = True while running: for e in pg.event.get(): if e.type == pg.QUIT: running = False pg.quit() quit() R.update_rects(e) display.fill((255, 255, 255)) R.render_rects() pg.display.flip() if __name__ == '__main__': main() </code></pre>
0
2016-07-27T22:25:23Z
38,624,284
<p>The code is iterating through the list and self.hovering changes after each step. Therefore, the last rectangle determines which value is printed since its the only one influencing it since the print function is called <strong>outside</strong> of the loop.</p> <p><strong>Update</strong>: <br> If you want it to be True if <strong>any</strong> of the rectangles fits, you can use:</p> <pre><code>any([x &lt;= mouse_x &lt;= x + w and y &lt;= mouse_y &lt;= y + h for x,y,w,h in self.rectangle_list]) </code></pre> <p>Any is a built-in function that is given an iterable as argument. It returns True whenever any value within the iterable is True, otherwise False. In this case, it is given a list created by a so called list comprehension. The list comprehension is equivalent to the following:</p> <pre><code>lis = [] for x, y, w, h in self.rectangle_list: lis.append(x &lt;= mouse_x &lt;= x + w and y &lt;= mouse_y &lt;= y + h) </code></pre> <p>However, it does not require to create an empty list first and is therfore more compact. </p>
1
2016-07-27T22:32:44Z
[ "python", "list", "pygame", "iteration" ]
Crop images using dimensions extracted from txt file
38,624,200
<p>I would like to crop multiple images in my folder using PIL or opencv2. But, I have the dimensions in a text file having the same filename as the image. So, let's say my filename is 1_a.jpg, the dimensions (top left.x,width;top left.x,height) are in the 1_a.txt file. So, my program must iterate through every file, select the dimensions and crop the image. I am using a similar setup where I am trying to append all the dimensions in a list separately and then trying to iterate images pointing to the lists while cropping but however, it doesn't work. Kindly help.</p> <p>Find my code below:-</p> <pre><code>for f in glob.glob(os.path.join(faces_folder_path, "*.txt")): file = open(f) small=[] data= file.read() print type(data) small.append(data.rstrip('\n')) print small print small[1] print type(small) x.append(small) print type(x) print x # print type(list) # print list # # print x # x.append(list) # for i,val in enumerate(x): # print val[0] for f in glob.glob(os.path.join(faces_folder_path, "*.png")): imgfile = f[53:75] print imgfile img=cv2.imread(imgfile) cv2.imshow('image',img) print (x[i]) print type(x[i]) # new_image=img[x[i]] # cv2.imshow('cropped',new_image) # cv2.imsave('imgfile',new_image) i+=1 cv2.waitKey(0) </code></pre>
0
2016-07-27T22:26:54Z
38,630,346
<p>You would be best to just cycle through all of the PNG files, and for each one attempt to find a matching text file as follows:</p> <pre><code>import glob import os import re faces_folder_path = r"c:\myfiles" for png_file in glob.glob(os.path.join(faces_folder_path, "*.png")): name, ext = os.path.splitext(os.path.basename(png_file)) try: with open(os.path.join(faces_folder_path, '{}.txt'.format(name))) as f_text: re_crop = re.search(r'(\d+),(\d+);(\d+),(\d+)', f_text.read()) if re_crop: x, width, y, height = [int(v) for v in re_crop.groups()] # Add crop code here else: print '"{}" text file format not understood'.format(png_file) except IOError as e: print '"{}" has no matching txt file'.format(png_file) </code></pre> <p>This takes the file path to each png file and extracts the base filename. It then constructs a matching txt file, loads this in and uses a regular expression to try and find the required crop details. Each entry is converted to <code>int</code>.</p> <p>This assumes an example text file would look something like this:</p> <pre class="lang-none prettyprint-override"><code>0,100;10,50 </code></pre>
0
2016-07-28T07:57:59Z
[ "python", "image", "opencv" ]
QFileDialog view folders and files but select folders only?
38,624,245
<p>I'm creating my own custom file dialog using the following code:</p> <pre><code>file_dialog = QtGui.QFileDialog() file_dialog.setFileMode(QtGui.QFileDialog.Directory) file_dialog.setViewMode(QtGui.QFileDialog.Detail) file_dialog.setOption(QtGui.QFileDialog.DontUseNativeDialog, True) </code></pre> <p>The behaviour that i'm interested in is for the user to be able to view both files and folders, but select folders only. (making files unselectable). Is that possible? </p> <p><strong>Note:</strong> Using the <code>DirectoryOnly</code> option is not good for me since it doesn't allow you to view files, just folders.</p> <p><strong>Edit</strong> (extra code that i forgot to add which responsible for being able to select multiple folders instead of just one):</p> <pre><code>file_view = file_dialog.findChild(QtGui.QListView, 'listView') if file_view: file_view.setSelectionMode(QtGui.QAbstractItemView.MultiSelection) f_tree_view = file_dialog.findChild(QtGui.QTreeView) if f_tree_view: f_tree_view.setSelectionMode(QtGui.QAbstractItemView.MultiSelection) </code></pre>
1
2016-07-27T22:29:44Z
38,643,574
<p>To prevent files being selected, you can install a proxy model which manipulates the flags for items in the file-view:</p> <pre><code>class ProxyModel(QtGui.QIdentityProxyModel): def flags(self, index): flags = super(ProxyModel, self).flags(index) if not self.sourceModel().isDir(index): flags &amp;= ~QtCore.Qt.ItemIsSelectable return flags # keep a reference somewhere to prevent core-dumps on exit self._proxy = ProxyModel(self) file_dialog.setProxyModel(self._proxy) </code></pre>
2
2016-07-28T17:57:02Z
[ "python", "qt", "pyqt", "qfiledialog" ]
What is the difference between metrics.auc and scipy.integrate.quad?
38,624,290
<p>I am getting different values when I calculate the Area Under the Curve when use sklearn.metrics.auc and when I use scipy.integrate.quad. </p> <p>To calculate the AUC, I passing in my data:</p> <pre><code>auc_path = metrics.auc(path,year) auc_sbt = metrics.auc(sbt,year) auc_path = 14929608030 auc_sbt = 14846098649 </code></pre> <p>To calculate the definite integral, I input the trendline equations (generated from the same data I input above) that I found from Excel into python:</p> <pre><code>def cur_path(x): return -47177.249*x + 8586190.275 cur_path_i, cur_path_err = quad(cur_path,1,23) def req_path(x): return 23195385.6616*np.exp(-0.049*x) req_path_i, req_path_err = quad(req_path,24,61) def sbt(x): return 8838484.57*np.exp(-0.03*x) sbt_i, sbt_err = quad(sbt,1,61) path = 298653886 sbt = 238648501 </code></pre> <p>Is the error attributed to the trendline equation from Excel? </p> <p>Thank you!</p>
0
2016-07-27T22:33:18Z
38,625,120
<p><a href="http://scikit-learn.org/stable/modules/generated/sklearn.metrics.auc.html" rel="nofollow"><code>sklearn.metrics.auc</code></a> just estimates the integral for your given pair of <code>x</code> and <code>y</code> vectors using the <a href="https://en.wikipedia.org/wiki/Trapezoidal_rule" rel="nofollow">trapezoid rule</a>. It doesn't make any strong assumptions about the functional form of the ROC curve.</p> <p>In the second case you seem to have fitted an exponential parametric model to your data (in Excel?), then used <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.quad.html" rel="nofollow"><code>scipy.integrate.quad</code></a> to integrate the fitted function over some interval.</p> <p>There's no particular reason to expect these two approaches to give identical results. Without having the data there's no way for us to tell whether your exponential fit looks good, or even whether an exponential model is appropriate in this case.</p>
0
2016-07-28T00:06:39Z
[ "python", "excel", "numpy", "scipy", "scikit-learn" ]
What is the difference between metrics.auc and scipy.integrate.quad?
38,624,290
<p>I am getting different values when I calculate the Area Under the Curve when use sklearn.metrics.auc and when I use scipy.integrate.quad. </p> <p>To calculate the AUC, I passing in my data:</p> <pre><code>auc_path = metrics.auc(path,year) auc_sbt = metrics.auc(sbt,year) auc_path = 14929608030 auc_sbt = 14846098649 </code></pre> <p>To calculate the definite integral, I input the trendline equations (generated from the same data I input above) that I found from Excel into python:</p> <pre><code>def cur_path(x): return -47177.249*x + 8586190.275 cur_path_i, cur_path_err = quad(cur_path,1,23) def req_path(x): return 23195385.6616*np.exp(-0.049*x) req_path_i, req_path_err = quad(req_path,24,61) def sbt(x): return 8838484.57*np.exp(-0.03*x) sbt_i, sbt_err = quad(sbt,1,61) path = 298653886 sbt = 238648501 </code></pre> <p>Is the error attributed to the trendline equation from Excel? </p> <p>Thank you!</p>
0
2016-07-27T22:33:18Z
38,647,387
<p>Based on your description of your data, I get the following plots. For the path data (curr_path and then req_path), I use this function: </p> <pre><code>start = 8549826 def path(year): if year &gt; 23: return start*(cur_path_exp)**23 * req_path_exp**(year-23) else: return start * (cur_path_exp)**year </code></pre> <p>and get this plot (over year from 1 to 61): <a href="http://i.stack.imgur.com/2UrV0.png" rel="nofollow"><img src="http://i.stack.imgur.com/2UrV0.png" alt="Plot of the generated path data."></a></p> <p>For the sbt array, I use this function:</p> <pre><code>start = 8549826 sbt = lambda year: start * (sbt_exp)**year </code></pre> <p>and get this plot:</p> <p><a href="http://i.stack.imgur.com/s2jWX.png" rel="nofollow"><img src="http://i.stack.imgur.com/s2jWX.png" alt="sbt plot"></a></p> <p>I then compared the integrals using <code>scipy.integrate.quad</code> and <code>sklearn.metrics.auc</code>.</p> <pre><code>import numpy as np from scipy.integrate import quad from sklearn.metrics import auc start = 8549826 sbt_exp = 0.9673405832388313 cur_path_exp = .9941 req_path_exp = 0.9522 sbt = lambda year: start * (sbt_exp)**year def path(year): if year &gt; 23: return start*(cur_path_exp)**23 * req_path_exp**(year-23) else: return start * (cur_path_exp)**year years = range(1,62) print "Quad sbt: ", quad(sbt, 1,61), "Auc sbt: ",auc(map(sbt, years), years) print "Quad sbt: ",quad(path, 1, 61), "Auc sbt: ",auc(map(path, years),years) </code></pre> <p>and got the output:</p> <pre><code>Quad sbt: (215108922.75692844, 2.3881887884705626e-06) Auc sbt: 154592534.468 Quad sbt: (303985184.7185244, 0.4825437736101641) Auc sbt: 241740742.863 </code></pre> <p>As you can see, they are quite different. This is because auc uses a simple trapezoidal rule, while quad uses the function you give it to interpolate the data and has a much higher level of accuracy. In summary, the difference between an <strong>exponential</strong> and a <strong>piece-wise linear interpolation</strong> is <strong>huge</strong>. </p>
0
2016-07-28T21:55:54Z
[ "python", "excel", "numpy", "scipy", "scikit-learn" ]
wrap a variable number of instances in a string with parenthesis in python
38,624,332
<p>I have a string that contains variable names separated by 'and's/'or's such as 'x[1] and x[2] or x[3]'. The number of variable names varies as does whether it's an 'and' or 'or' that comes in between them. I want to wrap parenthesis around each stretch of variables separated by 'or's. For example, if the string is 'x[1] and x[2] or x[3] and x[4] or x[5] or x[6] and x[7]', I want to change it to 'x[1] and (x[2] or x[3]) and (x[4] or x[5] or x[6]) and x[7]'.</p> <p>I'm not even a novice at regex. I was wondering if there is a fairly elegant and efficient way to do this using regex in python? Any help would be greatly appreacited.</p> <p>Josh</p>
0
2016-07-27T22:36:54Z
38,624,461
<p>This might do what you want:</p> <pre><code>import re s = 'x[1] and x[2] or x[3] and x[4] or x[5] or x[6] and x[7]' s = re.sub(r'(\S+(?:\s*or\s*\S+)+)', r'(\1)', s) assert s == 'x[1] and (x[2] or x[3]) and (x[4] or x[5] or x[6]) and x[7]' </code></pre> <hr /> <p>EDIT: A slightly more robust expression and more test cases:</p> <pre><code>import re tests = ( ('x[1] and x[2] or x[3] and x[4] or x[5] or x[6] and x[7]', 'x[1] and (x[2] or x[3]) and (x[4] or x[5] or x[6]) and x[7]'), ('door and floor', 'door and floor'), ('more and more and more', 'more and more and more') ) for test, expected in tests: actual = re.sub(r'\S+(?:\s*\bor\b\s*\S+)+', r'(\g&lt;0&gt;)', test) assert actual == expected </code></pre>
1
2016-07-27T22:50:31Z
[ "python", "regex", "search", "find", "substitution" ]
wrap a variable number of instances in a string with parenthesis in python
38,624,332
<p>I have a string that contains variable names separated by 'and's/'or's such as 'x[1] and x[2] or x[3]'. The number of variable names varies as does whether it's an 'and' or 'or' that comes in between them. I want to wrap parenthesis around each stretch of variables separated by 'or's. For example, if the string is 'x[1] and x[2] or x[3] and x[4] or x[5] or x[6] and x[7]', I want to change it to 'x[1] and (x[2] or x[3]) and (x[4] or x[5] or x[6]) and x[7]'.</p> <p>I'm not even a novice at regex. I was wondering if there is a fairly elegant and efficient way to do this using regex in python? Any help would be greatly appreacited.</p> <p>Josh</p>
0
2016-07-27T22:36:54Z
38,624,562
<p>As you already have an answer with a regex method, here is a method that doesn't require a regex:</p> <pre><code>&gt;&gt;&gt; s = 'x[1] and x[2] or x[3] and x[4] or x[5] or x[6] and x[7]' &gt;&gt;&gt; ' and '.join(['(%s)' % w if ' or ' in w else w for w in s.split(' and ')]) 'x[1] and (x[2] or x[3]) and (x[4] or x[5] or x[6]) and x[7]' </code></pre> <h3>How it works</h3> <p>The first step is to split on <code>and</code>:</p> <pre><code>&gt;&gt;&gt; s.split(' and ') ['x[1]', 'x[2] or x[3]', 'x[4] or x[5] or x[6]', 'x[7]'] </code></pre> <p>The next step is to decide if the substrings need to be surrounded by parens. That is done with a ternary statement:</p> <pre><code>&gt;&gt;&gt; w = 'x[2] or x[3]'; '(%s)' % w if ' or ' in w else w '(x[2] or x[3])' &gt;&gt;&gt; w = 'x[1]'; '(%s)' % w if ' or ' in w else w 'x[1]' </code></pre> <p>The last step is to reassemble the string with <code>' and '.join(...)</code>.</p>
0
2016-07-27T23:03:00Z
[ "python", "regex", "search", "find", "substitution" ]
Tastypie access resource by parameter other than PK
38,624,446
<p>I am having a hard time figuring out how to ask this question. </p> <p>I have a model <code>User</code>. Currently when I want to access a specific user I go to the url: <code>/api/v1/user/8/</code>. Although, all users have unique usernames, so I would like to go to a specific user by using the url: <code>/api/v1/user/joe/</code>.</p> <p>Maybe something with <code>prepend_urls()</code>?</p>
0
2016-07-27T22:49:34Z
38,624,576
<p>You need to use <code>detail_uri_name</code> in your <code>ModelResource</code>'s <code>Meta</code> class (<a href="http://django-tastypie.readthedocs.io/en/latest/resources.html#detail-uri-name" rel="nofollow">documentation</a>) - example resources.py:</p> <pre><code>from django.contrib.auth.models import User from tastypie.resources import ModelResource class UserResource(ModelResource): class Meta: queryset = User.objects.all() allowed_methods = ['get'] detail_uri_name = 'username' </code></pre>
3
2016-07-27T23:04:17Z
[ "python", "django", "api", "tastypie" ]
websockets proxied by nginx to gunicorn over https giving 400 (bad request)
38,624,447
<p>I am having trouble establishing a websocket in my Flask web application.</p> <p>On the client side, I am emitting a "ping" websocket event every second to the server. In the browser console, I see the following error each second</p> <pre><code>POST https://example.com/socket.io/?EIO=3&amp;transport=polling&amp;t=LOkVYzQ&amp;sid=88b5202cf38f40879ddfc6ce36322233 400 (BAD REQUEST) GET https://example.com/socket.io/?EIO=3&amp;transport=polling&amp;t=LOkVZLN&amp;sid=5a355bbccb6f4f05bd46379066876955 400 (BAD REQUEST) WebSocket connection to 'wss://example.com/socket.io/?EIO=3&amp;transport=websocket&amp;sid=5a355bbccb6f4f05bd46379066876955' failed: WebSocket is closed before the connection is established. </code></pre> <p>I have the following <code>nginx.conf</code></p> <pre><code>server { listen 80; server_name example.com www.example.com; return 301 https://$server_name$request_uri; } upstream app_server { # for UNIX domain socket setups server unix:/pathtowebapp/gunicorn.sock fail_timeout=0; } server { listen 443 ssl; server_name example.com www.example.com; keepalive_timeout 5; ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ssl_prefer_server_ciphers on; ssl_ciphers 'EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH'; charset utf-8; client_max_body_size 30M; location / { try_files $uri @proxy_to_app; } location /socket.io { proxy_pass http://app_server; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Upgrade websocket; proxy_set_header Connection "upgrade"; proxy_read_timeout 86400; proxy_buffering off; proxy_headers_hash_max_size 1024; } location /static { alias /pathtowebapp/webapp/static; } location @proxy_to_app { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # enable this if and only if you use HTTPS proxy_set_header X-Forwarded-Proto https; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header Host $http_host; # we don't want nginx trying to do something clever with # redirects, we set the Host: header above already. proxy_redirect off; #proxy_buffering off; proxy_pass http://app_server; } } </code></pre> <p>I have been looking all over for examples of a websocket working with https using nginx in front of gunicorn. </p> <p>My webpage loads, although the websocket connection is not successful.</p> <p>The client side websocket is established using the following javascript:</p> <pre><code>var socket = io.connect('https://' + document.domain + ':' + location.port + namespace); </code></pre> <p>Here is my <code>gunicorn.conf</code></p> <pre><code>import multiprocessing bind = 'unix:/pathtowebapp/gunicorn.sock' workers = multiprocessing.cpu_count() * 2 + 1 worker_class = 'eventlet' </code></pre> <p><strong>[EDIT]</strong> if I configure nginx the way it is in the <a href="https://flask-socketio.readthedocs.io/en/latest/#using-nginx-as-a-websocket-reverse-proxy" rel="nofollow">Flask-IO documentation</a> and just run <code>(env)$ python deploy_app.py</code> then it works. But I was under the impression that this was not as production-ideal as the setup I previously mentioned</p>
1
2016-07-27T22:49:42Z
38,648,638
<p>The problem is that you are running multiple workers on gunicorn. This is not a configuration that is currently supported, due to the very limited load balancer in gunicorn that does not support sticky sessions. Documentation reference: <a href="https://flask-socketio.readthedocs.io/en/latest/#gunicorn-web-server" rel="nofollow">https://flask-socketio.readthedocs.io/en/latest/#gunicorn-web-server</a>.</p> <p>Instead, run several gunicorn instances, each with one worker, and then set up nginx to do the load balancing, using the <code>ip_hash</code> method so that sessions are sticky.</p> <p>Also, in case you are not aware, if you run multiple servers you need to also run a message queue, so that the processes can coordinate. This is also covered in the documentation link above.</p>
1
2016-07-29T00:14:27Z
[ "python", "nginx", "websocket", "socket.io", "gunicorn" ]
Python: __add__ and +, different behavior with float and integer
38,624,450
<p>When adding an integer value to a float value, I realized that <code>__add__</code> method is working fine if called on float, such as this:</p> <pre><code>&gt;&gt;&gt; n = 2.0 &gt;&gt;&gt; m = 1 &gt;&gt;&gt; n.__add__(m) 3.0 </code></pre> <p>but not if called on an integer:</p> <pre><code>&gt;&gt;&gt; m.__add__(n) NotImplemented </code></pre> <p>At first I thought that <code>__add__</code> was just being implemented differently for <code>int</code> and <code>float</code> types (like float types accepting to be added to int types, but not the opposite). Then I noticed that everything works fine if I use the + operator instead:</p> <pre><code>&gt;&gt;&gt; n + m 3.0 &gt;&gt;&gt; m + n 3.0 </code></pre> <p>Does anybody know why this is happening? Are <code>__add__</code> and <code>+</code> not deeply related to each other?</p>
4
2016-07-27T22:49:44Z
38,624,533
<p><code>a + b</code> does not directly translate to <code>a.__add__(b)</code>. It also tries <code>b.__radd__(a)</code> if <code>a.__add__</code> doesn't exist or returns <code>NotImplemented</code>, or if <code>b</code> is an instance of a subtype of <code>a</code>'s type.</p>
6
2016-07-27T22:58:35Z
[ "python", "floating-point", "integer", "add" ]
Python use commands when running script
38,624,456
<p>I'm writing a script in python and I need to do something like this:</p> <p><code>python myscript.py command1 --commandarg1 --commandarg2</code></p> <p><code>python myscript.py --scriptargument1 --scriptargument2 command2 --commandarg1 --commandarg2 --commandarg3</code></p> <p>Is this possible using <code>argparse</code>?</p>
-1
2016-07-27T22:49:55Z
38,630,028
<p>Yes the argparse module is exactly that what you are looking for. </p> <p>visit this page to get the informations how to work with it:</p> <p><a href="https://docs.python.org/3/library/argparse.html" rel="nofollow">https://docs.python.org/3/library/argparse.html</a></p>
1
2016-07-28T07:42:18Z
[ "python" ]
Out of memory with Python but OK with Matlab while displaying the same 2D data as image
38,624,495
<p>I have a 2D array to display as image (it is 500 by 20 000). </p> <p>Python:</p> <pre><code>import numpy as np from matplotlib import pyplot as plt spect_data = np.loadtxt('some_data.txt') plt.figure(figsize=(12,9)) plt.imshow(spect_data,aspect='auto') plt.colorbar() plt.show() </code></pre> <p>Matlab:</p> <pre><code>spect_data=load('some_data.txt'); imagesc(spect_data) </code></pre> <p>Here's the error I get (sorry I wasn't clear about my problem the first time):</p> <blockquote> <p> Traceback (most recent call last):</p> <p>File "C:\Users\User\Anaconda\lib\site-packages\IPython\core\formatters.py", line 339, in <strong>call</strong> return printer(obj)</p> <p>File "C:\Users\User\Anaconda\lib\site-packages\IPython\core\pylabtools.py", line 228, in png_formatter.for_type(Figure, lambda fig: print_figure(fig, 'png', **kwargs))</p> <p>File "C:\Users\User\Anaconda\lib\site-packages\IPython\core\pylabtools.py", line 119, in print_figure fig.canvas.print_figure(bytes_io, **kw)</p> <p>File "C:\Users\User\Anaconda\lib\site-packages\matplotlib\backend_bases.py", line 2180, in print_figure **kwargs)</p> <p>File "C:\Users\User\Anaconda\lib\site-packages\matplotlib\backends\backend_agg.py", line 527, in print_png FigureCanvasAgg.draw(self)</p> <p>File "C:\Users\User\Anaconda\lib\site-packages\matplotlib\backends\backend_agg.py", line 474, in draw self.figure.draw(self.renderer)</p> <p>File "C:\Users\User\Anaconda\lib\site-packages\matplotlib\artist.py", line 61, in draw_wrapper draw(artist, renderer, *args, **kwargs)</p> <p>File "C:\Users\User\Anaconda\lib\site-packages\matplotlib\figure.py", line 1159, in draw func(*args)</p> <p>File "C:\Users\User\Anaconda\lib\site-packages\matplotlib\artist.py", line 61, in draw_wrapper draw(artist, renderer, *args, **kwargs)</p> <p>File "C:\Users\User\Anaconda\lib\site-packages\matplotlib\axes_base.py", line 2324, in draw a.draw(renderer)</p> <p>File "C:\Users\User\Anaconda\lib\site-packages\matplotlib\artist.py", line 61, in draw_wrapper draw(artist, renderer, *args, **kwargs)</p> <p>File "C:\Users\User\Anaconda\lib\site-packages\matplotlib\image.py", line 389, in draw im = self.make_image(renderer.get_image_magnification())</p> <p>File "C:\Users\User\Anaconda\lib\site-packages\matplotlib\image.py", line 624, in make_image transformed_viewLim)</p> <p>File "C:\Users\User\Anaconda\lib\site-packages\matplotlib\image.py", line 238, in _get_unsampled_image x = (x * 255).astype(np.uint8)</p> <p>MemoryError</p> </blockquote>
-1
2016-07-27T22:54:36Z
38,624,619
<p>I'm not sure this will solve your problem, but you seem to have the data in memory several times - as a numpy array, as a list of floats, and as a list of strings.</p> <p>If you only need the numpy array, you could use </p> <pre><code>np.loadtxt </code></pre> <p>or </p> <pre><code>np.fromfile </code></pre> <p>if you need more control over how the data is read.</p> <p>This assumes (you do not specify) that the data is in an ASCII file. For a more specific answer, you should post your code so people can see what you are doing and where the problem might be.</p>
2
2016-07-27T23:09:06Z
[ "python", "matlab", "matplotlib" ]
Taking identical 1st element of a list and assigning it as 1st element of the list in python
38,624,557
<p>I am trying to Taking identical 1st element of a list and assigning it as 1st element of the list. I was told it can be done by using defaultdict from collections module but is there a way i can do this without using the Collections library.</p> <p>What i have:</p> <pre><code>mapping = [['Tom', 'BTPS 1.500 625', 0.702604], ['Tom', 'BTPS 2.000 1225', 0.724939], ['Max', 'OBL 0.0 421', 0.766102], ['Max', 'DBR 3.250 721', 0.887863]] </code></pre> <p>What i am looking to do:</p> <pre><code>mapping = [['Tom',[ 'BTPS 1.500 625', 0.702604], [ 'BTPS 2.000 1225', 0.724939]],['Max',[ 'OBL 0.0 421', 0.766102],['DBR 3.250 721', 0.887863]]] </code></pre>
0
2016-07-27T23:01:16Z
38,624,593
<p>You should use a <em>dict</em>/<a href="https://docs.python.org/2/library/collections.html#collections.defaultdict" rel="nofollow">defaultdict</a> to group the data by name, using the first element which is the key as the name, slicing the rest of the data and appending that as a value:</p> <pre><code>from collections import defaultdict d = defaultdict(list) for sub in mapping: d[sub[0]].append(sub[1:]) print(d) </code></pre> <p>Which would give you:</p> <pre><code>defaultdict(&lt;type 'list'&gt;, {'Max': [['OBL 0.0 421', 0.766102], ['DBR 3.250 721', 0.887863]], 'Tom': [['BTPS 1.500 625', 0.702604], ['BTPS 2.000 1225', 0.724939]]}) </code></pre> <p>Or if the order matters, use an <a href="https://docs.python.org/2/library/collections.html#collections.OrderedDict" rel="nofollow"><em>OrderedDict</em></a>:</p> <pre><code>from collections import OrderedDict d = OrderedDict() for sub in mapping: d.setdefault(sub[0],[]).append(sub[1:]) </code></pre> <p>That gives you:</p> <pre><code>OrderedDict([('Tom', [['BTPS 1.500 625', 0.702604], ['BTPS 2.000 1225', 0.724939]]), ('Max', [['OBL 0.0 421', 0.766102], ['DBR 3.250 721', 0.887863]])]) </code></pre> <p>Without any imports, just use a regular dict again using <a href="http://www.tutorialspoint.com/python/dictionary_setdefault.htm" rel="nofollow">dict.setdefault</a>:</p> <pre><code>d = {} for sub in mapping: d.setdefault(sub[0],[]).append(sub[1:]) print(d) </code></pre> <p>Using setdefault, if the key is not in the dict it gets added with a list as the value, if it does exist it just appends the value.</p>
1
2016-07-27T23:06:36Z
[ "python" ]
Taking identical 1st element of a list and assigning it as 1st element of the list in python
38,624,557
<p>I am trying to Taking identical 1st element of a list and assigning it as 1st element of the list. I was told it can be done by using defaultdict from collections module but is there a way i can do this without using the Collections library.</p> <p>What i have:</p> <pre><code>mapping = [['Tom', 'BTPS 1.500 625', 0.702604], ['Tom', 'BTPS 2.000 1225', 0.724939], ['Max', 'OBL 0.0 421', 0.766102], ['Max', 'DBR 3.250 721', 0.887863]] </code></pre> <p>What i am looking to do:</p> <pre><code>mapping = [['Tom',[ 'BTPS 1.500 625', 0.702604], [ 'BTPS 2.000 1225', 0.724939]],['Max',[ 'OBL 0.0 421', 0.766102],['DBR 3.250 721', 0.887863]]] </code></pre>
0
2016-07-27T23:01:16Z
38,624,622
<p>You can loop over the names in mapping and add to dictionary. </p> <pre><code>mapping = [['Tom', 'BTPS 1.500 625', 0.702604], ['Tom', 'BTPS 2.000 1225', 0.724939], ['Max', 'OBL 0.0 421', 0.766102], ['Max', 'DBR 3.250 721', 0.887863]] #using dictionary to store output mapping_dict=dict() for items in mapping: if items[0] in mapping_dict: mapping_dict[items[0]].append([items[1],items[2]]) else: mapping_dict[items[0]]=[items[1],items[2]] print mapping_dict Output: {'Max': ['OBL 0.0 421', 0.766102, ['DBR 3.250 721', 0.887863]], 'Tom': ['BTPS 1.500 625', 0.702604, ['BTPS 2.000 1225', 0.724939]]} </code></pre>
0
2016-07-27T23:09:11Z
[ "python" ]
Unable to parse function declaration with Python like syntax
38,624,749
<p>I am using <a href="https://fdik.org/pyPEG/index.html" rel="nofollow">pyPEG</a> to parse the declaration of a function. Currently I have this written:</p> <pre><code>from pypeg2 import attr, \ optional, \ csl, \ name, \ List, \ Namespace class Parameters(Namespace): grammar = optional(csl(name())) class Function(List): grammar = "def", name(), \ "(", attr("params", Parameters), "):" </code></pre> <p>So for example if I do:</p> <pre><code>&gt;&gt;&gt; import pypeg2 &gt;&gt;&gt; f = pypeg2.parse("def f(a, b):", Function) </code></pre> <p>I would expect <code>f.params</code> to contain <code>a</code> and <code>b</code> as parameters. Instead:</p> <pre><code>&gt;&gt;&gt; f.params Parameters([], name=Symbol('b')) </code></pre> <p>only <code>b</code> is found. Why is <code>b</code> the only found symbol?</p>
0
2016-07-27T23:23:29Z
39,922,979
<p>Because <code>name()</code> essential attach a matched <code>Symbol</code> to the <code>name</code> attr of the class. In your case the attachment of <code>b</code> overwrites <code>a</code>.</p> <p>The official doc lists the following:</p> <pre><code>class Parameter(object): grammar = attr("typing", Type), name() class Parameters(Namespace): grammar = csl(Parameter) </code></pre> <p>Here each <code>Parameter</code> has a <code>name</code>. The <code>Parameters</code> looks for the <code>name</code> attribute of the matched <code>Parameter</code> and put it into is internal <code>dict</code>. </p>
0
2016-10-07T17:35:55Z
[ "python", "pypeg" ]
Convert txt files in a folder to rows in csv file
38,624,751
<p>I have 100 txt files in a folder. I would like to create a csv file in which the content of each text file becomes a single row (actually, a single cell in a row) in this csv file. So, the result would be a csv file with 100 rows. </p> <p>I tried the following code:</p> <pre><code>import glob read_files = glob.glob('neg/*') with open("neg.csv", "wb") as outfile: for f in read_files: with open(f, "rb") as infile: for line in infile: outfile.write(line) </code></pre> <p>This create a csv with over thousands of rows since each txt file contains multiple paragraphs. Any suggestion?</p>
0
2016-07-27T23:23:38Z
38,624,876
<p>Try:</p> <pre><code>import glob import csv read_files = glob.glob('neg/*') with open("neg.csv", "wb") as outfile: w=csv.writer(outfile) for f in read_files: with open(f, "rb") as infile: w.writerow([line for line in infile]) </code></pre> <p>That makes each line a cell in the output and each file a row.</p> <p>If you want each cell to be the entire contents of the file, try:</p> <pre><code>import glob import csv read_files = glob.glob('neg/*') with open("neg.csv", "wb") as outfile: w=csv.writer(outfile) for f in read_files: with open(f, "rb") as infile: w.writerow(" ".join([line for line in infile])) </code></pre>
2
2016-07-27T23:37:56Z
[ "python", "python-2.7" ]
Convert txt files in a folder to rows in csv file
38,624,751
<p>I have 100 txt files in a folder. I would like to create a csv file in which the content of each text file becomes a single row (actually, a single cell in a row) in this csv file. So, the result would be a csv file with 100 rows. </p> <p>I tried the following code:</p> <pre><code>import glob read_files = glob.glob('neg/*') with open("neg.csv", "wb") as outfile: for f in read_files: with open(f, "rb") as infile: for line in infile: outfile.write(line) </code></pre> <p>This create a csv with over thousands of rows since each txt file contains multiple paragraphs. Any suggestion?</p>
0
2016-07-27T23:23:38Z
38,624,881
<p>Before writing each <code>line</code>, first do <code>line.replace('\n',' ')</code> to replace all new line characters with spaces. </p> <p>Obviously, adjust your newline character according to your OS.</p>
0
2016-07-27T23:38:12Z
[ "python", "python-2.7" ]
how to use variable from .yml file to .py file
38,624,773
<p>I have below two files one is .py file and other is .yml file as shown in image. In .py file I am using all variable that define in .yml file. Now I am looking for a solution about How I can pass this .yml file or how I can call or use the variables from .yml file to .py file. I have also marked my question in image to help to understand my question exactly.</p> <p>Any suggestion will be very helpful. </p> <p>Thanks</p> <p>-> Below is abcd.py file</p> <pre><code># abcd.py import pexpect import os import yaml from yaml import load from pexpect import pxssh import pdb with open('/home/asdf/Desktop/test.yml', 'rb') as f: var=yaml.load(f.read()) def example(gw_user,gw_password,gw_host): child = pexpect.spawn("ssh"+" "+gw_user+"@"+gw_host,timeout=30) child.expect('password') child.sendline(gw_password) #child.expect(self.gw_prompt) print 'connection established' child.expect('$') child.sendline('cd /usr/local/lib/python2.7/dist-packages/ostinato/') child.expect('ostinato') child.sendline('python example.py') print 'establishing connectivity with ostinato' child.expect('127.0.0.1') child.sendline('10.0.0.3') child.expect('Tx') child.sendline('1') child.expect('Rx') child.sendline('1') child.expect('$') child.sendline('exit') child.interact() #return self.gw_user #pdb.set_trace() answer=example(var[Username],var[Userpassword],var[Hostname]) print (answer) </code></pre> <p>-> Below is test.yml file</p> <pre><code>--- - Username: - xyz - Userpassword: - ubuntu - Hostname: - 10.0.0.3 </code></pre> <p>Also attached below screenshot for better understanding of my question.</p> <p><a href="http://i.stack.imgur.com/N75rX.png" rel="nofollow"><img src="http://i.stack.imgur.com/N75rX.png" alt="enter image description here"></a></p>
0
2016-07-27T23:27:03Z
38,625,701
<p>Because of the structure of the YAML document, <code>yaml.load()</code> returns a list of dictionaries:</p> <pre><code>with open('test.yml') as f: var = yaml.load(f) &gt;&gt;&gt; var [{'Username': ['xyz']}, {'Userpassword': ['ubuntu']}, {'Hostname': ['10.0.0.3']}] </code></pre> <p>This is not the most usable data structure; not only is there a list of single key dictionaries, but the values themselves are lists that must be indexed to get to their contents. A single dictionary would be more convenient so, if you are able to, you could change the YAML to:</p> <pre><code>--- Username: xyz Userpassword: ubuntu Hostname: 10.0.0.3 </code></pre> <p>which represents a single dictionary:</p> <pre><code>&gt;&gt;&gt; var {'Username': 'xyz', 'Userpassword': 'ubuntu', 'Hostname': '10.0.0.3'} </code></pre> <p>Now it's easy to pass these values to your function:</p> <pre><code>answer = example(var['Username'], var['Userpassword'], var['Hostname']) </code></pre> <hr> <p>If you can't change the YAML file, then you can first make a single dictionary out of the data, and then use that to call the function as above:</p> <pre><code>with open('test.yml') as f: var = yaml.load(f) var = {k:v[0] for d in var for k,v in d.items()} answer = example(var['Username'], var['Userpassword'], var['Hostname']) </code></pre> <p>Here the line <code>var = {k:v[0] for d in var for k,v in d.items()}</code> is a dictionary comprehension that converts the list of single-key dictionaries into a single multi-key dictionary.</p>
1
2016-07-28T01:27:08Z
[ "python", "yaml" ]
how to use variable from .yml file to .py file
38,624,773
<p>I have below two files one is .py file and other is .yml file as shown in image. In .py file I am using all variable that define in .yml file. Now I am looking for a solution about How I can pass this .yml file or how I can call or use the variables from .yml file to .py file. I have also marked my question in image to help to understand my question exactly.</p> <p>Any suggestion will be very helpful. </p> <p>Thanks</p> <p>-> Below is abcd.py file</p> <pre><code># abcd.py import pexpect import os import yaml from yaml import load from pexpect import pxssh import pdb with open('/home/asdf/Desktop/test.yml', 'rb') as f: var=yaml.load(f.read()) def example(gw_user,gw_password,gw_host): child = pexpect.spawn("ssh"+" "+gw_user+"@"+gw_host,timeout=30) child.expect('password') child.sendline(gw_password) #child.expect(self.gw_prompt) print 'connection established' child.expect('$') child.sendline('cd /usr/local/lib/python2.7/dist-packages/ostinato/') child.expect('ostinato') child.sendline('python example.py') print 'establishing connectivity with ostinato' child.expect('127.0.0.1') child.sendline('10.0.0.3') child.expect('Tx') child.sendline('1') child.expect('Rx') child.sendline('1') child.expect('$') child.sendline('exit') child.interact() #return self.gw_user #pdb.set_trace() answer=example(var[Username],var[Userpassword],var[Hostname]) print (answer) </code></pre> <p>-> Below is test.yml file</p> <pre><code>--- - Username: - xyz - Userpassword: - ubuntu - Hostname: - 10.0.0.3 </code></pre> <p>Also attached below screenshot for better understanding of my question.</p> <p><a href="http://i.stack.imgur.com/N75rX.png" rel="nofollow"><img src="http://i.stack.imgur.com/N75rX.png" alt="enter image description here"></a></p>
0
2016-07-27T23:27:03Z
38,667,100
<h2>what if my .yum file has multiple values in list such as</h2> <pre><code>Username: - asdf - xyz Userpassword: - ubuntu - linux Hostname: - 10.0.0.3 - 10.0.0.4 </code></pre> <p>Then how the code work? because here I am using only single dictionary having multiple values in list.</p>
0
2016-07-29T20:37:08Z
[ "python", "yaml" ]
Nested `ImportError` on Py3 but not on Py2
38,624,810
<p>I'm having trouble understanding how nested imports work in a python project. For example:</p> <pre><code>test.py package/ __init__.py package.py subpackage/ __init__.py </code></pre> <p><code>test.py</code>:</p> <pre><code>import package </code></pre> <p><code>package/__init__.py</code>:</p> <pre><code>from .package import functionA </code></pre> <p><code>package/package.py</code>:</p> <pre><code>import subpackage def functionA(): pass </code></pre> <p>In Python 3.5 when I run <code>test.py</code> I get the following error, but no error in Python 2.7:</p> <pre><code>C:\Users\Patrick\Anaconda3\python.exe C:/Users/Patrick/Desktop/importtest/test.py Traceback (most recent call last): File "C:/Users/Patrick/Desktop/importtest/test.py", line 1, in &lt;module&gt; import package File "C:\Users\Patrick\Desktop\importtest\package\__init__.py", line 1, in &lt;module&gt; from .package import functionA File "C:\Users\Patrick\Desktop\importtest\package\package.py", line 1, in &lt;module&gt; import subpackage ImportError: No module named 'subpackage' </code></pre> <p>However if I run <code>package.py</code> with Python 3.5. I get no error at all.</p> <p>This seems strange to me as when <code>package.py</code> is run on its own the line <code>import subpackage</code> works, but with it is being 'run' (don't know if this is the right terminology here) through the nested import, the same line cannot find <code>subpackage</code>.</p> <p>Why are there differences between Python 2.7 and 3.5 in this case and how can this be resolved in a way that works for both 2.7.x and 3.x?</p> <p>I think this might be due to the fact that <code>import subpackage</code> in the nested import counts as an implicit relative import in the nested import but not when <code>package.py</code> is run directly, but if I do <code>import .subpackage</code> instead, I get this error on both 2.7 and 3.5:</p> <pre><code>C:\Users\Patrick\Anaconda3\python.exe C:/Users/Patrick/Desktop/importtest/test.py Traceback (most recent call last): File "C:/Users/Patrick/Desktop/importtest/test.py", line 1, in &lt;module&gt; import package File "C:\Users\Patrick\Desktop\importtest\package\__init__.py", line 1, in &lt;module&gt; from .package import functionA File "C:\Users\Patrick\Desktop\importtest\package\package.py", line 1 import .subpackage ^ SyntaxError: invalid syntax </code></pre>
0
2016-07-27T23:32:10Z
38,624,831
<p>You should use:</p> <pre><code>from . import subpackage </code></pre> <p>in <code>package/package.py</code>.</p>
2
2016-07-27T23:34:38Z
[ "python", "python-2.7", "python-3.x", "import", "packages" ]
Using argparse to overwrite variables depending on flags, use the default values if no args given (python)
38,624,818
<p>I have a program that stores a few important variables as strings that are necessary for the program to operate properly: <code>DeviceNumber</code>, <code>IPAddress</code>, and <code>Port</code>. These variables are stored in a file, which is loaded by the program.</p> <p>For debugging purposes, I would like to be able to quickly overwrite the files with command line arguments. The args would all be optional, and if not used then it just uses the variables taken out of the file.</p> <p>I can do simple positional args using something like <code>DeviceNumber = sys.args[1]</code>, and only overwrite vars if the args are present, but this has the problem of not being able to handle if you enter the variables in the wrong order, or if you enter, say, the <code>IPAddress</code> and <code>Port</code> but not the <code>DeviceNumber</code>.</p> <p>I have been reading through the pyDocs <a href="https://docs.python.org/2/howto/argparse.html" rel="nofollow">argparse Tutorial</a> and documentation, but it does not seem terribly useful for what I need - it covers mandatory args, and optional flags, but does not seem to allow optional args that depend on a flag to denote their purpose. <strong>EDIT:</strong> <em>Turns out it does, but the example is not very obvious, so I missed it.</em> Similarly I have had trouble finding applicable questions here on SE. </p> <p>In short, given a program like</p> <pre><code>#Default Names loaded from file DeviceNumber = "2000" IPAddress = "159.142.32.30" Port = 80 #if command line args entered: #overwrite default vars with arg corresponding to each one #this probably involves argparse, but I don't know how print "DNumber:"+DeviceNumber+" IP:"+IPAddress+" Port:"+Port </code></pre> <p>Some examples with different cmd line inputs/outputs would be:</p> <p>All values are defaults</p> <pre><code>$ python myfile.py DNumber:2000 IP:159.142.32.30 Port:80 </code></pre> <p>All values are overridden</p> <pre><code>$ python myfile.py -n 1701 -ip 120.50.60.1 -p 3000 DNumber:1701 IP:120.50.60.1 Port:3000 </code></pre> <p>Default <code>DNumber</code>, Override <code>IPAddress</code> + <code>Port</code>. Args were specified in different order.</p> <pre><code>$ python myfile.py -p 123 -ip 124.45.67.89 DNumber:2000 IP:124.45.67.89 Port:123 </code></pre> <p>Default <code>DNumber</code> and <code>IPAddress</code>, Override <code>Port</code></p> <pre><code>$ python myfile.py -p 500 DNumber:2000 IP:159.142.32.30 Port:500 </code></pre> <p>You get the idea...</p> <p>for the syntax of the flag/args relationship, I am also not sure if there is a specific syntax python needs you to use (i.e. <code>-p 500</code> vs. <code>-p500</code> v <code>-p=500</code>)</p>
0
2016-07-27T23:32:47Z
38,625,043
<p>There's a few ways to define default values for arguments specified by <a href="https://docs.python.org/3/library/argparse.html" rel="nofollow"><code>argparse</code></a>. When adding arguments to your parser, you can specify a default value. Simply:</p> <pre class="lang-py prettyprint-override"><code>import argparse parser = argparse.ArgumentParser() parser.add_argument("-p", "--port", dest="port", default=500, type=int, help="specify port") args = parser.parse_args() print "You've selected port: %d" % (args.port) </code></pre> <p>From the above example, it is trivial to extend to allow additional default functionality. Note that <code>dest="port"</code> is already by default due to the naming of the long argument <code>--port</code>. Like so:</p> <pre class="lang-py prettyprint-override"><code>parser.add_argument("-p", "--port", dest="port", default=None, type=int, help="specify port") args = parser.parse_args() if args.port is None: port = read_port_from_file() print "No optional port specified. Reading value from file." print "You've selected port: %d" % (args.port) </code></pre>
2
2016-07-27T23:57:28Z
[ "python", "argparse" ]
Numpy strange behavior - sanity check. How is this possible?
38,624,827
<p>I'm no Python expert by any stretch of the imagination, but this one has me stumped. Either that or I'm missing something completely obvious. It must be one of the two.</p> <p>I have two numpy arrays, <code>a</code> and <code>b</code>. <code>a</code> should be a proper subset of <code>b</code>. To confirm this I produce the set difference:</p> <pre><code>&gt;&gt;&gt; np.setdiff1d(a, b) array([], dtype=float64) </code></pre> <p>as expected. <code>a</code> is therefore a subset of <code>b</code>. Unless my understanding of <code>setdiff1d</code> is wrong, which I suppose it could be, but I reread the documentation and it states that <code>setdiff1d</code> returns a:</p> <blockquote> <p>Sorted 1D array of values in ar1 that are not in ar2.</p> </blockquote> <p>Ok, here's where something strange happens. I have some value <code>p</code>. The following should be a true statement if <code>a</code> really is a subset of <code>b</code>: <strong><em>if <code>p</code> is in <code>a</code>, then <code>p</code> is also in <code>b</code></em></strong></p> <p>When attempting to confirm this, I get:</p> <pre><code>&gt;&gt;&gt; p in a True &gt;&gt;&gt; p in b False </code></pre> <p>So I'm not sure exactly what's going on, and I was hoping someone would point at my stupid mistake and laugh.</p>
2
2016-07-27T23:33:44Z
38,624,919
<p><code>setdiff1d</code> and your other methods check number for <em>exact</em> equality. Due to floating point errors, it is very possible that your numbers aren't <em>exactly</em> equal. If you want to do floating point comparisons, you should instead use a very small epsilon.</p> <pre><code>if abs(a - b) &lt; 1e-12: disp('equal!') </code></pre>
1
2016-07-27T23:42:56Z
[ "python", "arrays", "numpy" ]
Maximum recursion depth exceeded, but only when using a decorator
38,624,852
<p>I'm writing a program to calculate Levenshtein distance in Python. I implemented memoization because I am running the algorithm recursively. My original function implemented the memoization in the function itself. Here's what it looks like:</p> <pre><code># Memoization table mapping from a tuple of two strings to their Levenshtein distance dp = {} # Levenshtein distance algorithm def lev(s, t): # If the strings are 0, return length of other if not s: return len(t) if not t: return len(s) # If the last two characters are the same, no cost. Otherwise, cost of 1 if s[-1] is t[-1]: cost = 0 else: cost = 1 # Save in dictionary if never calculated before if not (s[:-1], t) in dp: dp[(s[:-1], t)] = lev(s[:-1], t) if not (s, t[:-1]) in dp: dp[(s, t[:-1])] = lev(s, t[:-1]) if not (s[:-1], t[:-1]) in dp: dp[(s[:-1], t[:-1])] = lev(s[:-1], t[:-1]) # Returns minimum chars to delete from s, t, and both return min(dp[(s[:-1], t)] + 1, dp[(s, t[:-1])] + 1, dp[(s[:-1], t[:-1])] + cost) </code></pre> <p>This works! However, I found a way to memoize <a href="http://www.python-course.eu/python3_memoization.php">using decorators</a>. I tried to apply this technique to my algorithm:</p> <pre><code># Memoization table mapping from a tuple of two strings to their Levenshtein distance def memoize(func): memo = {} def wrap(s, t): if (s, t) not in memo: memo[(s, t)] = func(s, t) return memo[(s, t)] return wrap # Levenshtein distance algorithm @memoize # lev = memoize(lev) def lev(s, t): # If the strings are 0, return length of other if not s: return len(t) if not t: return len(s) # If the last two characters are the same, no cost. Otherwise, cost of 1 if s[-1] is t[-1]: cost = 0 else: cost = 1 # Returns minimum chars to delete from s, t, and both return min(lev(s[:-1], t) + 1, lev(s, t[:-1]) + 1, lev(s[:-1], t[:-1]) + cost) </code></pre> <p>To me, this looks cleaner and less confusing. I thought that the two would be functionally equivalent, but when I ran the version with the decorator, I was surprised to find that I got a <code>RecursionError: maximum recursion depth exceeded</code>.</p> <p>What exactly am I missing? Is using the decorator not functionally equivalent? I attempted a fix by adding <code>sys.setrecursionlimit(1500)</code> and this works, but it is a hack and doesn't explain why the two function differently. </p> <p>NOTE: I am using one paragraph of lorem ipsum as my test strings for s and t from Wikipedia:</p> <blockquote> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est labour.</p> </blockquote> <p>I understand that for even longer strings, my first function will fail. I just want to know why the decorated one fails first. Thanks!</p>
6
2016-07-27T23:36:17Z
38,624,949
<p>Consider the stack frames (function calls) that are happening in your original code. They will look something like:</p> <pre><code>lev(s, t) -&gt; lev(..., ...) -&gt; lev(..., ...) -&gt; lev(..., ...) -&gt; lev(..., ...) </code></pre> <p>In you memoized version they appear as:</p> <pre><code>wraps(s, t) -&gt; lev(..., ...) -&gt; wraps(s, t) -&gt; lev(..., ...) -&gt; wraps(s, t) -&gt; lev(..., ...) -&gt; wraps(s, t) -&gt; lev(..., ...) -&gt; wraps(s, t) -&gt; lev(..., ...) </code></pre> <p>That is, your stack frame will be twice as big, as each "call" actually invokes two functions. Thus you will exhaust the stack frame limit earlier.</p>
7
2016-07-27T23:46:50Z
[ "python", "python-3.x", "recursion", "decorator", "memoization" ]
Maximum recursion depth exceeded, but only when using a decorator
38,624,852
<p>I'm writing a program to calculate Levenshtein distance in Python. I implemented memoization because I am running the algorithm recursively. My original function implemented the memoization in the function itself. Here's what it looks like:</p> <pre><code># Memoization table mapping from a tuple of two strings to their Levenshtein distance dp = {} # Levenshtein distance algorithm def lev(s, t): # If the strings are 0, return length of other if not s: return len(t) if not t: return len(s) # If the last two characters are the same, no cost. Otherwise, cost of 1 if s[-1] is t[-1]: cost = 0 else: cost = 1 # Save in dictionary if never calculated before if not (s[:-1], t) in dp: dp[(s[:-1], t)] = lev(s[:-1], t) if not (s, t[:-1]) in dp: dp[(s, t[:-1])] = lev(s, t[:-1]) if not (s[:-1], t[:-1]) in dp: dp[(s[:-1], t[:-1])] = lev(s[:-1], t[:-1]) # Returns minimum chars to delete from s, t, and both return min(dp[(s[:-1], t)] + 1, dp[(s, t[:-1])] + 1, dp[(s[:-1], t[:-1])] + cost) </code></pre> <p>This works! However, I found a way to memoize <a href="http://www.python-course.eu/python3_memoization.php">using decorators</a>. I tried to apply this technique to my algorithm:</p> <pre><code># Memoization table mapping from a tuple of two strings to their Levenshtein distance def memoize(func): memo = {} def wrap(s, t): if (s, t) not in memo: memo[(s, t)] = func(s, t) return memo[(s, t)] return wrap # Levenshtein distance algorithm @memoize # lev = memoize(lev) def lev(s, t): # If the strings are 0, return length of other if not s: return len(t) if not t: return len(s) # If the last two characters are the same, no cost. Otherwise, cost of 1 if s[-1] is t[-1]: cost = 0 else: cost = 1 # Returns minimum chars to delete from s, t, and both return min(lev(s[:-1], t) + 1, lev(s, t[:-1]) + 1, lev(s[:-1], t[:-1]) + cost) </code></pre> <p>To me, this looks cleaner and less confusing. I thought that the two would be functionally equivalent, but when I ran the version with the decorator, I was surprised to find that I got a <code>RecursionError: maximum recursion depth exceeded</code>.</p> <p>What exactly am I missing? Is using the decorator not functionally equivalent? I attempted a fix by adding <code>sys.setrecursionlimit(1500)</code> and this works, but it is a hack and doesn't explain why the two function differently. </p> <p>NOTE: I am using one paragraph of lorem ipsum as my test strings for s and t from Wikipedia:</p> <blockquote> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est labour.</p> </blockquote> <p>I understand that for even longer strings, my first function will fail. I just want to know why the decorated one fails first. Thanks!</p>
6
2016-07-27T23:36:17Z
38,624,952
<p>This <em>looks</em> like an infinite recursion issue, but it's not. You're just recursing really deeply, and the decorator makes it deeper.</p> <p>Instead of directly calling the <code>lev</code> function you defined, every call goes through <code>wrap</code>, and <code>wrap</code> calls <code>lev</code>. That makes your call stack twice as deep. You would have run into this problem anyway if you didn't use the decorator and your inputs got bigger.</p> <p>To fix this, you'll probably have to switch to a non-recursive program structure, either by using a bottom-up dynamic programming style or by converting the recursion to iteration and maintaining a stack manually.</p>
6
2016-07-27T23:47:03Z
[ "python", "python-3.x", "recursion", "decorator", "memoization" ]
Maximum recursion depth exceeded, but only when using a decorator
38,624,852
<p>I'm writing a program to calculate Levenshtein distance in Python. I implemented memoization because I am running the algorithm recursively. My original function implemented the memoization in the function itself. Here's what it looks like:</p> <pre><code># Memoization table mapping from a tuple of two strings to their Levenshtein distance dp = {} # Levenshtein distance algorithm def lev(s, t): # If the strings are 0, return length of other if not s: return len(t) if not t: return len(s) # If the last two characters are the same, no cost. Otherwise, cost of 1 if s[-1] is t[-1]: cost = 0 else: cost = 1 # Save in dictionary if never calculated before if not (s[:-1], t) in dp: dp[(s[:-1], t)] = lev(s[:-1], t) if not (s, t[:-1]) in dp: dp[(s, t[:-1])] = lev(s, t[:-1]) if not (s[:-1], t[:-1]) in dp: dp[(s[:-1], t[:-1])] = lev(s[:-1], t[:-1]) # Returns minimum chars to delete from s, t, and both return min(dp[(s[:-1], t)] + 1, dp[(s, t[:-1])] + 1, dp[(s[:-1], t[:-1])] + cost) </code></pre> <p>This works! However, I found a way to memoize <a href="http://www.python-course.eu/python3_memoization.php">using decorators</a>. I tried to apply this technique to my algorithm:</p> <pre><code># Memoization table mapping from a tuple of two strings to their Levenshtein distance def memoize(func): memo = {} def wrap(s, t): if (s, t) not in memo: memo[(s, t)] = func(s, t) return memo[(s, t)] return wrap # Levenshtein distance algorithm @memoize # lev = memoize(lev) def lev(s, t): # If the strings are 0, return length of other if not s: return len(t) if not t: return len(s) # If the last two characters are the same, no cost. Otherwise, cost of 1 if s[-1] is t[-1]: cost = 0 else: cost = 1 # Returns minimum chars to delete from s, t, and both return min(lev(s[:-1], t) + 1, lev(s, t[:-1]) + 1, lev(s[:-1], t[:-1]) + cost) </code></pre> <p>To me, this looks cleaner and less confusing. I thought that the two would be functionally equivalent, but when I ran the version with the decorator, I was surprised to find that I got a <code>RecursionError: maximum recursion depth exceeded</code>.</p> <p>What exactly am I missing? Is using the decorator not functionally equivalent? I attempted a fix by adding <code>sys.setrecursionlimit(1500)</code> and this works, but it is a hack and doesn't explain why the two function differently. </p> <p>NOTE: I am using one paragraph of lorem ipsum as my test strings for s and t from Wikipedia:</p> <blockquote> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est labour.</p> </blockquote> <p>I understand that for even longer strings, my first function will fail. I just want to know why the decorated one fails first. Thanks!</p>
6
2016-07-27T23:36:17Z
38,625,382
<p>Trying to understand your code, I made some modifications. Nothing big, just a matter of preference.</p> <p>I only changed one line:</p> <pre><code>if s[-1] is t[-1]: </code></pre> <p>for this one</p> <pre><code>if s[-1] == t[-1]: </code></pre> <p>As is, your code runs without any recursion problem</p> <p><strong>EDIT</strong> Testing it with the whole string you are using, I ran into recursion limit problem too. Definitely, it goes deep.</p> <p>Add these 2 lines:</p> <pre><code>import sys sys.setrecursionlimit(10000) def memoize(func): memo = {} def wrap(s, t): if (s, t) not in memo: memo[(s, t)] = func(s, t) return memo[(s, t)] return wrap @memoize def lev(s, t): len_s, len_t = len(s), len(t) if len_s==0: return len_t if len_t==0: return len_s cost = 0 if s[-1] == t[-1] else 1 return min(lev(s[:-1], t) + 1, lev(s, t[:-1]) + 1, lev(s[:-1], t[:-1]) + cost) s = "Lorem ibsum +++" t = "Loren ipsum ..." print(lev(s, t)) # 5 </code></pre> <p>Other than that, because you are using Python 3 (as I see in the question tag), you could use the <code>functools.lru_cache</code> instead of a custom <code>memoize</code> function:</p> <pre><code>from functools import lru_cache @lru_cache(maxsize=None) def lev(s, t): ... ... </code></pre>
4
2016-07-28T00:41:31Z
[ "python", "python-3.x", "recursion", "decorator", "memoization" ]
GUI, Buttons not displaying in window
38,624,875
<p>For my homework, I have to create a widget. I'm very new to this. I'm trying to get my buttons to show up. I have tried packing them, but I don't know what I'm doing wrong. Here is what I have.</p> <pre><code>from tkinter import * import turtle main = Tk() main.title("TurtleApp") class turtleApp: def __init_(self): self.main = main self.step = 10 self.turtle = turtle.Turtle() self.window = turtle.Screen() self.createDirectionPad def createDirectionPad(self): mainFrame = Frame(main) mainFrame.pack() button1 = Button(mainFrame,text = "left", fg="red") button2 = Button(mainFrame,text = "right", fg="red") button3 = Button(mainFrame,text = "up", fg="red") button4= Button(mainFrame,text = "down", fg="red") button1.pack() button2.pack() button3.pack() button4.pack() main.mainloop() </code></pre>
0
2016-07-27T23:37:50Z
38,624,891
<p>First of all your indentation is off, but once you fix that, you never actually create an instance of your <code>turtleApp</code> class, so none of that code ever gets executed leaving you with an empty GUI.</p> <pre><code># Actually create a turtleApp instance which adds the buttons app = turtleApp() # Enter your main event loop main.mainloop() </code></pre> <p>You also need to actually <em>call</em> <code>createDirectionPad</code> within <code>__init__</code> using explicit <code>()</code>. As it is, <code>self.createDirectionPad</code> (without the <code>()</code>) just creates a reference to the method and doesn't actually call it.</p> <pre><code>def __init__(self): # other stuff self.createDirectionPad() </code></pre> <p><strong>Update</strong></p> <p>You also have a typo in your <code>__init__</code> function declaration. You are missing the final <code>_</code> in <code>__init__</code></p>
2
2016-07-27T23:39:23Z
[ "python", "tkinter" ]
401 error python MongoDB connection
38,624,903
<p>I'm trying to set a connection between Python and MongoDB to store tweets. My problem is that I get 401 in each request with <code>Mylistener</code>. Could you please help to fix this ?</p> <pre><code>class MyListener(StreamListener): def __init__(self, start_time, time_limit=60): self.time = start_time self.limit = time_limit self.tweet_data = [] def on_data(self, data): while (time.time() - self.time)&lt;self.limit: try: client = MongoClient('localhost',27017) client.server_info() db = client.tweets_db collection = db.collect_tweets tweet = json.loads(data) collect_tweets.insert(tweet) return True except BaseException as e: print("Error on_data: %s" % str(e)) return True def on_error(self, status): print(status) Keywords_list=['word1','word2','word3'] twitter_stream = Stream(auth, MyListener(start_time, time_limit)) </code></pre>
0
2016-07-27T23:41:40Z
38,625,250
<p>Sounds like you need to authenticate with the database right after creating the new MongoClient instance:</p> <pre><code>client.tweets_db.authenticate('user', 'password') </code></pre> <p>See <a href="https://api.mongodb.com/python/current/examples/authentication.html" rel="nofollow">here</a> for more detailed examples</p>
0
2016-07-28T00:25:41Z
[ "python", "mongodb" ]
Why are these functions not drawing on the same graph together?
38,624,967
<p>I'd like to be able to click on the two buttons generated in the IPython GUI and then generate a total of 6 points on the same graph. However, right now clicking the two buttons does not create the 6 points, and only creates the graph made by the first button to be clicked. What am I doing wrong?</p> <pre><code>import matplotlib.pyplot as plt from matplotlib.patches import Rectangle from ipywidgets.widgets import Button from IPython.display import display class Test(object): def __init__(self): self.figure = plt.figure() self.ax = self.figure.gca() self.button = Button(description = "Draw new points.") display(self.button) self.button.on_click(self.button_clicked) self.button2 = Button(description = "Draw more points.") display(self.button2) self.button2.on_click(self.button_clicked2) def button_clicked(self, event): self.ax.scatter([1,2,8], [6,5,4]) self.figure.canvas.draw() plt.show() def button_clicked2(self, event): self.ax.scatter([1,0,5], [3,8,3]) self.figure.canvas.draw() plt.show() test = Test() </code></pre>
1
2016-07-27T23:48:51Z
38,625,607
<p>I played around with your code and got it to work by adding %matplotlib notebook and removing calls to plt.show().</p> <pre><code>%matplotlib notebook import matplotlib.pyplot as plt from matplotlib.patches import Rectangle from ipywidgets.widgets import Button from IPython.display import display class Test(object): def __init__(self): plt.ion() self.figure = plt.figure() self.ax = self.figure.gca() self.button = Button(description = "Draw new points.") display(self.button) self.button.on_click(self.button_clicked) self.button2 = Button(description = "Draw more points.") display(self.button2) self.button2.on_click(self.button_clicked2) def button_clicked(self, event): self.ax.scatter([1,2,8], [6,5,4]) self.figure.canvas.draw() def button_clicked2(self, event): self.ax.scatter([1,0,5], [3,8,3]) self.figure.canvas.draw() test = Test() </code></pre> <p>Make sure that you have the latest version of matplotlib installed. This functionality depends on the nbagg backend. See <a href="http://stackoverflow.com/questions/34486642/what-is-the-currently-correct-way-to-dynamically-update-plots-in-jupyter-ipython">this question</a> for more information.</p>
1
2016-07-28T01:13:44Z
[ "python", "matplotlib", "ipython" ]
Creating a dictionary from a list of strings
38,625,057
<p>I have a list of strings </p> <pre><code>list = ['2(a)', '2(b)', '3', '3(a)', '1d', '5'] </code></pre> <p>where it is intentional that the 1d, 3, and 5 don't involve parentheses.</p> <p>I would like to create a dictionary which looks like this:</p> <pre><code>dict = {'2': 'a', '2': 'b', '3': 'a', '1': 'd'} </code></pre> <p>or</p> <pre><code>dict = {'2': ['a', 'b'], '3': ['a'], '1': ['d']}. </code></pre> <p>Essentially, ignore those strings without a letter a-z. I've used regular expressions to extract from the top list the following:</p> <pre><code>['a', 'b', 'a', 'd'], </code></pre> <p>but this hasn't helped me much in forming my dictionary easily.</p> <p>Any help is much appreciated.</p>
0
2016-07-27T23:59:40Z
38,625,110
<p>Since a dictionary can't contain duplicate keys, use a <code>defaultdict</code>:</p> <pre><code>import collections l = ['2(a)', '2(b)', '3', '3(a)', '1c', '5'] d = collections.defaultdict(list) for item in l: num = ''.join(c for c in item if c.isdigit()) word = ''.join(c for c in item if c.isalpha()) if word and num: d[num].append(word) </code></pre> <p>Result:</p> <pre><code>&gt;&gt;&gt; print(d) defaultdict(&lt;class 'list'&gt;, {'2': ['a', 'b'], '1': ['c'], '3': ['a']}) </code></pre>
4
2016-07-28T00:05:42Z
[ "python", "regex", "string", "python-2.7", "dictionary" ]
Creating a dictionary from a list of strings
38,625,057
<p>I have a list of strings </p> <pre><code>list = ['2(a)', '2(b)', '3', '3(a)', '1d', '5'] </code></pre> <p>where it is intentional that the 1d, 3, and 5 don't involve parentheses.</p> <p>I would like to create a dictionary which looks like this:</p> <pre><code>dict = {'2': 'a', '2': 'b', '3': 'a', '1': 'd'} </code></pre> <p>or</p> <pre><code>dict = {'2': ['a', 'b'], '3': ['a'], '1': ['d']}. </code></pre> <p>Essentially, ignore those strings without a letter a-z. I've used regular expressions to extract from the top list the following:</p> <pre><code>['a', 'b', 'a', 'd'], </code></pre> <p>but this hasn't helped me much in forming my dictionary easily.</p> <p>Any help is much appreciated.</p>
0
2016-07-27T23:59:40Z
38,625,225
<p>This is a good time to use <code>setdefault()</code> for a <strong>dictionary</strong> to define the structure of your dictionary. The first part involves capturing the numbers from the elements using a regex that captures all numbers. That <code>list</code> is then concatenated using <code>join()</code>. </p> <p>We then extract only <strong>alphabet</strong> characters using either a <em>list comprehension</em> -> <code>[j for j in i if j.isalpha()]</code>, or pass as a <em>generator</em> <code>j for j in i if j.isalpha()</code> (<em>generator in our case, joining the elements as a</em> <code>string</code> <em>together once again</em>). </p> <p>Lastly a check to see that both <code>key</code> and <code>value</code> exist so that we can set our dictionary to be of this format -> <code>{ '' : [] , ...}</code></p> <pre><code>import re def to_dict(l): d = {} for i in l: key = re.findall(r'\d+', i) value = ''.join(j for j in i if j.isalpha()) if key and value: d.setdefault(''.join(key), []).append(value) return d </code></pre> <p><strong>Sample output:</strong></p> <pre><code>l = ['2(a)', '2(b)', '3', '3(a)', '1c', '5'] print to_dict(l) &gt;&gt;&gt; {'1': ['c'], '3': ['a'], '2': ['a', 'b']} </code></pre>
2
2016-07-28T00:21:48Z
[ "python", "regex", "string", "python-2.7", "dictionary" ]
Change some, but not all, pandas multiindex column names
38,625,102
<p>Suppose I have a data frame with multiindex column names that looks like this:</p> <pre><code> A B '1.5' '2.3' '8.4' b1 r1 1 2 3 a r2 4 5 6 b r3 7 8 9 10 </code></pre> <p>How would I change the just the column names under 'A' from strings to floats, without modifying 'b1', to get the following?</p> <pre><code> A B 1.5 2.3 8.4 b1 r1 1 2 3 a r2 4 5 6 b r3 7 8 9 10 </code></pre> <p>In the real use case, under 'A' there would be thousands of columns with names that should be floats (they represent the wavelengths for a spectrometer) and the data in the data frame represents multiple different observations. </p> <p>Thanks!</p>
0
2016-07-28T00:04:06Z
38,626,145
<pre><code># build the DataFrame (sideways at first, then transposed) arrays = [['A','A','A','B'],['1.5', '2.3', '8.4', 'b1']] tuples = list( zip(*arrays) ) data1 = np.array([[1,2,3,'a'], [4,5,6,'b'], [7,8,9,10]]) index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second']) df = pd.DataFrame(data1.T, index=index).T </code></pre> <p>Printing df.columns gives the existing column names. </p> <pre><code>Out[84]: MultiIndex(levels=[[u'A', u'B'], [u'1.5', u'2.3', u'8.4', u'b1']], labels=[[0, 0, 0, 1], [0, 1, 2, 3]], names=[u'first', u'second']) </code></pre> <p>Now change the column names</p> <pre><code># make new column titles (probably more pythonic ways to do this) A_cols = [float(i) for i in df['A'].columns] B_cols = [i for i in df['B'].columns] cols = A_cols + B_cols # set levels levels = [df.columns.levels[0],cols] df.columns.set_levels(levels,inplace=True) </code></pre> <p>Gives the following output</p> <pre><code>Out[86]: MultiIndex(levels=[[u'A', u'B'], [1.5, 2.3, 8.4, u'b1']], labels=[[0, 0, 0, 1], [0, 1, 2, 3]], names=[u'first', u'second']) </code></pre>
1
2016-07-28T02:24:54Z
[ "python", "pandas" ]
how to search for a text in a string and replace with its value
38,625,104
<p>I need to search for image_bid in string <code>s</code>and if exists need to replace that string with its value <code>DEBUG</code> in this case,I tried the following but doesn't seem to work,can anyone suggest how can I do that?</p> <pre><code>import re s = "cols/sel/Pkg/Bin/LA/${image_bid:DEBUG}/" match = re.search('image_bid:(\w+)',s) print match.group(1) if match: final_value = s.replace('image_bid:(\w+)',match.group(1)) print final_value MY OUTPUT:- cols/sel/Pkg/Bin/LA/${image_bid:DEBUG}/ Expected output:- cols/sel/Pkg/Bin/LA/DEBUG </code></pre>
1
2016-07-28T00:04:28Z
38,625,185
<blockquote> <p>The method replace() returns a copy of the string in which the occurrences of old have been replaced with new, optionally restricting the number of replacements to max.</p> </blockquote> <p>It doesn't seem like the <code>replace</code> method for string support regular expression, use <code>re.sub</code> instead:</p> <pre><code>if match: final_value = re.sub(r'\${image_bid:\w+}',match.group(1), s) print final_value # cols/sel/Pkg/Bin/LA/DEBUG/ </code></pre>
0
2016-07-28T00:16:29Z
[ "python" ]
how to search for a text in a string and replace with its value
38,625,104
<p>I need to search for image_bid in string <code>s</code>and if exists need to replace that string with its value <code>DEBUG</code> in this case,I tried the following but doesn't seem to work,can anyone suggest how can I do that?</p> <pre><code>import re s = "cols/sel/Pkg/Bin/LA/${image_bid:DEBUG}/" match = re.search('image_bid:(\w+)',s) print match.group(1) if match: final_value = s.replace('image_bid:(\w+)',match.group(1)) print final_value MY OUTPUT:- cols/sel/Pkg/Bin/LA/${image_bid:DEBUG}/ Expected output:- cols/sel/Pkg/Bin/LA/DEBUG </code></pre>
1
2016-07-28T00:04:28Z
38,625,190
<p>You probably want something like</p> <pre><code>final_value = re.sub(r'\$\{image_bid\:(\w+)\}/', r'\1', s) </code></pre>
0
2016-07-28T00:17:15Z
[ "python" ]
Suport Vector machine (SVM) training using multiple features
38,625,115
<p>I am trying to train my svm algorithm with a point dataset extracted from GPS. My data instances (e.g x1, x2, x3,... xn) have a set of attributes (speed, coordinates, etc). I consider the line between two data instances (points) as a segment and I am trying to train my algorithm using more than one features (attributes) and with a moving order. Considering I have my data in a CSV file, what I am trying to do is:</p> <pre><code>1st row: x1(speed, lon, lat), x2(speed,lon, lat), x3(speed,lon, lat) 2nd row:x2, x3, x4 3rd row: x3, x4, x5 </code></pre> <p>and so on.</p> <p>By doing this, I will train my algorithm to learn sequences, which is what I am trying to do. My question is; How will I train it in the form of sequence? and how this sequence will include more than one features?</p> <p>I am keen to use either R or Python, though I am more familiar with R. as far as I'm aware of the sklearn library in Python may be useful as well, but I do not understand the form that the training set has to have to train the svm. Any help would be much appreciated. Thanks</p>
0
2016-07-28T00:06:24Z
38,626,786
<p>after reading reading the description you gave to ali_m , why you choosed SVM? An alternative could be insted of using SVM(supervised learning) , use "anomaly detection"(unsupervised learning) where abnormal in your case would be an anomaly and you could vary the threshold and play with it.</p>
0
2016-07-28T03:50:02Z
[ "python", "svm" ]
Translate row in Python to JavaScript: [(M[i], k // M[i])]
38,625,204
<p>I'm trying to translate the following script into JavaScript. There is one row which I have no idea what it does, I'm suspecting push to the array.</p> <pre><code>def greedyCoinChanging(M, k): n = len(M) result = [] for i in xrange(n - 1, -1, -1): result += [(M[i], k // M[i])] // &lt;-- what the hell is this in JavaScript? k %= M[i] return result </code></pre>
1
2016-07-28T00:19:09Z
38,625,237
<p>In JavaScript, you don't have to use a tuple. You can just use an array.</p> <pre><code>result.push([M[i], Math.floor(k/M[i])]); </code></pre> <p>Also, the integer division (<code>//</code>) can become <code>Math.floor(k/M[i])</code>;</p>
1
2016-07-28T00:23:44Z
[ "javascript", "python" ]
Why pandas silently ignores .iloc[i, j] assignment with too many indices?
38,625,223
<p>Why does pandas behave differently when setting or getting items in a series with erroneous number of indexes:</p> <pre><code>df = pd.DataFrame({'a': [10]}) # df['a'] is a series, can be indexed with 1 index only # will raise IndexingError, as expected df['a'].iloc[0, 0] df['a'].loc[0, 0] # will raise nothing, not as expected df['a'].iloc[0, 0] = 1000 # equivalent to pass df['a'].loc[0, 0] = 1000 # equivalent to df['a'].loc[0] = 1000 # pandas version 0.18.1, python 3.5 </code></pre> <p>Edit: <a href="https://github.com/pydata/pandas/issues/13831" rel="nofollow">Reported</a>.</p>
5
2016-07-28T00:21:17Z
38,644,472
<h3>Getting values</h3> <p>If the key is a tuple (as in your example), then the <code>__getitem__</code> method of the superclass for the <code>loc</code> and <code>iloc</code> objects at some point calls <code>_has_valid_tuple(self, key)</code>.</p> <p>This method has the following code</p> <pre><code>for i, k in enumerate(key): if i &gt;= self.obj.ndim: raise IndexingError('Too many indexers') </code></pre> <p>This raises an <code>IndexingError</code> you would expect.</p> <h3>Setting values</h3> <p>The superclass's <code>__setitem__</code> makes a call to <code>_get_setitem_indexer</code> and in turn <code>_convert_to_indexer</code>.</p> <p>This superclass's implementation of <code>_convert_to_indexer</code> is a bit messy but in this case it returns a numpy array <code>[0, 0]</code>.</p> <p>The class of the iLoc indexer, however, overrides <code>_convert_to_indexer</code>. This method returns the original tuple...</p> <pre><code>def _convert_to_indexer(self, obj, axis=0, is_setter=False): ... elif self._has_valid_type(obj, axis): return obj </code></pre> <p>Now an <code>indexer</code> variable is a numpy array for the <code>.loc</code> case and tuple for the <code>.iloc</code> case. This causes the difference in setting behavior in the subsequent superclass call to <code>_setitem_with_indexer(indexer, value)</code>.</p>
1
2016-07-28T18:47:58Z
[ "python", "pandas" ]
How to use class based view in Django for html button?
38,625,337
<p>I wrote the following view:</p> <pre><code>class UserDeleteView(TemplateView): template_name = "user/user_delete.html" form_class = UserDeleteForm model = User def delete_my_account(self): user = get_user(self.request).user if user.is_authenticated(): logout(self.request) user.delete() return redirect('/') </code></pre> <p>1) How can I call that method in <code>user/user_delete.html</code> ?</p> <p>I think that my form_class attribute is not necessary since I use a <code>TemplateView</code>.</p> <p>2) How would the code look like to use the <code>UserDeleteView</code> for <code>forms.py</code>? How to create the Delete Button?</p>
0
2016-07-28T00:36:20Z
38,625,456
<p>It might not be the answer you are looking for, but you can use DeleteView instead of TemplateView which just needs a success url.</p> <p>You can look its default functions methods that can be used here : <a href="https://ccbv.co.uk/projects/Django/1.9/django.views.generic.edit/DeleteView/" rel="nofollow">DeleteView</a></p> <p>And Documentation here: <a href="https://docs.djangoproject.com/en/1.9/ref/class-based-views/generic-editing/#deleteview" rel="nofollow">Django Documentation on DeleteView</a></p> <pre><code>class UserDeleteView(LoginRequiredMixin, DeleteView): template_name = "user/user_delete.html" form_class = UserDeleteForm model = User def get_success_url(self): # logout(self.request) return redirect('/') </code></pre> <p>Not sure if this would work in case of deleting the logged in user. I apologize as i could have mentioned this briefly without giving code in a comment, but i don't have enough reputation for that.</p>
1
2016-07-28T00:53:36Z
[ "python", "django", "python-3.x", "button", "methods" ]
How to use class based view in Django for html button?
38,625,337
<p>I wrote the following view:</p> <pre><code>class UserDeleteView(TemplateView): template_name = "user/user_delete.html" form_class = UserDeleteForm model = User def delete_my_account(self): user = get_user(self.request).user if user.is_authenticated(): logout(self.request) user.delete() return redirect('/') </code></pre> <p>1) How can I call that method in <code>user/user_delete.html</code> ?</p> <p>I think that my form_class attribute is not necessary since I use a <code>TemplateView</code>.</p> <p>2) How would the code look like to use the <code>UserDeleteView</code> for <code>forms.py</code>? How to create the Delete Button?</p>
0
2016-07-28T00:36:20Z
38,626,827
<p>One way of doing it would be something like this</p> <pre><code>class UserDeleteView(View): def post(self, request, object_id, *args, **kwargs): '''retrieve the object for the given object_id and delete it''' return redirect(url_to_be_redirected_to) </code></pre> <p>This should be sufficient for a basic Django view. In your HTML template lets say you have a button for deleting the object and lets also say that it has <code>id</code> attribute set to <code>deleteButton</code>. You will have to make use of javascripting to initiate the delete. For eg, your button is like</p> <pre><code>&lt;a href="delete_url" id="deleteButton"&gt;Delete&lt;/a&gt; </code></pre> <p>So you can write something like this </p> <pre><code>$("body").on("click", "a#deleteButton", function(event){ event.preventDefault(); var url = $(this).attr("href"); var csrf = fetch_csrf_value_and_assign_here; $.post(url, {csrfmiddlewaretoken:csrf}, function(response){}); }); </code></pre> <p><strong>PS:</strong> This is a bare minimum way to do something you want. Also, it is not the only way. But this should give you another perspective to look at what you want to achieve.</p> <p><strong>Edit 1:</strong> A sample url config for the view I have presented.</p> <pre><code> url(r'delete/(?P&lt;object_id&gt;\d+)/$', views.UserDeleteView.as_view(), name='delete-user') </code></pre> <p>Then in your HTML, you can button like,</p> <pre><code>&lt;a href="{% url 'appname:delete-user' object_id_you_want_to_delete %}" id="deleteButton"&gt;Delete&lt;/a&gt; </code></pre> <p>You need to have <code>id</code> of the object you wish to delete in your template, which I am sure you do.</p>
1
2016-07-28T03:54:44Z
[ "python", "django", "python-3.x", "button", "methods" ]
Correct syntax for calling a group of objects in a list?
38,625,435
<p>I have a list with 1000 items in it but only want to call a certain range of them.</p> <pre><code>class myClass(): def event(self): #do stuff my_list = [myClass(i) for i in range(1000)] #incorrect part: my_list[0 - 10].event() </code></pre> <p>Meaning that I am trying to call "event" for only the first 9 objects. What would be the correct way to write this?</p>
-1
2016-07-28T00:50:38Z
38,625,457
<p>Do this:</p> <pre><code>for obj in my_list[:9]: obj.event() </code></pre> <p>Note since you just want the first 9 objects to be called, you need to use indexes 0-8 i.e. 0,1,2,3,4,5,6,7,8</p>
5
2016-07-28T00:53:37Z
[ "python" ]
Correct syntax for calling a group of objects in a list?
38,625,435
<p>I have a list with 1000 items in it but only want to call a certain range of them.</p> <pre><code>class myClass(): def event(self): #do stuff my_list = [myClass(i) for i in range(1000)] #incorrect part: my_list[0 - 10].event() </code></pre> <p>Meaning that I am trying to call "event" for only the first 9 objects. What would be the correct way to write this?</p>
-1
2016-07-28T00:50:38Z
38,625,460
<pre><code>[x.event() for x in my_list[:9]] </code></pre> <p>or</p> <pre><code>list(map(lambda x: x.event(), my_list[:9])) </code></pre> <p>or, as @khredos suggests,</p> <pre><code>for obj in my_list[:9]: obj.event() </code></pre> <p>If <code>myClass.event()</code> does return something (and you want to keep the result), the first is the most pythonic. If, on the other hand, <code>myClass.event()</code> involves side effects (and you do not want to keep the result, of course), go for the the third approach.</p>
3
2016-07-28T00:53:43Z
[ "python" ]
Does python run all computations in double percision?
38,625,448
<p>I know MatLab does everything in double, I heard about the similar thing for python but not quite sure. Can anyone confirm it with reference? Thanks!</p>
0
2016-07-28T00:53:09Z
38,625,477
<p>Well, that's a simplification.</p> <ul> <li><p>The <code>float</code> type in Python is double-precision.</p></li> <li><p>The <code>int</code> type has integer precision, but only limited by memory. Large numbers can have far more significant digits than a double float.</p></li> <li><p>When using NumPy, you may choose the precision you want.</p></li> </ul>
4
2016-07-28T00:56:47Z
[ "python", "numpy" ]
Python csv reader.next() vs next(reader)
38,625,485
<p>When reading files using the <code>csv</code> module, there are two ways to iterate through the generator returned by <code>csv.reader</code>.</p> <pre><code>with open('foo.csv') as f: reader = csv.reader(f) row1 = reader.next() row2 = next(reader) </code></pre> <p>Is there any difference between how <code>row1</code> and <code>row2</code> are obtained? Is one preferred over the other?</p>
1
2016-07-28T00:58:00Z
38,625,550
<p>In the beginning, the only option was to call <code>iterator.next()</code> on an iterator <code>iterator</code>. Python 2.6 introduced the builtin <code>next(iterator)</code>, which simply called <code>iterator.next()</code> under the hood. In Python 3, <code>next(iterator)</code> calls <code>iterator.__next__()</code>, and <code>iterator.next()</code> raises an <code>AttributeError</code>. So unless you are on a really old version of Python (in which case you should upgrade anyway), use the builtin.</p>
1
2016-07-28T01:06:08Z
[ "python", "csv" ]
shell multipipe broken with multiple python scripts
38,625,530
<p>I am trying to get the stdout of a python script to be shell-piped in as stdin to another python script like so:</p> <pre><code>find ~/test -name "*.txt" | python my_multitail.py | python line_parser.py </code></pre> <p>It should print an output but nothing comes out of it.</p> <p>Please note that this works:</p> <pre><code>find ~/test -name "*.txt" | python my_multitail.py | cat </code></pre> <p>And this works too:</p> <pre><code>echo "bla" | python line_parser.py </code></pre> <p>my_multitail.py prints out the new content of the .txt files:</p> <pre><code>from multitail import multitail import sys filenames = sys.stdin.readlines() # we get rid of the trailing '\n' for index, filename in enumerate(filenames): filenames[index] = filename.rstrip('\n') for fn, line in multitail(filenames): print '%s: %s' % (fn, line), sys.stdout.flush() </code></pre> <p>When a new line is added to the .txt file ("hehe") then my_multitail.py prints:</p> <blockquote> <p>/home/me/test2.txt: hehe</p> </blockquote> <p>line_parser.py simply prints out what it gets on stdin:</p> <pre><code>import sys for line in sys.stdin: print "line=", line </code></pre> <p>There is something I must be missing. Please community help me :)</p>
1
2016-07-28T01:03:32Z
38,627,080
<p>There's a hint if you run your <code>line_parser.py</code> interactively:</p> <pre><code>$ python line_parser.py a b c line= a line= b line= c </code></pre> <p>Note that I hit ctrl+D to provoke an EOF after entering the 'c'. You can see that it's slurping up all the input before it starts iterating over the lines. Since this is a pipeline and you're continuously sending output through to it, this doesn't happen and it never starts processing. You'll need to choose a different way of iterating over <code>stdin</code>, for example:</p> <pre><code>import sys line = sys.stdin.readline() while line: print "line=", line line = sys.stdin.readline() </code></pre>
3
2016-07-28T04:24:37Z
[ "python", "bash", "shell", "pipe" ]
Python Equivalence of the Scala Code in Spark
38,625,582
<p>I have this piece of code in Scala</p> <pre><code> val file = sc.textFile(filelocation) //Inital edge list that is to be passed to Iterate function var edges : RDD[(Int, Int)] = file.flatMap{ s =&gt; val nodes = s.split("\\s+") Seq((nodes(0).toInt, nodes(1).toInt)) } edges.collect() </code></pre> <p>I am reading a local file whose input is </p> <pre><code>1 0 0 3 3 4 2 4 </code></pre> <p>The output of the code is:</p> <pre><code>Array[(Int, Int)] = Array((1,0), (0,3), (3,4), (2,4)) </code></pre> <p>I want to achieve same thing in python. I am doing this right now</p> <pre><code>filelocation = "/FileStore/tables/nr8rkr051469528365715/cc_test-3be20.txt" file = sc.textFile(filelocation) def tokenize(text): row = text.split('\\s+') return row result = file.flatMap(tokenize) </code></pre> <p>And I am getting this as an output</p> <pre><code>Out[5]: [u'1 0', u'0 3', u'3 4', u'2 4'] </code></pre>
-3
2016-07-28T01:09:14Z
38,625,774
<p>Change the <code>flatMap</code> to <code>map</code></p> <p>This is going to work!</p>
0
2016-07-28T01:36:27Z
[ "python", "scala", "apache-spark", "pyspark", "databricks" ]
How can I parse a special XML format under Python?
38,625,639
<p>The data format looks like that:</p> <pre><code>&lt;doc&gt; &lt;url&gt;i am url&lt;/url&gt; &lt;docno&gt;01a064132d932277&lt;/docno&gt; &lt;contenttitle&gt;title&lt;/contenttitle&gt; &lt;content&gt;whatever the content is &lt;/content&gt; &lt;/doc&gt; ... &lt;doc&gt; &lt;url&gt;i am another url&lt;/url&gt; &lt;docno&gt;01a064132d932277&lt;/docno&gt; &lt;contenttitle&gt;title&lt;/contenttitle&gt; &lt;content&gt;whatever the content is &lt;/content&gt; &lt;/doc&gt; </code></pre> <p>So the whole document contains lots of small XML format content, more specifically, that's every 6 row comes an XML format. I try to use the lxml or Beautiful Soup, but they don't provide the API that read six rows each time.</p> <p>Also, there are more than one .txt in the folder.</p> <p>How can I solve that question?</p>
0
2016-07-28T01:17:50Z
38,625,826
<p>You could:</p> <ul> <li>read the file (raw text, unparsed) into a string</li> <li>append "<code>&lt;root&gt;</code>" to the beginning and "<code>&lt;/root&gt;</code>" to the end of the string</li> <li>then have BeautifulSoup parse the resulting string.</li> </ul> <p>Then each of the original <code>&lt;doc&gt;</code> elements would be one of the many children of <code>&lt;root&gt;</code>.</p>
3
2016-07-28T01:42:01Z
[ "python", "xml" ]
Using list.index() to find datetime.date object throws an error
38,625,664
<p>I have a list containing datetime.date() objects. I am trying to find the index of a specific date object. </p> <p>I tried this - </p> <pre><code>&gt;&gt; index = date_obj.index(datetime.date(2009, 1, 31)) &gt;&gt; *** TypeError: descriptor 'date' requires a 'datetime.datetime' object but received a 'int' </code></pre> <p>But when I tried this it worked -</p> <pre><code>&gt;&gt; index = date_obj.index(datetime.strptime("2009-01-31","%Y-%m-%d").date()) &gt;&gt; 10 </code></pre>
0
2016-07-28T01:21:13Z
38,625,675
<p>You imported <code>datetime.datetime</code> as <code>datetime</code></p> <pre><code>from datetime import datetime </code></pre> <p><code>datetime.date</code> is part of the base library, not <code>datetime.datetime</code></p> <p>You should just import <code>datetime</code> and use <code>datetime.datetime</code> and <code>datetime.date</code> explicitly or use something like the following to avoid these issues.</p> <pre><code>from datetime import datetime as dt </code></pre>
2
2016-07-28T01:23:25Z
[ "python", "list", "datetime", "python-datetime" ]
Using list.index() to find datetime.date object throws an error
38,625,664
<p>I have a list containing datetime.date() objects. I am trying to find the index of a specific date object. </p> <p>I tried this - </p> <pre><code>&gt;&gt; index = date_obj.index(datetime.date(2009, 1, 31)) &gt;&gt; *** TypeError: descriptor 'date' requires a 'datetime.datetime' object but received a 'int' </code></pre> <p>But when I tried this it worked -</p> <pre><code>&gt;&gt; index = date_obj.index(datetime.strptime("2009-01-31","%Y-%m-%d").date()) &gt;&gt; 10 </code></pre>
0
2016-07-28T01:21:13Z
38,625,683
<p>You have probably used</p> <pre><code>from datetime import datetime </code></pre> <p>and the problem is that date is part of the datetime library not from the datetime.datetime module ;)</p>
1
2016-07-28T01:24:43Z
[ "python", "list", "datetime", "python-datetime" ]
In Beautifulsoup4, Get All SubElements of an Element, but Not SubElements of the SubElements
38,625,693
<p>I've got the following html:</p> <pre><code>&lt;div class="what-im-after"&gt; &lt;p&gt; "content I want" &lt;/p&gt; &lt;p&gt; "content I want" &lt;/p&gt; &lt;p&gt; "content I want" &lt;/p&gt; &lt;div class='not-what-im-after"&gt; &lt;p&gt; "content I don't want" &lt;/p&gt; &lt;/div&gt; &lt;p&gt; "content I want" &lt;/p&gt;&lt;p&gt; "content I want" &lt;/p&gt; &lt;/div&gt; </code></pre> <p>I'm trying to extract all the content from the paragraph tags that are SubElements of the <code>&lt;div class="what-im-after"&gt;</code> container, but not the ones that are found within the <code>&lt;div class="not-what-im-after"&gt;</code> container.</p> <p>when I do this:</p> <pre><code>soup = Beautifulsoup(html.text, 'lxml') content = soup.find('div', class_='what-im-after').findAll('p') </code></pre> <p>I get back all the <code>&lt;p&gt;</code> tags, including those within the <code>&lt;div class='not-what-im-after&gt;</code>, which makes complete sense to me; that's what I'm asking it for. </p> <p>My question is how do I instruct Python to get all the <code>&lt;p&gt;</code> tags, unless they are in another SubElement?</p>
1
2016-07-28T01:26:07Z
38,625,694
<p>In the course of writing this question, an approach came to mind which seems to work fine. </p> <p>Basically, I'm checking each <code>&lt;p&gt;</code> element to see if the parent element is <code>&lt;div class="what-im-after"&gt;</code> which, in effect, excludes any <code>&lt;p&gt;</code> tags nested within subelements.</p> <p>My code is as follows:</p> <pre><code>filter_list = [] parent = soup.find('div', class_='what-im-after') content = soup.find('div', class_='what-im-after').findAll('p') if content.parent is parent: filter_list.append(content) </code></pre> <p><code>filter_list</code> then contains all of the <code>&lt;p&gt;</code> tags that aren't nested within other SubElements.</p>
0
2016-07-28T01:26:07Z
[ "python", "web-scraping", "beautifulsoup" ]
In Beautifulsoup4, Get All SubElements of an Element, but Not SubElements of the SubElements
38,625,693
<p>I've got the following html:</p> <pre><code>&lt;div class="what-im-after"&gt; &lt;p&gt; "content I want" &lt;/p&gt; &lt;p&gt; "content I want" &lt;/p&gt; &lt;p&gt; "content I want" &lt;/p&gt; &lt;div class='not-what-im-after"&gt; &lt;p&gt; "content I don't want" &lt;/p&gt; &lt;/div&gt; &lt;p&gt; "content I want" &lt;/p&gt;&lt;p&gt; "content I want" &lt;/p&gt; &lt;/div&gt; </code></pre> <p>I'm trying to extract all the content from the paragraph tags that are SubElements of the <code>&lt;div class="what-im-after"&gt;</code> container, but not the ones that are found within the <code>&lt;div class="not-what-im-after"&gt;</code> container.</p> <p>when I do this:</p> <pre><code>soup = Beautifulsoup(html.text, 'lxml') content = soup.find('div', class_='what-im-after').findAll('p') </code></pre> <p>I get back all the <code>&lt;p&gt;</code> tags, including those within the <code>&lt;div class='not-what-im-after&gt;</code>, which makes complete sense to me; that's what I'm asking it for. </p> <p>My question is how do I instruct Python to get all the <code>&lt;p&gt;</code> tags, unless they are in another SubElement?</p>
1
2016-07-28T01:26:07Z
38,626,254
<pre><code>from bs4 import BeautifulSoup htmltxt = """&lt;div class="what-im-after"&gt; &lt;p&gt; "content I want" &lt;/p&gt; &lt;p&gt; "content I want" &lt;/p&gt; &lt;p&gt; "content I want" &lt;/p&gt; &lt;div class='not-what-im-after"&gt; &lt;p&gt; "content I don't want" &lt;/p&gt; &lt;/div&gt; &lt;p&gt; "content I want" &lt;/p&gt;&lt;p&gt; "content I want" &lt;/p&gt; &lt;/div&gt;""" soup = BeautifulSoup(htmltxt, 'lxml') def filter_p(container): items = container.contents ans = [] for item in items: if item.name == 'p': ans.append(item) return ans print(filter_p(soup.div)) </code></pre> <p>Maybe you want this. And I just filter the first level p children of div.</p>
-1
2016-07-28T02:40:16Z
[ "python", "web-scraping", "beautifulsoup" ]
In Beautifulsoup4, Get All SubElements of an Element, but Not SubElements of the SubElements
38,625,693
<p>I've got the following html:</p> <pre><code>&lt;div class="what-im-after"&gt; &lt;p&gt; "content I want" &lt;/p&gt; &lt;p&gt; "content I want" &lt;/p&gt; &lt;p&gt; "content I want" &lt;/p&gt; &lt;div class='not-what-im-after"&gt; &lt;p&gt; "content I don't want" &lt;/p&gt; &lt;/div&gt; &lt;p&gt; "content I want" &lt;/p&gt;&lt;p&gt; "content I want" &lt;/p&gt; &lt;/div&gt; </code></pre> <p>I'm trying to extract all the content from the paragraph tags that are SubElements of the <code>&lt;div class="what-im-after"&gt;</code> container, but not the ones that are found within the <code>&lt;div class="not-what-im-after"&gt;</code> container.</p> <p>when I do this:</p> <pre><code>soup = Beautifulsoup(html.text, 'lxml') content = soup.find('div', class_='what-im-after').findAll('p') </code></pre> <p>I get back all the <code>&lt;p&gt;</code> tags, including those within the <code>&lt;div class='not-what-im-after&gt;</code>, which makes complete sense to me; that's what I'm asking it for. </p> <p>My question is how do I instruct Python to get all the <code>&lt;p&gt;</code> tags, unless they are in another SubElement?</p>
1
2016-07-28T01:26:07Z
38,629,528
<p>What you want is to set <em>recursive=False</em> if you just want the p tags under the <code>what-im-after</code> div that are not inside any other tags:</p> <pre><code>soup = BeautifulSoup(html) print(soup.find('div', class_='what-im-after').find_all("p", recursive=False)) </code></pre> <p>That is exactly the same as your loop logic checking the parent.</p>
1
2016-07-28T07:18:13Z
[ "python", "web-scraping", "beautifulsoup" ]
How to distribute python software to users of low technical ability?
38,625,698
<p>I have a python application (3.5) that I’m trying to distribute. It:</p> <ul> <li>Uses no GUI libraries (it runs in the browser)</li> <li>Uses several external packages (Flask, SocketIO, httplib2)</li> <li>maintains saved config and data files inside the main source directory</li> </ul> <p>The target users:</p> <ul> <li>Use Mac or Windows</li> <li>Do not understand the concept of the terminal/command line (testing has shown that it can take hours to teach users how to <code>cd</code> into the source directory to run a <code>.py</code> file).</li> <li>Generally have little difficulty installing the python interpreter from <a href="https://python.org" rel="nofollow">python.org</a> (but have great trouble starting and exiting the python console).</li> <li>Are generally of very low technical ability.</li> </ul> <p>Preferably, the app should:</p> <ul> <li><p>be “click and play”, as I have found that typically the <code>cd</code> navigation is the biggest hurdle preventing users from running my application.</p></li> <li><p>not require manually modifying any system settings</p></li> </ul> <p>I am developing from Ubuntu Linux. I have access to a Windows VM, but not a Mac computer. How do I distribute my application?</p>
0
2016-07-28T01:26:50Z
38,625,772
<p>There are a couple of applications that can help you to distribute a Python Application, for this case you want to take a look on Python freezing tools like <a href="http://www.py2exe.org/" rel="nofollow">py2exe</a> (windows only) or <a href="https://pythonhosted.org/py2app/" rel="nofollow">py2app</a> (MacOs).</p> <p>This two will help you distribute your code without all the hassle of making the user to install the dependencies and run anything from the command line.</p> <p>However if your application runs on the browser, you probably want to just put that into a server (take a look of openshift, it's free) it will make your life a lot easier.</p>
0
2016-07-28T01:36:21Z
[ "python", "software-distribution" ]
mysql store muptiple alias for one person
38,625,706
<p>One person have one name and multiple alias。 Person can index by name and alias. So I design two table store this relationship: and . Like this:</p> <pre><code>&lt;user table&gt; |user_id | int |name | varchar &lt;alias table&gt; |user_id | int |alias | varchar </code></pre> <p>Two table joined by user_id. So one user can set multiple alias and can index by alias. <strong>But now we need add unique constraint. If user's name and each alias are same it is considered repeat!</strong> So i think use one table store like this:</p> <pre><code>&lt;user table&gt; |user_id | int |name | varchar |sorted_alias_str | varchar ps: sorted_alias_str store each alias which join by comma. like: 'name1,name2' </code></pre> <p><strong>with unique constraint (name, sorted_alias_str)</strong></p> <p>but the number of user's alias is limit by 'sorted_alias_str' length.</p> <p>is there a better way of doing this?</p>
0
2016-07-28T01:27:19Z
38,625,773
<p>I agree with having a unique constraint, but it should be <code>UNIQUE CONSTRAINT (user_id, alias)</code> on the <code>alias</code> table. But I disagee with the <code>sorted_alias_str</code>. This column will be a hassle to maintain, because it will have to be recomputed each time any user adds or drops an alias. Instead, you can just use <code>GROUP_CONCAT</code> to obtain a CSV list of aliases for each user, e.g.</p> <pre><code>SELECT t1.user_id, t1.name, t2.aliases FROM user t1 INNER JOIN ( SELECT user_id, GROUP_CONCAT(COALESCE(alias, 'NA') AS aliases FROM alias GROUP BY user_id ) t2 ON t1.user_id = t2.user_id </code></pre>
0
2016-07-28T01:36:21Z
[ "python", "mysql", "database", "web-services" ]
mysql store muptiple alias for one person
38,625,706
<p>One person have one name and multiple alias。 Person can index by name and alias. So I design two table store this relationship: and . Like this:</p> <pre><code>&lt;user table&gt; |user_id | int |name | varchar &lt;alias table&gt; |user_id | int |alias | varchar </code></pre> <p>Two table joined by user_id. So one user can set multiple alias and can index by alias. <strong>But now we need add unique constraint. If user's name and each alias are same it is considered repeat!</strong> So i think use one table store like this:</p> <pre><code>&lt;user table&gt; |user_id | int |name | varchar |sorted_alias_str | varchar ps: sorted_alias_str store each alias which join by comma. like: 'name1,name2' </code></pre> <p><strong>with unique constraint (name, sorted_alias_str)</strong></p> <p>but the number of user's alias is limit by 'sorted_alias_str' length.</p> <p>is there a better way of doing this?</p>
0
2016-07-28T01:27:19Z
38,625,791
<p>The unique constraint should be on the (user_id, name). This prevents one person (user_id) from having the same alias multiple times.</p>
1
2016-07-28T01:37:33Z
[ "python", "mysql", "database", "web-services" ]
mysql store muptiple alias for one person
38,625,706
<p>One person have one name and multiple alias。 Person can index by name and alias. So I design two table store this relationship: and . Like this:</p> <pre><code>&lt;user table&gt; |user_id | int |name | varchar &lt;alias table&gt; |user_id | int |alias | varchar </code></pre> <p>Two table joined by user_id. So one user can set multiple alias and can index by alias. <strong>But now we need add unique constraint. If user's name and each alias are same it is considered repeat!</strong> So i think use one table store like this:</p> <pre><code>&lt;user table&gt; |user_id | int |name | varchar |sorted_alias_str | varchar ps: sorted_alias_str store each alias which join by comma. like: 'name1,name2' </code></pre> <p><strong>with unique constraint (name, sorted_alias_str)</strong></p> <p>but the number of user's alias is limit by 'sorted_alias_str' length.</p> <p>is there a better way of doing this?</p>
0
2016-07-28T01:27:19Z
38,625,955
<p>What you have already gives a single user multiple aliases. A composite unique constraint ensures one user will not have the same alias more than once.</p> <pre><code>&lt;user table&gt; |user_id | int (unique) |name | varchar &lt;alias table&gt; |user_id | int (unique, also ref to user.user_id) |alias | varchar unique constraint (user_id, alias) </code></pre> <p>Every UNIQUE constraint is also an index.</p> <p>For even more structure, you can put all of your known aliases in one table.</p> <pre><code>&lt;user table&gt; |user_id | int (unique) |name | varchar &lt;user_alias table&gt; |user_id | int (ref to user.user_id) |alias_id | int (ref to alias.alias_id) unique constraint (user_id, alias_id) &lt;alias table&gt; |alias_id | int (unique) |alias | varchar </code></pre> <p>Finally, if you acknowledge that a name is just a specially identified alias, you can add a bit more structure :</p> <pre><code>&lt;user table&gt; |user_id | int (unique) |name | int (ref to alias.alias_id) &lt;user_alias table&gt; |user_id | int (ref to user.user_id) |alias_id | int (ref to alias.alias_id) unique constraint (user_id, alias_id) &lt;alias table&gt; |alias_id | int (unique) |alias | varchar </code></pre>
0
2016-07-28T02:00:02Z
[ "python", "mysql", "database", "web-services" ]
Python convert string to datetime for comparison to datetime object
38,625,723
<p>I have a string <code>lfile</code> with a datetime in it (<code>type(lfile)</code> gives <code>&lt;type 'str'&gt;</code>) and a Python datetime object <code>wfile</code>. Here is the code:</p> <pre><code>import os, datetime lfile = '2005-08-22_11:05:45.000000000' time_w = os.path.getmtime('{}\\{}.py' .format('C:\Temp_Readouts\RtFyar','TempReads.csv')) wfile = datetime.datetime.fromtimestamp(time_w) </code></pre> <p><code>wfile</code> contains this <code>2006-11-30 19:08:06.531328</code> and <code>repr(wfile)</code> gives:</p> <pre><code>datetime.datetime(2006, 11, 30, 19, 8, 6, 531328) </code></pre> <p><strong>Problem:</strong></p> <p>I need to:</p> <ol> <li>convert <code>lfile</code> into a Python datetime object</li> <li>compare <code>lfile</code> to <code>wfile</code> and determine which datetime is more recent</li> </ol> <p>For 1.:</p> <p>I am only able to get a partial solution using <code>strptime</code> as per <a href="http://stackoverflow.com/questions/698223/how-can-i-parse-a-time-string-containing-milliseconds-in-it-with-python">here</a>. Here is what I tried:</p> <pre><code>lfile = datetime.datetime.strptime(linx_file_dtime, '%Y-%m-%d_%H:%M:%S') </code></pre> <p>The output is:</p> <pre><code>`ValueError: unconverted data remains: .000` </code></pre> <p><em>Question 1</em></p> <p>It seems that <code>strptime()</code> <a href="http://stackoverflow.com/questions/10611328/format-nanoseconds-in-python">cannot</a> handle the nano seconds. How do I tell <code>strptime()</code> to ignore the last 3 zeros?</p> <p>For 2.:</p> <p>When I use <code>type(wfile)</code> I get <code>&lt;type 'datetime.datetime'&gt;</code>. If both <code>wfile</code> and <code>lfile</code> are Python datetime objects (i.e. if step 1. is successful), then would <a href="http://stackoverflow.com/questions/8142364/how-to-compare-two-dates">this</a> work?:</p> <pre><code>if wtime &lt; ltime: print 'Linux file created after Windows file' else: print 'Windows file created after Linux file' </code></pre> <p><em>Question 2</em></p> <p>Or is there some other way in which Python can compare datetime objects to determine which of the two occurred after the other?</p>
1
2016-07-28T01:29:24Z
38,625,832
<p><strong>Question 1</strong></p> <p>Python handles microseconds, not nano seconds. You can strip the last three characters of the time to convert it to microseconds and then add <code>.%f</code> to the end:</p> <pre><code>lfile = datetime.datetime.strptime(linx_file_dtime[:-3], '%Y-%m-%d_%H:%M:%S.%f') </code></pre> <p><strong>Question 2</strong></p> <p>Yes, comparison works:</p> <pre><code>if wtime &lt; ltime: ... </code></pre>
2
2016-07-28T01:43:00Z
[ "python", "python-2.7", "datetime", "strptime" ]
Python convert string to datetime for comparison to datetime object
38,625,723
<p>I have a string <code>lfile</code> with a datetime in it (<code>type(lfile)</code> gives <code>&lt;type 'str'&gt;</code>) and a Python datetime object <code>wfile</code>. Here is the code:</p> <pre><code>import os, datetime lfile = '2005-08-22_11:05:45.000000000' time_w = os.path.getmtime('{}\\{}.py' .format('C:\Temp_Readouts\RtFyar','TempReads.csv')) wfile = datetime.datetime.fromtimestamp(time_w) </code></pre> <p><code>wfile</code> contains this <code>2006-11-30 19:08:06.531328</code> and <code>repr(wfile)</code> gives:</p> <pre><code>datetime.datetime(2006, 11, 30, 19, 8, 6, 531328) </code></pre> <p><strong>Problem:</strong></p> <p>I need to:</p> <ol> <li>convert <code>lfile</code> into a Python datetime object</li> <li>compare <code>lfile</code> to <code>wfile</code> and determine which datetime is more recent</li> </ol> <p>For 1.:</p> <p>I am only able to get a partial solution using <code>strptime</code> as per <a href="http://stackoverflow.com/questions/698223/how-can-i-parse-a-time-string-containing-milliseconds-in-it-with-python">here</a>. Here is what I tried:</p> <pre><code>lfile = datetime.datetime.strptime(linx_file_dtime, '%Y-%m-%d_%H:%M:%S') </code></pre> <p>The output is:</p> <pre><code>`ValueError: unconverted data remains: .000` </code></pre> <p><em>Question 1</em></p> <p>It seems that <code>strptime()</code> <a href="http://stackoverflow.com/questions/10611328/format-nanoseconds-in-python">cannot</a> handle the nano seconds. How do I tell <code>strptime()</code> to ignore the last 3 zeros?</p> <p>For 2.:</p> <p>When I use <code>type(wfile)</code> I get <code>&lt;type 'datetime.datetime'&gt;</code>. If both <code>wfile</code> and <code>lfile</code> are Python datetime objects (i.e. if step 1. is successful), then would <a href="http://stackoverflow.com/questions/8142364/how-to-compare-two-dates">this</a> work?:</p> <pre><code>if wtime &lt; ltime: print 'Linux file created after Windows file' else: print 'Windows file created after Linux file' </code></pre> <p><em>Question 2</em></p> <p>Or is there some other way in which Python can compare datetime objects to determine which of the two occurred after the other?</p>
1
2016-07-28T01:29:24Z
38,626,162
<p>That's right, <code>strptime()</code> does not handle nanoseconds. The accepted answer in the question that you linked to offers an option: strip off the last 3 digits and then parse with <code>.%f</code> appended to the format string.</p> <p>Another option is to use <code>dateutil.parser.parse()</code>:</p> <pre><code>&gt;&gt;&gt; from dateutil.parser import parse &gt;&gt;&gt; parse('2005-08-22_11:05:45.123456789', fuzzy=True) datetime.datetime(2005, 8, 22, 11, 5, 45, 123456) </code></pre> <p><code>fuzzy=True</code> is required to overlook the unsupported underscore between date and time components. Because <code>datetime</code> objects do not support nanoseconds, the last 3 digits vanish, leaving microsecond accuracy.</p>
1
2016-07-28T02:26:03Z
[ "python", "python-2.7", "datetime", "strptime" ]
Faster way to partition a Face with Sketch in ABAQUS with scripting
38,625,874
<p>My aim is to obtain a transition mapped quad meshing on a long rectangular region which is a parametrised model. The final mesh can be seen as follows: </p> <p><a href="http://i.stack.imgur.com/P9esm.png" rel="nofollow"><img src="http://i.stack.imgur.com/P9esm.png" alt="Transition Mapped Quad Meshing"></a></p> <p>The only way I could realise this final output mesh was to partition the face with sketch and then, using adequate mesh controls and seeding on the respective edges. For this reason, I started with generating a block on the left hand side of the geometry like this:</p> <p><a href="http://i.stack.imgur.com/w3jpB.png" rel="nofollow"><img src="http://i.stack.imgur.com/w3jpB.png" alt="Single block created by partioning the face with sketch"></a> </p> <p>Thereafter, a "for" loop was used in the Python script running from the left hand side of the rectangular face to the right-most end and the final partitioned face looks like this:</p> <p><a href="http://i.stack.imgur.com/WQfT2.png" rel="nofollow"><img src="http://i.stack.imgur.com/WQfT2.png" alt="Final geometry ready to be meshed"></a></p> <p>So, I tried doing this in three ways.</p> <p>Option 1: Place the sketcher window using findAt at the left hand side and then generate the block and with a "for" loop push the origin of the coordinate system of the sketcher window to the right incrementally all the way to the right-most side. In other words, the position of the block with respect to the origin stayed the same always and hence, when the origin moved from left to right, the block moved with it. So I had to open and clos "Partition Face with Sketch" as many times as the number of blocks required. </p> <p>Option 2: The origin of the Sketcher window stayed at the same place (i.e. at 0.0, 0.0, 0.0) and the blocks were pushed to the right incrementally. In comparison with Option 1, here the relative position of the block with respect to the origin changed over each increment. Here also, "Partition Face with Sketch" was opened and closed as many times as the number of blocks required. </p> <p>Option 3: I opened the "Partition Face with Sketch" only once and the origin stayed at the same place. Then I drew all these horizontal and vertical lines also with a "for" loop resulting in the final partitioned face.</p> <p>All these methodologies work perfectly but are extremely time-consuming. Each of these methods takes almost from 8-12 minutes to finish generating all the blocks and hence, is not suitable for a convergence study.</p> <p>Can anyone suggest a better solution to make this entire process faster, like in 3-4 minutes or so? Would really appreciate it. Thanks in advance.</p> <p>EDIT: Here is the code guys:</p> <pre><code># The arguments of the function "block" are the x and y coordinates of the # 4 corners of the rectangle where the blocks have to be generated in. def block(x_left, x_right, y_top, y_bottom): # Opens the sketcher window p = mdb.models['TDCB'].parts['Part_TDCB'] f, e, d = p.faces, p.edges, p.datums t = p.MakeSketchTransform(sketchPlane=f.findAt(coordinates=(x_left + ((x_right - x_left) / 3), y_bottom + ((y_top - y_bottom) / 3), 0.0), normal=(0.0, 0.0, 1.0)), sketchPlaneSide=SIDE1, origin=(x_left, y_bottom, 0.0)) s = mdb.models['TDCB'].ConstrainedSketch(name='__profile__', sheetSize=500.00, gridSpacing=12.00, transform=t) g, v, d1, c = s.geometry, s.vertices, s.dimensions, s.constraints s.setPrimaryObject(option=SUPERIMPOSE) p.projectReferencesOntoSketch(sketch=s, filter=COPLANAR_EDGES) # The following block generates the first couple of horizontal lines s.Line(point1=(block_width, 0.0), point2=(block_width, y_top)) # Line No.1 s.Line(point1=(0.0, y_coord[-2]), point2=(block_width, y_coord[-2])) # Line No.2 s.Line(point1=(0.0, y_coord[-3]), point2=(block_width, y_coord[-3])) # Line No.3 s.Line(point1=(0.0, y_coord[-4]), point2=(block_width, y_coord[-4])) # Line No.4 s.Line(point1=(0.0, y_coord[-5]), point2=(block_width, y_coord[-5])) # Line No.5 s.Line(point1=(0.0, y_coord[-6]), point2=(block_width, y_coord[-6])) # Line No.6 # Closes the sketcher window p = mdb.models['TDCB'].parts['Part_TDCB'] f = p.faces pickedFaces = f.findAt((x_left + ((x_right - x_left) / 3), y_bottom + ((y_top - y_bottom) / 3), 0.0)) e1, d2 = p.edges, p.datums p.PartitionFaceBySketch(faces=pickedFaces, sketch=s) s.unsetPrimaryObject() del mdb.models['TDCB'].sketches['__profile__'] return # Finally the blocks are generated using a "for" loop for i in range(total_blocks): block(x_left, x_right, y_top, y_bottom) </code></pre>
0
2016-07-28T01:48:05Z
39,328,730
<p>It seems you don't have to iterate the process of sketching as in ABAQUS Sketch you can use Linear Pattern to copy/duplicate the initial sketch (first block on the left side). This may make the whole process easier. Thanks.</p> <p>Regards, Longjie</p>
0
2016-09-05T10:34:04Z
[ "python", "scripting", "abaqus" ]
JQuery Ajax call not working in If statement
38,625,945
<p>Is there a reason why my Ajax call will not work inside of an if statement? I may be doing something fundamentally wrong here because I don't have a lot of experience with JS or Ajax. Thanks</p> <p>The working js function is:</p> <pre><code>function filter(varType, varValue) { var $products = $('#products'); $.getJSON($SCRIPT_ROOT + '/filterSize/' + varValue) .success(function (data) { $products.empty(); // clear html from container var elt0 = '&lt;div class="page-content"&gt;&lt;h1 id="shoes"&gt;Shoes&lt;/h1&gt;&lt;/div&gt;'; $products.append(elt0); if (Object.keys(data.shoes).length === 0) { none = '&lt;span class="noresults"&gt;No results&lt;/span&gt;'; $products.append(none); } else { var numItems = (Object.keys(data.shoes).length); for (index = 0; index &lt; numItems ; ++index) { var elt1 = Flask.url_for("static", {"filename": data.shoes[index].img1}); var elt2 = '&lt;div id="item" class="col-md-4"&gt;&lt;div class="products"&gt;&lt;a href="shop/item/' + data.shoes[index].id + '"&gt;&lt;h5&gt;' + data.shoes[index].name + '&lt;/h5&gt;&lt;img src="' + elt1 + '" alt="" width="200px" height="125px"&gt;&lt;/a&gt;&lt;/div&gt;'; $products.append(elt2); } } }); } </code></pre> <p>But if I were to do this, it suddenly stops working:</p> <pre><code>function filter(varType, varValue) { var $products = $('#products'); var x = 5 var y = 6 if (y &gt; x) { $.getJSON($SCRIPT_ROOT + '/filterSize/' + varValue) } .success(function (data) { $products.empty(); // clear html from container var elt0 = '&lt;div class="page-content"&gt;&lt;h1 id="shoes"&gt;Shoes&lt;/h1&gt;&lt;/div&gt;'; $products.append(elt0); if (Object.keys(data.shoes).length === 0) { none = '&lt;span class="noresults"&gt;No results&lt;/span&gt;'; $products.append(none); } else { var numItems = (Object.keys(data.shoes).length); for (index = 0; index &lt; numItems ; ++index) { var elt1 = Flask.url_for("static", {"filename": data.shoes[index].img1}); var elt2 = '&lt;div id="item" class="col-md-4"&gt;&lt;div class="products"&gt;&lt;a href="shop/item/' + data.shoes[index].id + '"&gt;&lt;h5&gt;' + data.shoes[index].name + '&lt;/h5&gt;&lt;img src="' + elt1 + '" alt="" width="200px" height="125px"&gt;&lt;/a&gt;&lt;/div&gt;'; $products.append(elt2); } } }); } </code></pre>
0
2016-07-28T01:57:59Z
38,625,971
<p>You closed the curly brace of your <code>if-</code> statement too soon:</p> <pre><code>if (y &gt; x) { $.getJSON($SCRIPT_ROOT + '/filterSize/' + varValue) //} &lt;-- TOO EARLY .success(function (data) { .... }); } &lt;-- SHOULD BE HERE INSTEAD </code></pre> <p>End the <code>if</code> statement after the <code>.success()</code> callback.</p>
1
2016-07-28T02:03:35Z
[ "javascript", "jquery", "python", "ajax" ]
JQuery Ajax call not working in If statement
38,625,945
<p>Is there a reason why my Ajax call will not work inside of an if statement? I may be doing something fundamentally wrong here because I don't have a lot of experience with JS or Ajax. Thanks</p> <p>The working js function is:</p> <pre><code>function filter(varType, varValue) { var $products = $('#products'); $.getJSON($SCRIPT_ROOT + '/filterSize/' + varValue) .success(function (data) { $products.empty(); // clear html from container var elt0 = '&lt;div class="page-content"&gt;&lt;h1 id="shoes"&gt;Shoes&lt;/h1&gt;&lt;/div&gt;'; $products.append(elt0); if (Object.keys(data.shoes).length === 0) { none = '&lt;span class="noresults"&gt;No results&lt;/span&gt;'; $products.append(none); } else { var numItems = (Object.keys(data.shoes).length); for (index = 0; index &lt; numItems ; ++index) { var elt1 = Flask.url_for("static", {"filename": data.shoes[index].img1}); var elt2 = '&lt;div id="item" class="col-md-4"&gt;&lt;div class="products"&gt;&lt;a href="shop/item/' + data.shoes[index].id + '"&gt;&lt;h5&gt;' + data.shoes[index].name + '&lt;/h5&gt;&lt;img src="' + elt1 + '" alt="" width="200px" height="125px"&gt;&lt;/a&gt;&lt;/div&gt;'; $products.append(elt2); } } }); } </code></pre> <p>But if I were to do this, it suddenly stops working:</p> <pre><code>function filter(varType, varValue) { var $products = $('#products'); var x = 5 var y = 6 if (y &gt; x) { $.getJSON($SCRIPT_ROOT + '/filterSize/' + varValue) } .success(function (data) { $products.empty(); // clear html from container var elt0 = '&lt;div class="page-content"&gt;&lt;h1 id="shoes"&gt;Shoes&lt;/h1&gt;&lt;/div&gt;'; $products.append(elt0); if (Object.keys(data.shoes).length === 0) { none = '&lt;span class="noresults"&gt;No results&lt;/span&gt;'; $products.append(none); } else { var numItems = (Object.keys(data.shoes).length); for (index = 0; index &lt; numItems ; ++index) { var elt1 = Flask.url_for("static", {"filename": data.shoes[index].img1}); var elt2 = '&lt;div id="item" class="col-md-4"&gt;&lt;div class="products"&gt;&lt;a href="shop/item/' + data.shoes[index].id + '"&gt;&lt;h5&gt;' + data.shoes[index].name + '&lt;/h5&gt;&lt;img src="' + elt1 + '" alt="" width="200px" height="125px"&gt;&lt;/a&gt;&lt;/div&gt;'; $products.append(elt2); } } }); } </code></pre>
0
2016-07-28T01:57:59Z
38,625,972
<pre><code> if (y &gt; x) { $.getJSON($SCRIPT_ROOT + '/filterSize/' + varValue) .success(function (data) { $products.empty(); // clear html from container var elt0 = '&lt;div class="page-content"&gt;&lt;h1 id="shoes"&gt;Shoes&lt;/h1&gt;&lt;/div&gt;'; $products.append(elt0); if (Object.keys(data.shoes).length === 0) { none = '&lt;span class="noresults"&gt;No results&lt;/span&gt;'; $products.append(none); } else { var numItems = (Object.keys(data.shoes).length); for (index = 0; index &lt; numItems ; ++index) { var elt1 = Flask.url_for("static", {"filename": data.shoes[index].img1}); var elt2 = '&lt;div id="item" class="col-md-4"&gt;&lt;div class="products"&gt;&lt;a href="shop/item/' + data.shoes[index].id + '"&gt;&lt;h5&gt;' + data.shoes[index].name + '&lt;/h5&gt;&lt;img src="' + elt1 + '" alt="" width="200px" height="125px"&gt;&lt;/a&gt;&lt;/div&gt;'; $products.append(elt2); } } }); } </code></pre> <p>This is valid syntax. You need to move the .success inside the parenthesis.</p>
1
2016-07-28T02:03:59Z
[ "javascript", "jquery", "python", "ajax" ]
Django Rest Framework - adding JOIN endpoints
38,626,017
<p>I'm making a REST API with Django Rest Framework (DRF) which has the following endpoints:</p> <pre><code>/users/ /users/&lt;pk&gt;/ /items/ /items/&lt;pk&gt;/ </code></pre> <p>but I'd like to add the endpoint:</p> <pre><code>/users/&lt;pk&gt;/items/ </code></pre> <p>which would of course return the items that belong (have a foreign key) to that user. </p> <p>Currently my code is:</p> <pre><code>######################### ##### myapp/urls.py ##### ######################### from django.conf.urls import url, include from rest_framework.routers import DefaultRouter from rest_framework.decorators import api_view, renderer_classes from rest_framework import response, schemas from rest_framework_swagger.renderers import OpenAPIRenderer, SwaggerUIRenderer from myapp.views import ItemViewSet, UserViewSet # Create a router and register our viewsets with it. router = DefaultRouter() router.register(r'users', UserViewSet) router.register(r'items', ItemViewSet) @api_view() @renderer_classes([OpenAPIRenderer, SwaggerUIRenderer]) def schema_view(request): generator = schemas.SchemaGenerator(title='My API') return response.Response(generator.get_schema(request=request)) urlpatterns = [ url(r'^', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), ] ########################## ##### myapp/views.py ##### ########################## from django.contrib.auth import get_user_model from rest_framework import viewsets, permissions from myapp.serializers import MyUserSerializer, ItemSerializer from myapp.models import Item class UserViewSet(viewsets.ReadOnlyModelViewSet): queryset = get_user_model().objects.all() serializer_class = MyUserSerializer permission_classes = (permissions.IsAuthenticated,) class ItemViewSet(viewsets.ReadOnlyModelViewSet): queryset = Item.objects.all() serializer_class = ItemSerializer permission_classes = (permissions.IsAuthenticated,) ################################ ##### myapp/serializers.py ##### ################################ from rest_framework import serializers from django.contrib.auth import get_user_model from myapp.models import Item class MyUserSerializer(serializers.ModelSerializer): class Meta: model = get_user_model() fields = ('pk', 'email',) class ItemSerializer(serializers.ModelSerializer): class Meta: model = Item fields = ('pk', 'name',) </code></pre> <p>Is there a good way to add this endpoint in DRF, given how I'm using DRF?</p> <p>I could just add a function view in <code>urls.py</code> like so:</p> <pre><code>from myapp.views import items_for_user urlpatterns = [ url(r'^', include(router.urls)), url(r'^users/(?P&lt;pk&gt;[0-9]+)/items/$', items_for_user), ] </code></pre> <p>but I want to leverage DRF, get the browsable API, and make use of <code>ViewSet</code>s instead of coding one-off function views like this. </p> <p>Any ideas?</p>
2
2016-07-28T02:08:54Z
39,727,821
<p>Took me a while to figure this out. I've been using view sets, so I'll give this answer within that setting.</p> <p>First, URLConf and registered routes remain unchanged, i.e.,</p> <pre><code>router = DefaultRouter() router.register(r'users', UserViewSet) router.register(r'items', ItemViewSet) urlpatterns = [ url(r'^', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework') ), ] </code></pre> <p>Your items will still be at <code>/items/&lt;pk&gt;/</code>, with permissions crafted for each of them depending on who requests them, by creating custom permissions, for example:</p> <pre><code>class IsItemOwnerPermissions(permissions.DjangoObjectPermissions): """ The current user is the owner of the item. """ def has_object_permission(self, request, view, obj): # A superuser? if request.user.is_superuser: return True # Owner if obj.owner.pk == request.user.pk: return True return False </code></pre> <p>Next, for <code>/user/&lt;pk&gt;/items/</code> you need to define <a href="http://www.django-rest-framework.org/api-guide/routers/#customizing-dynamic-routes" rel="nofollow"><code>@detail_route</code></a>, like this:</p> <pre><code>class UserViewSet(viewsets.ReadOnlyModelViewSet): # Your view set properties and methods @detail_route( methods=['GET', 'POST'], permission_classes=[IsItemOwnerPermissions], ) def items(self, request, pk=None): """ Returns a list of all the items belonging to `/user/&lt;pk&gt;`. """ user = get_user_model().objects.get(pk=pk) items = user.items.all() page = self.paginate_queryset(items) if page is None: serializer = ItemSerializer( objs, context={'request': request}, many=True ) return Response(serializer.data) else: serializer = ItemSerializer( page, context={'request': request}, many=True ) return self.get_paginated_response(serializer.data) </code></pre> <p>A detailed route named <code>xyz</code> corresponds to the route <code>user/&lt;pk&gt;/xyz</code>. There are also list routes (<code>@list_route</code>); one named <code>xyz</code> would correspond to <code>user/xyz</code> (for example <code>user/add_item</code>).</p> <p>The above structure will give you: <code>/user</code>, <code>/user/&lt;pk&gt;</code>, <code>user/&lt;pk&gt;/items</code>, <code>/items</code>, and <code>/items/&lt;pk&gt;</code>, but <strong>not</strong> (as I wrongly tried to achieve) <code>user/&lt;user_pk&gt;/items/&lt;items_pk&gt;</code>. Instead, <code>user/&lt;pk&gt;/items</code> will give you a list of user's items, but their individual properties will still be accessible only via <code>/items/&lt;pk&gt;</code>.</p> <p>I just got this to work on my project, and the above code is a quick adaptation to your case. I hope it helps you, but there might still be problems there.</p> <p><strong>Update:</strong> What you wanted can be done using <a href="http://www.django-rest-framework.org/api-guide/relations/#custom-hyperlinked-fields" rel="nofollow">custom hyperlinked fields</a>. I didn't try it (yet), so I cannot say how to use these, but there are nice examples on that link.</p>
0
2016-09-27T14:51:22Z
[ "python", "django", "rest" ]
Trying to convert a CSV into JSON in python for posting to REST API
38,626,039
<p>I've got the following data in a CSV file (a few hundred lines) that I'm trying to massage into sensible JSON to post into a rest api I've gone with the bare minimum fields required, but here's what I've got:</p> <pre><code>dateAsked,author,title,body,answers.author,answers.body,topics.name,answers.accepted 13-Jan-16,Ben,Cant set a channel ,"Has anyone had any issues setting channels. it stays at �0�. It actually tells me there are �0� files.",Silvio,"I�m not sure. I think you can leave the cable out, because the control works. But you could try and switch two port and see if problem follows the serial port. maybe �extended� clip names over 32 characters. Please let me know if you find out! Best regards.",club_k,TRUE </code></pre> <p>Here's a sample of JSON that is roughly like where I need to get to:</p> <pre><code>json_test = """{ "title": "Can I answer a question?", "body": "Some text for the question", "author": "Silvio", "topics": [ { "name": "club_k" } ], "answers": [ { "author": "john", "body": "I\'m not sure. I think you can leave the cable out. Please let me know if you find out! Best regards.", "accepted": "true" } ] }""" </code></pre> <p>Pandas seems to import it into a dataframe okay (ish) but keeps telling me I can't serialize it to json - also need to clean it and sanitise, but that should be fairly easy to achieve within the script.</p> <p>There must also be a way to do this in Pandas, but I'm beating my head against a wall here - as the columns for both answers and topics can't easily be merged together into a dict or a list in python.</p>
1
2016-07-28T02:11:16Z
38,626,745
<p>You can use a <code>csv.DictReader</code> to process the CSV file as a dictionary for each row. Using the field names as keys, a new dictionary can be constructed that groups common keys into a nested dictionary keyed by the part of the field name after the <code>.</code>. The nested dictionary is held within a list, although it is unclear whether that is really necessary - the nested dictionary could probably be placed immediately under the top-level without requiring a list. Here's the code to do it:</p> <pre><code>import csv import json json_data = [] for row in csv.DictReader(open('/tmp/data.csv')): data = {} for field in row: key, _, sub_key = field.partition('.') if not sub_key: data[key] = row[field] else: if key not in data: data[key] = [{}] data[key][0][sub_key] = row[field] # print(json.dumps(data, indent=True)) # print('---------------------------') json_data.append(json.dumps(data)) </code></pre> <p>For your data, with the <code>print()</code> statements enabled, the output would be:</p> <pre> { "body": "Has anyone had any issues setting channels. it stays at '0'. It actually tells me there are '0' files.", "author": "Ben", "topics": [ { "name": "club_k" } ], "title": "Cant set a channel ", "answers": [ { "body": "I'm not sure. I think you can leave the cable out, because the control works. But you could try and switch two port and see if problem follows the serial port. maybe 'extended' clip names over 32 characters. \nPlease let me know if you find out!\n Best regards.", "accepted ": "TRUE", "author": "Silvio" } ], "dateAsked": "13-Jan-16" } --------------------------- </pre>
2
2016-07-28T03:45:13Z
[ "python", "json", "csv", "pandas" ]
Why won't this print, when I type in a keyword?
38,626,044
<pre><code>`print"Welcome to Caleb's login script!" loop = 'true' while(loop == 'true'): username = raw_input("Username Please") password= raw_input("Password Please") if(username == "Caleb" and password == "Lamps320"): print 'Logged in as ' + username loop = 'false' loop1 = 'true' while(loop1 == 'true'): command = raw_input(username + " &gt;&gt; ") if(command == "exit" or command == "Exit"): break if(command == "Passwords" or command == "passwords"): print"passwords" else: print 'Invalid Username/password! Please try again.' </code></pre> <p>I want it to print passwords when I type "Passwords or passwords" it will say 'password'. But when I try and run it and log in and type in passwords or Passwords it will not work. Can somebody help me? The code is supposed to be a login system to access something. But when I type in the keyword (password) it just returns the command prompt. Note: I used Python2.7.3 (Also I can't get the python code to work with the code indent.</p>
-2
2016-07-28T02:11:55Z
38,626,415
<p>Your script is inconsistently indented. It does what you say it does when that is fixed.</p> <pre><code>print"Welcome to Caleb's login script!" loop = 'true' while(loop == 'true'): username = raw_input("Username Please") password= raw_input("Password Please") if(username == "Caleb" and password == "Lamps320"): print 'Logged in as ' + username loop = 'false' loop1 = 'true' while(loop1 == 'true'): command = raw_input(username + " &gt;&gt; ") if(command == "exit" or command == "Exit"): break if(command == "Passwords" or command == "passwords"): print"passwords" else: print 'Invalid Username/password! Please try again.' </code></pre> <p>Depending on how secure this is supposed to be, there are many ways to make it better. Here are a few.</p> <ul> <li>Compare the password to a hash instead of the actual password so your password isn't in plaintext inside the file. See, for example, <a href="http://www.mindrot.org/projects/py-bcrypt/" rel="nofollow">PyBcrypt project</a></li> <li>No 'true' and 'false' constants. Python already has <code>True</code> and <code>False</code> for this purpose, they are the boolean type.</li> </ul>
0
2016-07-28T03:00:45Z
[ "python" ]
why list(print(x.upper(), end=' ') for x in 'spam') gets a [None, None, None, None] list?
38,626,055
<p>On page 608 of 《Learning Python 5th》 ,there is a example code: </p> <pre><code>&gt;&gt;&gt; list(print(x.upper(), end=' ') for x in 'spam') S P A M [None, None, None, None] </code></pre> <p>so,why [None, None, None, None] pops up on the last?</p>
1
2016-07-28T02:13:35Z
38,626,086
<p>The <code>print</code> function returns <code>None</code>... Your expression therefore constructs a list <code>[None, None, None, None]</code>. Since you are in the python Read Evaluate Print Loop (REPL), the result of the expression gets printed after it is evaluated... </p> <p>So, the evaluation of the expression has the side-effect of printing <code>S P A M</code> and then after the the expression is evaluated, it's value gets printed (<code>[None, None, None, None]</code>).</p>
4
2016-07-28T02:17:23Z
[ "python", "python-3.x" ]
Store the result of a function as a variable
38,626,087
<p>I'm trying to write an RSA code, but I'm having issues with a simple thing. I want to store the result of a function as a variable, twice in Python. This is my code</p> <pre><code>def random_odd_between(j,k): k1 = (k-1)//2 j1 = j//2 a1 = int(random()*(k1-j1+1))+j1 a = 2*a1 +1 return a # The list of primes less than 10^6 is given by: list_of_primes = prime_range(1,10^6) # Write a function to check if given number is prime: def check_if_prime(n): prime_flag = 1 for i in list_of_primes: checker = n%i if checker != 0: if (n/i) in ZZ: prime_flag = 0 break else: prime_flag = 0 break return prime_flag # Generate random numbers between 6*10^9 and 10^10 until we get a prime. # Generate two prime numbers between 6*10^9 and 10^10 for p and q def get_a_prime(): count = 0 prime_found = 0 while prime_found == 0: a = random_odd_between(6*10^9,10^10) prime_found = check_if_prime(a) count = count + 1 # Print a prime you've got: print '%i' %a p = get_a_prime() q = get_a_prime() n = p*q # Let t stand for totient t = (p-1)*(q-1) </code></pre> <p>I can't get my p and q to be defined however, they keep just giving me an error. I realize I need to do some kind of return, but I can't get the syntax right</p>
0
2016-07-28T02:17:25Z
38,626,102
<p>just replace <code>print '%i' %a</code> with <code>return a</code></p>
3
2016-07-28T02:19:04Z
[ "python", "rsa" ]
Store the result of a function as a variable
38,626,087
<p>I'm trying to write an RSA code, but I'm having issues with a simple thing. I want to store the result of a function as a variable, twice in Python. This is my code</p> <pre><code>def random_odd_between(j,k): k1 = (k-1)//2 j1 = j//2 a1 = int(random()*(k1-j1+1))+j1 a = 2*a1 +1 return a # The list of primes less than 10^6 is given by: list_of_primes = prime_range(1,10^6) # Write a function to check if given number is prime: def check_if_prime(n): prime_flag = 1 for i in list_of_primes: checker = n%i if checker != 0: if (n/i) in ZZ: prime_flag = 0 break else: prime_flag = 0 break return prime_flag # Generate random numbers between 6*10^9 and 10^10 until we get a prime. # Generate two prime numbers between 6*10^9 and 10^10 for p and q def get_a_prime(): count = 0 prime_found = 0 while prime_found == 0: a = random_odd_between(6*10^9,10^10) prime_found = check_if_prime(a) count = count + 1 # Print a prime you've got: print '%i' %a p = get_a_prime() q = get_a_prime() n = p*q # Let t stand for totient t = (p-1)*(q-1) </code></pre> <p>I can't get my p and q to be defined however, they keep just giving me an error. I realize I need to do some kind of return, but I can't get the syntax right</p>
0
2016-07-28T02:17:25Z
38,626,485
<p>I believe you had errors in both your <code>check_if_prime</code> and <code>get_a_prime</code> functions. In the former, <code>ZZ</code> is not defined and the first <code>break</code> should be indented one more level and the last one is redundant. Better yet, just return True or False when needed.</p> <p>In the second function, you need to return the value that is prime rather than just print it.</p> <pre><code>def check_if_prime(n): if n == 2: return True # 2 is a prime. if n % 2 == 0 or n &lt;= 1: return False # Anything less than or equal to one is not prime. for divisor in xrange(3, int(n ** 0.5) + 1, 2): # 3, 5, 7, ..., int(SQRT(n)) + 1 if not n % divisor: return False # NOT divisible by the divisor. return True # Must be prime. def get_a_prime(): prime_found = False while not prime_found: a = random_odd_between(6 * 10 ^ 9, 10 ^ 10) prime_found = check_if_prime(a) return a </code></pre> <p><strong>Testing</strong></p> <pre><code>primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101] # Ensure all primes above are prime per our function. &gt;&gt;&gt; all(check_if_prime(n) for n in primes) True # Ensure all numbers in range 0-101 that is not identified as a prime is not a prime. &gt;&gt;&gt; any(check_if_prime(n) for n in xrange(102) if n not in primes) False </code></pre>
0
2016-07-28T03:11:54Z
[ "python", "rsa" ]
Getting Top N items per group in pySpark
38,626,124
<p>I am using Spark 1.6.2, I have the following data structure:</p> <pre><code>sample = sqlContext.createDataFrame([ (1,['potato','orange','orange']), (1,['potato','orange','yogurt']), (2,['vodka','beer','vodka']), (2,['vodka','beer','juice', 'vinegar']) ],['cat','terms']) </code></pre> <p>I would like to extract top N most frequent terms per cat. I have developed the following solution which seems to work, however I wanted to see if there is a better way to do this. </p> <pre><code>from collections import Counter def get_top(it, terms=200): c = Counter(it.__iter__()) return [x[0][1] for x in c.most_common(terms)] ( sample.select('cat',sf.explode('terms')).rdd.map(lambda x: (x.cat, x.col)) .groupBy(lambda x: x[0]) .map(lambda x: (x[0], get_top(x[1], 2))) .collect() ) </code></pre> <p>It provides the following output:</p> <pre><code>[(1, ['orange', 'potato']), (2, ['vodka', 'beer'])] </code></pre> <p>Which is in line with what I am looking for, but I really don't like the fact that I am resorting to using Counter. How can I do it with spark alone?</p> <p>Thanks</p>
0
2016-07-28T02:21:26Z
38,626,490
<p>If this is working it is probably better to post this to <a href="http://codereview.stackexchange.com/">Code Review</a>.</p> <p>Just as an exercise I did this without the Counter but largely you are just replicating the same functionality.</p> <ul> <li>Count each occurrence of (<code>cat</code>, <code>term</code>)</li> <li>Group by <code>cat</code></li> <li>Sort the values based on Count and slice to number of terms (<code>2</code>)</li> </ul> <p>Code:</p> <pre><code>from operator import add (sample.select('cat', sf.explode('terms')) .rdd .map(lambda x: (x, 1)) .reduceByKey(add) .groupBy(lambda x: x[0][0]) .mapValues(lambda x: [r[1] for r, _ in sorted(x, key=lambda a: -a[1])[:2]]) .collect()) </code></pre> <p>Output:</p> <pre><code>[(1, ['orange', 'potato']), (2, ['vodka', 'beer'])] </code></pre>
1
2016-07-28T03:12:27Z
[ "python", "apache-spark" ]
Misshaped blob in caffe
38,626,234
<p>I'm using the following prototxt:</p> <pre><code>layer { name: "pool2" type: "Pooling" bottom: "conv5" top: "pool2" pooling_param { pool: MAX kernel_w: 2 kernel_h: 1 stride_w: 2 stride_h: 1 pad_h: 0 pad_w: 0 } } </code></pre> <p>The blob shape before is 1x64x1x30, and after is 1x64x1x15. Shouldn't it be 1x64x1x14?</p> <p>From caffe doc:</p> <pre><code>w_o = (w_i + 2*pad_w - kernel_w)/stride_w = (30 - 2)/2 = 14. </code></pre> <p>It makes sense since the pool would be: [0,1] [2,3] [4,5] ... [28,29] which are 14 elements.</p>
1
2016-07-28T02:36:15Z
38,626,737
<p>In general, the max pooling layer accepts an input volume of size W1 x H1 x D1 and requires two hyperparameters -- the stride (S) and kernel size (K). It produces an output volume of size W2 x H2 x D2 where we have W2 = (W1 - K)/S + 1, H2 = (H1 - K)/S + 1, and D2 = D1. Simple computation yields that a kernel size of 2 and stride of 2 halve the input, verifying caffe's network output shape. </p>
0
2016-07-28T03:44:00Z
[ "python", "deep-learning", "caffe" ]
Why is a generator produced by yield faster than a generator produced by xrange?
38,626,308
<p>I was investigating Python generators and decided to run a little experiment.</p> <pre><code>TOTAL = 100000000 def my_sequence(): i = 0 while i &lt; TOTAL: yield i i += 1 def my_list(): return range(TOTAL) def my_xrange(): return xrange(TOTAL) </code></pre> <p>Memory usage (using psutil to get process RSS memory) and time taken (using time.time()) are shown below after running each method several times and taking the average:</p> <pre><code>sequence_of_values = my_sequence() # Memory usage: 6782976B Time taken: 9.53674e-07 s sequence_of_values2 = my_xrange() # Memory usage: 6774784B Time taken: 2.14576e-06 s list_of_values = my_list() # Memory usage: 3266207744B Time taken: 1.80253s </code></pre> <p>I noticed that producing a generator by using xrange is consistently (slightly) slower than that by using yield. Why is that so? </p>
10
2016-07-28T02:48:00Z
38,626,519
<p>I'm going to preface this answer by saying that timings on this scale are likely going to be hard to measure accurately (probably best to use <code>timeit</code>) and that these sorts of optimizations will almost never make any difference in your actual program's runtime ...</p> <p>Ok, now the disclaimer is done ...</p> <p>The first thing that you need to notice is that you're only timing the construction of the generator/xrange object -- You are <strong>NOT</strong> timing how long it takes to actually iterate over the values<sup>1</sup>. There are a couple reasons why creating the generator might be faster in some cases than creating the xrange object...</p> <ol> <li>For the generator case, you're only creating a generator -- No code in the generator actually gets run. This amounts to roughly 1 function call.</li> <li>For the <code>xrange</code> case, you're calling the function <em>and</em> then you have to lookup the global name <code>xrange</code>, the global <code>TOTAL</code> and then you need to call that builtin -- So there <em>are</em> more things being executed in this case.</li> </ol> <p>As for memory -- In both of the lazy approaches, the memory used will be dominated by the python runtime -- Not by the size of your generator objects. The only case where the memory use is impacted appreciably by your script is the case where you construct a list of 100million items.</p> <p>Also note that I can't actually confirm your results consistently on my system... Using <code>timeit</code>, I actually get that <code>my_xrange</code> is <em>sometimes</em><sup>2</sup> faster to construct (by ~30%).</p> <p>Adding the following to the bottom of your script:</p> <pre><code>from timeit import timeit print timeit('my_xrange()', setup='from __main__ import my_xrange') print timeit('my_sequence()', setup='from __main__ import my_sequence') </code></pre> <p>And my results are (for <code>CPython</code> on OS-X El-Capitan):</p> <pre><code>0.227491140366 0.356791973114 </code></pre> <p>However, <code>pypy</code> seems to favor the generator construction (I tried it with both <code>my_xrange</code> first and <code>my_sequence</code> first and got fairly consistent results though the first one to run does seem to be at a bit of a disadvantage -- Maybe due to JIT warm-up time or something):</p> <pre><code>0.00285911560059 0.00137305259705 </code></pre> <hr> <p><sup><sup>1</sup>Here, I would <em>expect</em> <code>xrange</code> to have the edge -- but again, nothing is true until you <code>timeit</code> and then it's only true if the timings differences are significant and it's only true on the computer where you did the timings.</sup> <br> <sup><sup>2</sup>See opening disclaimer :-P</sup></p>
9
2016-07-28T03:16:39Z
[ "python", "python-2.7", "python-3.x", "yield" ]
Why is a generator produced by yield faster than a generator produced by xrange?
38,626,308
<p>I was investigating Python generators and decided to run a little experiment.</p> <pre><code>TOTAL = 100000000 def my_sequence(): i = 0 while i &lt; TOTAL: yield i i += 1 def my_list(): return range(TOTAL) def my_xrange(): return xrange(TOTAL) </code></pre> <p>Memory usage (using psutil to get process RSS memory) and time taken (using time.time()) are shown below after running each method several times and taking the average:</p> <pre><code>sequence_of_values = my_sequence() # Memory usage: 6782976B Time taken: 9.53674e-07 s sequence_of_values2 = my_xrange() # Memory usage: 6774784B Time taken: 2.14576e-06 s list_of_values = my_list() # Memory usage: 3266207744B Time taken: 1.80253s </code></pre> <p>I noticed that producing a generator by using xrange is consistently (slightly) slower than that by using yield. Why is that so? </p>
10
2016-07-28T02:48:00Z
38,626,711
<p>As I mentioned in my comment above, with your generator function and with xrange, you're not actually creating the sequence, merely creating the object. @mgilson's answer covers the calls related to <em>creating</em> them.</p> <p>As for actually doing something with them:</p> <pre><code>&gt;&gt;&gt; TOTAL = 100000 &gt;&gt;&gt; # your functions here ... &gt;&gt;&gt; import timeit &gt;&gt;&gt; timeit.timeit("list(my_seq())", setup="from __main__ import my_seq", number=1000) 9.783777457339898 &gt;&gt;&gt; timeit.timeit("list(my_xrange())", setup="from __main__ import my_xrange", number=1000) 1.2652621698083024 &gt;&gt;&gt; timeit.timeit("list(my_list())", setup="from __main__ import my_list", number=1000) 2.666709824464867 &gt;&gt;&gt; timeit.timeit("my_list()", setup="from __main__ import my_list", number=1000) 1.2324339537661615 </code></pre> <ol> <li><p>You'll see that I'm creating a <code>list</code> out of each so I'm processing the sequences.</p></li> <li><p>The generator function is nearly 10x the time for <code>xrange</code>.</p></li> <li><p><code>list(my_list)</code> is redundant since <code>my_list</code> already returns the list produced by <code>range</code>, so I did it one more time without the call to <code>list()</code>.</p></li> <li><p><code>range</code> is nearly the same as <code>xrange</code> but that's because I reduced TOTAL. The biggest difference there would be that <code>range</code> would consume more memory since it creates the entire list first and so takes <em>longer only in that part</em>. Creating a list from xrange = range, effectively. So the final memory used would be the same and since I'm merely creating a list out of the xrange, it's hard to see the difference in this trivial case.</p></li> </ol>
3
2016-07-28T03:41:32Z
[ "python", "python-2.7", "python-3.x", "yield" ]
how to do a simple calculate in web.py template
38,626,344
<p>in <code>web.py</code>'s template, I can retrieve number like this:</p> <pre><code>$for item in item_list: &lt;td&gt;$item.get("fans_cnt")&lt;/td&gt; </code></pre> <p>and this <code>$item.get("fans_cnt")</code> will get a number, now I want it divided by 1000, but this won't work:</p> <pre><code>$for item in item_list: &lt;td&gt;$item.get("fans_cnt")/1000&lt;/td&gt; </code></pre> <p>So, what's the right way to make this happen?</p>
0
2016-07-28T02:52:03Z
38,626,399
<p>From <a href="http://webpy.org/docs/0.3/templetor" rel="nofollow">the docs</a>, under heading Syntax, section <em>Expression Substitution</em>:</p> <blockquote> <p>Special character $ is used to specify python expressions. Expression can be enclosed in () or {} for explicit grouping.</p> </blockquote> <p>So:</p> <pre><code>$for item in item_list: &lt;td&gt;$(item.get("fans_cnt")/1000)&lt;/td&gt; </code></pre> <p>should do what you want.</p>
2
2016-07-28T02:58:53Z
[ "python", "templates", "web.py" ]
Python pip installation not working how to do?
38,626,409
<p>I keep trying to install Pip using get-pip.py and only get the wheel file in the scripts folder. Try running "pip" in the command prompt and it just comes out with an error. Running windows 8 incase you need. <em>edit</em> error is 'pip' is not recognized as an internal or external command...</p>
-1
2016-07-28T03:00:06Z
38,627,143
<p>Try navigating to ~/Python[version]/Scripts in cmd, then use <strong>pip[version] [command] [module]</strong> (ie. pip3 install themodulename or pip2 install themodulename)</p>
0
2016-07-28T04:31:37Z
[ "python", "python-2.7", "pip" ]
Python pip installation not working how to do?
38,626,409
<p>I keep trying to install Pip using get-pip.py and only get the wheel file in the scripts folder. Try running "pip" in the command prompt and it just comes out with an error. Running windows 8 incase you need. <em>edit</em> error is 'pip' is not recognized as an internal or external command...</p>
-1
2016-07-28T03:00:06Z
38,627,346
<p>If you are using latest version of Python.</p> <p>In computer properties, Go to Advanced System Settings -> Advanced tab -> Environmental Variables</p> <p>In System variables section, there is variable called PATH. Append c:\Python27\Scripts (Note append, not replace)</p> <p>Then open a new command prompt, try "pip"</p>
1
2016-07-28T04:52:26Z
[ "python", "python-2.7", "pip" ]
Pass JSON Data from PHP to Python Script
38,626,423
<p>I'd like to be able to pass a PHP array to a Python script, which will utilize the data to perform some tasks. I wanted to try to execute my the Python script from PHP using shell_exec() and pass the JSON data to it (which I'm completely new to).</p> <pre><code>$foods = array("pizza", "french fries"); $result = shell_exec('python ./input.py ' . escapeshellarg(json_encode($foods))); echo $result; </code></pre> <p>The "escapeshellarg(json_encode($foods)))" function seems to hand off my array as the following to the Python script (I get this value if I 'echo' the function:</p> <pre><code>'["pizza","french fries"]' </code></pre> <p>Then inside the Python script:</p> <pre><code>import sys, json data = json.loads(sys.argv[1]) foods = json.dumps(data) print(foods) </code></pre> <p>This prints out the following to the browser:</p> <pre><code>["pizza", "french fries"] </code></pre> <p>This is a plain old string, not a list. My question is, how can I best treat this data like a list, or some kind of data structure which I can iterate through with the "," as a delimiter? I don't really want to output the text to the browser, I just want to be able to break down the list into pieces and insert them into a text file on the filesystem. </p>
3
2016-07-28T03:02:32Z
38,626,631
<p>You can base64 <code>foods</code> to string, then passed to the data to Python and decode it.For example:</p> <pre><code>import sys, base64 if len(sys.argv) &gt; 1: data = base64.b64decode(sys.argv[1]) foods = data.split(',') print(foods) </code></pre>
0
2016-07-28T03:32:31Z
[ "php", "python", "json" ]
Pass JSON Data from PHP to Python Script
38,626,423
<p>I'd like to be able to pass a PHP array to a Python script, which will utilize the data to perform some tasks. I wanted to try to execute my the Python script from PHP using shell_exec() and pass the JSON data to it (which I'm completely new to).</p> <pre><code>$foods = array("pizza", "french fries"); $result = shell_exec('python ./input.py ' . escapeshellarg(json_encode($foods))); echo $result; </code></pre> <p>The "escapeshellarg(json_encode($foods)))" function seems to hand off my array as the following to the Python script (I get this value if I 'echo' the function:</p> <pre><code>'["pizza","french fries"]' </code></pre> <p>Then inside the Python script:</p> <pre><code>import sys, json data = json.loads(sys.argv[1]) foods = json.dumps(data) print(foods) </code></pre> <p>This prints out the following to the browser:</p> <pre><code>["pizza", "french fries"] </code></pre> <p>This is a plain old string, not a list. My question is, how can I best treat this data like a list, or some kind of data structure which I can iterate through with the "," as a delimiter? I don't really want to output the text to the browser, I just want to be able to break down the list into pieces and insert them into a text file on the filesystem. </p>
3
2016-07-28T03:02:32Z
38,627,103
<p>If you have the json string: <strong>data = '["pizza","french fries"]'</strong> and <em>json.loads(data)</em> isn't working (which it should), then you can use: <strong>MyPythonList = eval(data)</strong>. <em>eval</em> takes a string and converts it to a python object</p>
0
2016-07-28T04:27:28Z
[ "php", "python", "json" ]
Better Method of Creating Multi Line Text Entry?
38,626,532
<p>I need to create a message box for a user in a GUI with tkinter. For 3/4 of my entries, <code>Entry(master, options. . .,)</code> works. But for a message box, I need a multi line entry. </p> <p>How would I do this? I tried <code>ScrolledText(root).pack()</code>, but it doesn't have the same commands/variables as Entry.</p>
1
2016-07-28T03:19:48Z
38,628,794
<p>It is not explicitly mentioned in the <a href="http://effbot.org/zone/tkinter-scrollbar-patterns.htm" rel="nofollow">documentation</a>, but even if the <a href="http://effbot.org/tkinterbook/entry.htm" rel="nofollow"><code>tkinter.Entry</code></a> widget's content can be scrolled, it <strong>can only be scrolled horizontally</strong> meaning that you can not use the <code>yscrollcommand</code>option unlike with <code>Canvas</code>, <code>Text</code> and <code>Listbox</code> widgets.</p> <p>This means technically your goal is not feasible, I mean you can not write multiple lines inside an Entry widget so that you scroll them vertically but only horizontally: </p> <p><a href="http://i.stack.imgur.com/pdxdZ.png" rel="nofollow"><img src="http://i.stack.imgur.com/pdxdZ.png" alt="enter image description here"></a></p> <p>(if you need the code of this screenshot, please let me know).</p>
1
2016-07-28T06:39:19Z
[ "python", "python-3.x", "tkinter", "multiline", "entry" ]
Better Method of Creating Multi Line Text Entry?
38,626,532
<p>I need to create a message box for a user in a GUI with tkinter. For 3/4 of my entries, <code>Entry(master, options. . .,)</code> works. But for a message box, I need a multi line entry. </p> <p>How would I do this? I tried <code>ScrolledText(root).pack()</code>, but it doesn't have the same commands/variables as Entry.</p>
1
2016-07-28T03:19:48Z
38,629,542
<p>Billal is right, however i would recomend simply using a Textbox.</p> <p>go to: <a href="http://www.tutorialspoint.com/python/tk_text.htm" rel="nofollow">http://www.tutorialspoint.com/python/tk_text.htm</a></p> <p>for more information </p>
1
2016-07-28T07:18:28Z
[ "python", "python-3.x", "tkinter", "multiline", "entry" ]
DoesNotExist at /admin/login/ while using userena
38,626,574
<p>I just used userena to create user function and everything works fine except it gives this error when I try to log in at admin page, and I'm using django 1.9.7 and userena 2.0.1. I read some old posts and it says to remove <code>'django.contrib.sites'</code> in INSTALLED_APPS, but userena wouldn't work if I remove it. <br>here's the error informations:</p> <pre><code>DoesNotExist at /admin/login/ Site matching query does not exist. Request Method: GET Request URL: http://127.0.0.1:8000/admin/login/?next=/admin/ Django Version: 1.9.7 Exception Type: DoesNotExist Exception Value: Site matching query does not exist. </code></pre> <p><br>and the settings.py</p> <pre><code>... INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'polls', 'MessageBoard', 'userena', 'guardian', 'easy_thumbnails', 'accounts', ] ... # email EMAIL_BACKEND = 'django.core.mail.backends.dummy.EmailBackend' # required settings ANONYMOUS_USER_ID = -1 AUTH_PROFILE_MODULE = 'accounts.MyProfile' USER_SIGNIN_REDIRECT_URL = '/accounts/%(username)s/' LOGIN_URL = '/accounts/signin/' LOGOUT_URL = '/accounts/signout/' </code></pre>
1
2016-07-28T03:24:57Z
38,628,132
<p>Probably here's an answer: <a href="http://django-userena.readthedocs.io/en/latest/faq.html#i-get-a-site-matching-query-does-not-exist-exception" rel="nofollow">I get a “Site matching query does not exist.” exception</a></p> <p>Did you forget to set up your SITE_ID setting variable?</p>
1
2016-07-28T05:57:09Z
[ "python", "django", "django-userena" ]
DoesNotExist at /admin/login/ while using userena
38,626,574
<p>I just used userena to create user function and everything works fine except it gives this error when I try to log in at admin page, and I'm using django 1.9.7 and userena 2.0.1. I read some old posts and it says to remove <code>'django.contrib.sites'</code> in INSTALLED_APPS, but userena wouldn't work if I remove it. <br>here's the error informations:</p> <pre><code>DoesNotExist at /admin/login/ Site matching query does not exist. Request Method: GET Request URL: http://127.0.0.1:8000/admin/login/?next=/admin/ Django Version: 1.9.7 Exception Type: DoesNotExist Exception Value: Site matching query does not exist. </code></pre> <p><br>and the settings.py</p> <pre><code>... INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'polls', 'MessageBoard', 'userena', 'guardian', 'easy_thumbnails', 'accounts', ] ... # email EMAIL_BACKEND = 'django.core.mail.backends.dummy.EmailBackend' # required settings ANONYMOUS_USER_ID = -1 AUTH_PROFILE_MODULE = 'accounts.MyProfile' USER_SIGNIN_REDIRECT_URL = '/accounts/%(username)s/' LOGIN_URL = '/accounts/signin/' LOGOUT_URL = '/accounts/signout/' </code></pre>
1
2016-07-28T03:24:57Z
38,630,170
<p>This error indicates that you do not have and <code>Site</code>s configured in your database. That can be done with your admin. If you visit <a href="http://localhost:8000/admin/sites/site/" rel="nofollow">http://localhost:8000/admin/sites/site/</a> you will see that currently the list is empty.</p> <p>Just add a site and then add</p> <pre><code>SITE_ID = 1 </code></pre> <p>into your settings.py</p>
1
2016-07-28T07:49:14Z
[ "python", "django", "django-userena" ]
form.is_valid() returning false with file attachments
38,626,616
<p>I have a form page which asks for file upload, but in the views.py page, form.is_valid() is always returning 'False'. The following is the forms.py:</p> <p>forms.py</p> <pre><code>from django import forms class Upload_resume(forms.Form): f_name = forms.CharField(label='First Name', max_length=64, required=True) s_name = forms.CharField(label='Second Name', max_length=64, required=True) email = forms.EmailField() phone_no = forms.CharField(widget=forms.TextInput(attrs={'type':'number'})) resume = forms.Field(label='Upload Resume', widget = forms.FileInput, required = True ) </code></pre> <p>The following is my views.py</p> <pre><code>from django.shortcuts import render from .forms import Upload_resume from django.core.mail import send_mail, EmailMessage def up_resume(request): if request.method == 'POST': for key, value in request.POST.items(): print(key, value) form = Upload_resume(request.POST, request.FILES) print form.is_valid() print form.errors print type(form.errors) </code></pre> <p>I am getting the following errors:</p> <pre><code>(u'resume', u'NBA Meeting.docx') (u'f_name', u'Jeril') (u'phone_no', u'9784644334') (u's_name', u'K') (u'csrfmiddlewaretoken', u'9z6I0VaNGESR49iBHXvHwCGRRlGcjH1v') (u'email', u'jeril.work@gmail.com') False &lt;ul class="errorlist"&gt;&lt;li&gt;resume&lt;ul class="errorlist"&gt;&lt;li&gt;This field is required.&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;/ul&gt; &lt;class 'django.forms.utils.ErrorDict'&gt; </code></pre> <p>What might be the error? The name of the file that I uploaded is displaying correctly, but still i get an error. Could anyone help. I am new to Django.</p>
0
2016-07-28T03:30:22Z
38,626,633
<p>The <code>POST</code> request is missing the file. The <code>form</code> tag in your template should have <code>enctype='multipart/form-data'</code> when you are trying to upload a file.</p>
1
2016-07-28T03:32:44Z
[ "python", "django" ]
Convert PIL image to bytearray
38,626,692
<p>In C#, I can use Bitmap.lockbits() to access a bitmap as a byte array. How to do this in PIL? I have tried Image.write() but it wrote a full format image to a stream.</p>
0
2016-07-28T03:38:39Z
38,626,806
<pre><code>from io import BytesIO from PIL import Image with BytesIO() as output: with Image.open(path_to_image) as img: img.save(output, 'BMP') data = output.getvalue() </code></pre>
2
2016-07-28T03:52:08Z
[ "python", "python-imaging-library" ]
python Raspberry pi receive udp data from spesefic port Visual Studio
38,626,698
<p>I currently got my Raspberry Pi 3 working as a File-Sharing device on my local internet. A 5' display is connected to it and I want to be able to send commands to it through udp packets. I know a lot about c#, but I'm totally new to python. I'm programming in Visual Studio. I already have the sending program working coded in c#</p> <pre><code>Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); IPAddress serverAddr = IPAddress.Parse(IPADDRESS); IPEndPoint endPoint = new IPEndPoint(serverAddr, 2522); byte[] send_buffer = UTF8Encoding.UTF8.GetBytes(TEXT); sock.SendTo(send_buffer, endPoint); </code></pre> <p>I know it works becuase of my hard work with my UDP-Chat which is working. Problem is, how do I receive it on my raspberry pi through python? I tried:</p> <pre><code>import socket UDP_IP = "192.168.1.11" #Which is my local ip for my computer UDP_PORT = 2522 sock = socket.socket(socket.AF_INET, # Internet socket.SOCK_DGRAM) # UDP sock.bind((UDP_IP, UDP_PORT)) while True: data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes print (data) </code></pre> <p>But I got this message displayed when doing 'python Receiver.py':</p> <pre><code>Traceback (most recent call last): File "Receiver.py", line 7, in &lt;module&gt; sock.bind(("192.168.1.11", UDP_PORT)) File "/usr/lib/python2.7/socket.py", line 224, in meth return getattr(self._sock,name)(*args) socket.error: [Errno 99] Cannot assign requested address </code></pre> <p>I created a new one, called it test.py, put it in same folder and ran it. simple print "hello world!", and it worked like expected. Did I do something wrong here? do I need to install something extra for my RPi3? Please help.</p>
0
2016-07-28T03:39:51Z
38,627,168
<p>I figured it out. I changed UDP_IP = "192.168.1.11" to UDP_IP = "" Like so:</p> <pre><code>import socket UDP_PORT = 2522 UDP_IP = "" sock = socket.socket(socket.AF_INET, # Internet socket.SOCK_DGRAM) # UDP sock.bind((UDP_IP, UDP_PORT)) while True: data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes print (data) </code></pre> <p>I tried UDP_IP = " " before, but it gave Visual Studio Red lines.. And so I changed it to UDP_IP = "", and it worked. That little space destroyed the code.</p>
0
2016-07-28T04:35:17Z
[ "python", "visual-studio", "udp", "raspberry-pi", "raspbian" ]
Mapping a list into a reference list
38,626,700
<p>I am trying to make this as clear as I can. Please let me know if I should clarify anything.</p> <p>I have a long list of variables in a list in the following format - </p> <pre><code>L = ["Fruit", "Transportation", "Housing", "Food", "Education"] </code></pre> <p>I would like to map a shorter list into it. The shorter list does not have each but only some of the variables in the long list. For instance -</p> <pre><code>S = ["Fruit", "Food"] </code></pre> <p>What I am interested in obtaining is the binary values of the short list while it maps into the L list.</p> <p>With S as an example, it should be:</p> <pre><code>S = [1, 0, 0, 1, 0] </code></pre> <p>I tried map(S, L) but clearly a list is not callable. </p> <pre><code>TypeError: 'list' object is not callable </code></pre> <p>What would be a good way to do this? Thank you!!</p>
0
2016-07-28T03:40:19Z
38,626,743
<p>By using a list comprehension that takes every value in <code>L</code> and if it is contained inside <code>S</code> it returns a value of <code>1</code>, and, if not, it returns a value of <code>0</code>:</p> <pre><code>m = [1 if subval in S else 0 for subval in L] </code></pre> <p>the result is:</p> <pre><code>[1, 0, 0, 1, 0] </code></pre>
1
2016-07-28T03:44:45Z
[ "python", "list", "mapping" ]
Mapping a list into a reference list
38,626,700
<p>I am trying to make this as clear as I can. Please let me know if I should clarify anything.</p> <p>I have a long list of variables in a list in the following format - </p> <pre><code>L = ["Fruit", "Transportation", "Housing", "Food", "Education"] </code></pre> <p>I would like to map a shorter list into it. The shorter list does not have each but only some of the variables in the long list. For instance -</p> <pre><code>S = ["Fruit", "Food"] </code></pre> <p>What I am interested in obtaining is the binary values of the short list while it maps into the L list.</p> <p>With S as an example, it should be:</p> <pre><code>S = [1, 0, 0, 1, 0] </code></pre> <p>I tried map(S, L) but clearly a list is not callable. </p> <pre><code>TypeError: 'list' object is not callable </code></pre> <p>What would be a good way to do this? Thank you!!</p>
0
2016-07-28T03:40:19Z
38,626,744
<p>Try this:</p> <pre><code>[int(x in S) for x in L] </code></pre>
1
2016-07-28T03:45:03Z
[ "python", "list", "mapping" ]
Mapping a list into a reference list
38,626,700
<p>I am trying to make this as clear as I can. Please let me know if I should clarify anything.</p> <p>I have a long list of variables in a list in the following format - </p> <pre><code>L = ["Fruit", "Transportation", "Housing", "Food", "Education"] </code></pre> <p>I would like to map a shorter list into it. The shorter list does not have each but only some of the variables in the long list. For instance -</p> <pre><code>S = ["Fruit", "Food"] </code></pre> <p>What I am interested in obtaining is the binary values of the short list while it maps into the L list.</p> <p>With S as an example, it should be:</p> <pre><code>S = [1, 0, 0, 1, 0] </code></pre> <p>I tried map(S, L) but clearly a list is not callable. </p> <pre><code>TypeError: 'list' object is not callable </code></pre> <p>What would be a good way to do this? Thank you!!</p>
0
2016-07-28T03:40:19Z
38,626,783
<p>You can use python's list comprehension as follow: </p> <pre><code>ans=[1 if x in S else 0 for x in L] </code></pre>
1
2016-07-28T03:49:48Z
[ "python", "list", "mapping" ]
Mapping a list into a reference list
38,626,700
<p>I am trying to make this as clear as I can. Please let me know if I should clarify anything.</p> <p>I have a long list of variables in a list in the following format - </p> <pre><code>L = ["Fruit", "Transportation", "Housing", "Food", "Education"] </code></pre> <p>I would like to map a shorter list into it. The shorter list does not have each but only some of the variables in the long list. For instance -</p> <pre><code>S = ["Fruit", "Food"] </code></pre> <p>What I am interested in obtaining is the binary values of the short list while it maps into the L list.</p> <p>With S as an example, it should be:</p> <pre><code>S = [1, 0, 0, 1, 0] </code></pre> <p>I tried map(S, L) but clearly a list is not callable. </p> <pre><code>TypeError: 'list' object is not callable </code></pre> <p>What would be a good way to do this? Thank you!!</p>
0
2016-07-28T03:40:19Z
38,626,804
<blockquote> <p>I tried map(S, L) but clearly a list is not callable.</p> </blockquote> <p>But its methods are:</p> <pre><code>&gt;&gt;&gt; map(S.count, L) [1, 0, 0, 1, 0] </code></pre> <p>(This one assumes there are no duplicates in S. If that's not the case, you could for example use <code>map(list(set(S)).count, L)</code> instead.)</p>
1
2016-07-28T03:51:45Z
[ "python", "list", "mapping" ]
Filling NaN values in a Pandas DataFrame conditionally on the values of non-NaN columns
38,626,704
<p>I have a question regarding filling <code>NaN</code> values in a Pandas <code>DataFrame</code> conditionally on the values of non-<code>NaN</code> columns. To illustrate:</p> <pre><code>import numpy as np import pandas as pd print pd.__version__ 0.18.1 df = pd.DataFrame({'a': [1, 0, 0, 0, 1], 'b': [0, 1, 0, 0, 0], 'c': [0, 0, 1, 1, 0], 'x': [0.5, 0.2, 0, 0.2, 0], 'y': [0, 0, 0, 1, 0], 'z': [0.1, 0.1, 0.9, 0, 0.4]}) df.ix[[2,4], ['x','y','z']] = np.nan print df a b c x y z 0 1 0 0 0.5 0.0 0.1 1 0 1 0 0.2 0.0 0.1 2 0 0 1 NaN NaN NaN 3 0 0 1 0.2 1.0 0.0 4 1 0 0 NaN NaN NaN </code></pre> <p>Now suppose I have some default values, that depend on the first three columns:</p> <pre><code>default_c = pd.Series([0.5, 0.5, 0.5], index=['x', 'y', 'z']) default_a = pd.Series([0.2, 0.2, 0.2], index=['x', 'y', 'z']) </code></pre> <p>In other words, I'd like to paste in <code>default_c</code> for the <code>NaN</code> values in row 2, and paste in <code>default_a</code> in row 4. To do this, I came up with the following somewhat inelegant solution:</p> <pre><code>nan_x = np.isnan(df['x']) is_c = df['c']==1 nan_c = nan_x &amp; is_c print nan_c 0 False 1 False 2 True 3 False 4 False dtype: bool df.ix[nan_c, default_c.index] = default_c.values print df a b c x y z 0 1 0 0 0.5 0.0 0.1 1 0 1 0 0.2 0.0 0.1 2 0 0 1 0.5 0.5 0.5 3 0 0 1 0.2 1.0 0.0 4 1 0 0 NaN NaN NaN </code></pre> <p>Is there a better way to do this using the <code>fillna()</code> function? </p> <p>For example, the following doesn't work, I'm guessing because I am filling a slice of the <code>DataFrame</code>:</p> <pre><code>df.loc[df['a']==1].fillna(default_a, inplace=True) print df a b c x y z 0 1 0 0 0.5 0.0 0.1 1 0 1 0 0.2 0.0 0.1 2 0 0 1 0.5 0.5 0.5 3 0 0 1 0.2 1.0 0.0 4 1 0 0 NaN NaN NaN </code></pre> <p>But this long line does:</p> <pre><code>df.loc[df['a']==1] = df.loc[df['a']==1].fillna(default_a) print df a b c x y z 0 1 0 0 0.5 0.0 0.1 1 0 1 0 0.2 0.0 0.1 2 0 0 1 0.5 0.5 0.5 3 0 0 1 0.2 1.0 0.0 4 1 0 0 0.2 0.2 0.2 </code></pre> <p>Anyways, just looking for advice on how to make this code as simple as possible.</p>
2
2016-07-28T03:40:46Z
38,642,444
<p>You may set <code>a, b, c</code> columns as a multi-index and use pandas <a href="http://pandas.pydata.org/pandas-docs/stable/merging.html#merging-together-values-within-series-or-dataframe-columns" rel="nofollow"><code>combine_first</code></a>.</p> <p>First, you would need a frame of defaults. In your setting it can be:</p> <pre><code>df0 = pd.concat([default_a, default_c], axis=1).T df0.index = pd.Index([(1, 0, 0), (0, 0, 1)], names=list("abc")) df0 Out[148]: x y z a b c 1 0 0 0.2 0.2 0.2 0 0 1 0.5 0.5 0.5 </code></pre> <p>Then set a multi-index to df1, apply <code>combine_first</code>, and reset an index:</p> <pre><code>df1 = df.set_index(['a', 'b', 'c']) &gt;&gt;&gt; df1 Out[151]: x y z a b c 1 0 0 0.5 0.0 0.1 0 1 0 0.2 0.0 0.1 0 1 NaN NaN NaN 1 0.2 1.0 0.0 1 0 0 NaN NaN NaN df1.combine_first(df0) Out[152]: x y z a b c 0 0 1 0.5 0.5 0.5 1 0.2 1.0 0.0 1 0 0.2 0.0 0.1 1 0 0 0.5 0.0 0.1 0 0.2 0.2 0.2 df1.combine_first(df0).reset_index() Out[154]: a b c x y z 0 0 0 1 0.5 0.5 0.5 1 0 0 1 0.2 1.0 0.0 2 0 1 0 0.2 0.0 0.1 3 1 0 0 0.5 0.0 0.1 4 1 0 0 0.2 0.2 0.2 </code></pre> <p>A side effect is a different sort order of the output. To keep the order, we may use the original index (if it's monotonic and unique, otherwise use an additional temp column instead):</p> <pre><code>df2 = df.reset_index().set_index(['a', 'b', 'c']) &gt;&gt;&gt; df2 Out[156]: index x y z a b c 1 0 0 0 0.5 0.0 0.1 0 1 0 1 0.2 0.0 0.1 0 1 2 NaN NaN NaN 1 3 0.2 1.0 0.0 1 0 0 4 NaN NaN NaN df2.combine_first(df0).reset_index().set_index('index').sort_index() Out[160]: a b c x y z index 0 1 0 0 0.5 0.0 0.1 1 0 1 0 0.2 0.0 0.1 2 0 0 1 0.5 0.5 0.5 3 0 0 1 0.2 1.0 0.0 4 1 0 0 0.2 0.2 0.2 </code></pre>
1
2016-07-28T16:54:26Z
[ "python", "pandas" ]
forward expects 1 arguments (0 given)
38,626,750
<pre><code>from turtle import * from Tkinter import * class TurtleApp: def left(self): self.turtle.right(90) def forward(self): self.turtle.forward(self.step) def right(self): self.turtle.right(90) def backward(self): self.turtle.backward(self.step) def __init__(self): self.main = Tk() self.main.title('TurtleApp') self.step = 10 self.turtle = Turtle() self.window = Screen() self.window.setup(500,500) self.turtle.speed(self.step) topFrame = Frame(self.main) topFrame.pack(side='top') topLabel = Label(topFrame, text='Turtle Controls') topLabel.pack() self.createDirectionPad() self.createStepEntry() def createDirectionPad(self): leftFrame = Frame(self.main) leftFrame.pack(side='left') leftButton = Button(leftFrame, text='Left',command=left) forwardButton = Button(leftFrame, text='Forward',command=forward) rightButton = Button(leftFrame, text='Right',command=right) backwardButton = Button(leftFrame, text='Backward',command=backward) leftButton.grid(row=1,column=0) forwardButton.grid(row=0,column=1) rightButton.grid(row=1,column=2) backwardButton.grid(row=2,column=1) def createStepEntry(self): rightFrame = Frame(self.main) rightFrame.pack(side='right') stepLabel = Label(rightFrame,text='Enter step size') stepLabel.pack(side='top') stepEntry = Entry(rightFrame) stepEntry.pack() stepButton = Button(rightFrame,text='Change step size') stepButton.pack(side='bottom') root = TurtleApp() root.main.mainloop() </code></pre> <p>When I run this and then click on the "Forward" button, I get a type error saying that 0 arguments were given. Other than self (which is already given?) I don't know what to pass to it. Is there something I am missing here, or is it just so poorly planned that it is unable to move the turtle? </p>
0
2016-07-28T03:45:44Z
38,626,866
<p>You need to refer to the <code>forward()</code> method defined in your <code>TurtleApp</code> class, not to the <code>turtle.forward()</code> function defined in the <code>turtle</code> module. The latter is being called because <code>from turtle import *</code> places <code>forward()</code> into the global scope and consequently the wrong <code>forward()</code> is being called.</p> <p>Change the code in <code>createDirectionPad()</code> to use <code>self</code> when referring to your class's methods:</p> <pre><code> leftButton = Button(leftFrame, text='Left',command=self.left) forwardButton = Button(leftFrame, text='Forward',command=self.forward) rightButton = Button(leftFrame, text='Right',command=self.right) backwardButton = Button(leftFrame, text='Backward',command=self.backward) </code></pre>
1
2016-07-28T03:58:30Z
[ "python", "tkinter", "typeerror", "turtle-graphics" ]
How can I make a button that access a a file in tkinter?
38,626,775
<p>I've been wanting to make a code that would let me open a directory window and select a csv file from a folder. I wanted to make 4 buttons that would do that, and then one button that if pressed it would run a code and write a new file. </p> <p>I've tried it several ways but so far i got not much this is my code:</p> <pre><code>from tkinter import* #how to organize layout# root = Tk() #CONSTRUCTOR(think blank window in your head) topFrame = Frame(root) #this is pretty much saying, # "i'm gonna make an invisible container and is gonna go into themain window, # root". topFrame.pack() #everytime there is something to display we have to pack it in. #Do the exact same thing for the bottom frame bottomFrame = Frame(root) bottomFrame.pack(side=BOTTOM) #let's through some widgets in here button1 = Button(topFrame,text="Button1",fg="yellow") button2 = Button(topFrame,text="Button2",fg="blue") button3 = Button(topFrame,text="Button3",fg="red") button4 = Button(topFrame,text="Button4",fg="white") button5 = Button(bottomFrame,text="Button5",fg="black") button1.pack(side=LEFT) button2.pack(side=LEFT) button3.pack(side=LEFT) button4.pack(side=LEFT) button5.pack(side=BOTTOM) </code></pre>
-1
2016-07-28T03:48:25Z
38,626,799
<p>Something along these lines:</p> <pre><code>from Tkinter import * def getFile(): # Get File Code b = Button(text="click me", command=getFile) b.pack() </code></pre> <p>By using <code>command=getFile</code>, Tk knows to call the <code>getFile</code> method when the button is clicked.</p> <p>Good luck!</p>
1
2016-07-28T03:51:26Z
[ "python", "tkinter", "python-3.5" ]
'float' object has no attribute 'astype'
38,626,789
<p>I am trying to find median values in a column of the dataframe. The median value that I am getting is float but I need it in integer format. </p> <pre><code>c_med = round(df['count'].median().astype(int)) c_med = round(df['count'].median()).astype(int) </code></pre> <p>Both the above types give me this error. If <code>astype(int)</code> is removed then the answer is correct. </p> <p>Error </p> <pre><code>Traceback (most recent call last): File "all_median.py", line 16, in &lt;module&gt; c_med = round(df['count'].median()).astype(int) AttributeError: 'float' object has no attribute 'astype' </code></pre>
-4
2016-07-28T03:50:27Z
38,626,818
<p>You no longer are in the Pandas API after the <code>round</code> function. </p> <p>You have to cast the value like so </p> <pre><code>c_med = int(round(df['count'].median()) </code></pre> <p>I'm not too familiar with Pandas, but you could try </p> <pre><code>c_med = df['count'].median().round().astype(int) </code></pre>
2
2016-07-28T03:53:30Z
[ "python", "pandas", "median" ]
Calling another method to another class
38,626,810
<p>i newbie on python programming, i so confused, why i cant call another method from another class, </p> <p>this is my source- file : 8_turunan lanjut.py</p> <pre><code>class Karyawan(object): 'untuk kelas karyawan' jml_karyawan = 0 # Class variable # constructor def __init__(self, kid, nama, jabatan): self.kid = kid self.nama = nama self.jabatan = jabatan Karyawan.jml_karyawan += 1 # method def infoKaryawan(self): print "Karyawan baru masuk" print "===================" print "ID : %s " % self.kid print "Nama : %s " % self.nama print "Jabatan : %s " % self.jabatan </code></pre> <p>second source file : 9_turunan advance.py</p> <pre><code> # cara mengakses/memakai class/membuat Object class cobaa(): obj = Karyawan("K001", "Ganjar", "Teknisi") obj.infoKaryawan() # tambah karyawan baru obj2 = Karyawan("K002", "Nadya", "Akunting") obj2.infoKaryawan() # tampilkan total Karyawan print "-----------------------------" print "Total Karyawan : %d " % Karyawan.jml_karyawan </code></pre> <p>how can i call method <strong>init</strong> and infoKaryawan to class cobaa on file 9_turunan advance.py</p> <p>i already put <code>from percobaan.Karyawan import __init__</code> on file : 9_turunan advance and its wrong, i dont know where's the problem of my source</p> <p>here my directory sturcture <a href="http://i.stack.imgur.com/anIXs.png" rel="nofollow">directory structure</a></p>
0
2016-07-28T03:52:40Z
38,626,932
<p>Your indentation is off in your class. It should read as follows:</p> <pre><code>class Karyawan(object): 'untuk kelas karyawan' jml_karyawan = 0 # Class variable def __init__(self, kid, nama, jabatan): self.kid = kid self.nama = nama self.jabatan = jabatan Karyawan.jml_karyawan += 1 def infoKaryawan(self): print "Karyawan baru masuk" print "===================" print "ID : %s " % self.kid print "Nama : %s " % self.nama print "Jabatan : %s " % self.jabatan </code></pre> <p>Then, in your other file, just import it as such: <code>from filename import Karyawan</code> </p> <p>Good luck!</p>
1
2016-07-28T04:06:59Z
[ "python", "class", "methods" ]
Missing lines when writing file with multiprocessing Lock Python
38,626,817
<p>This is my code:</p> <pre><code>from multiprocessing import Pool, Lock from datetime import datetime as dt console_out = "/STDOUT/Console.out" chunksize = 50 lock = Lock() def writer(message): lock.acquire() with open(console_out, 'a') as out: out.write(message) out.flush() lock.release() def conf_wrapper(state): import ProcessingModule as procs import sqlalchemy as sal stcd, nrows = state engine = sal.create_engine('postgresql://foo:bar@localhost:5432/schema') writer("State {s} started at: {n}" "\n".format(s=str(stcd).zfill(2), n=dt.now())) with engine.connect() as conn, conn.begin(): procs.processor(conn, stcd, nrows, chunksize) writer("\tState {s} finished at: {n}" "\n".format(s=str(stcd).zfill(2), n=dt.now())) def main(): nprocesses = 12 maxproc = 1 state_list = [(2, 113), (10, 119), (15, 84), (50, 112), (44, 110), (11, 37), (33, 197)] with open(console_out, 'w') as out: out.write("Starting at {n}\n".format(n=dt.now())) out.write("Using {p} processes..." "\n".format(p=nprocesses)) with Pool(processes=int(nprocesses), maxtasksperchild=maxproc) as pool: pool.map(func=conf_wrapper, iterable=state_list, chunksize=1) with open(console_out, 'a') as out: out.write("\nAll done at {n}".format(n=dt.now())) </code></pre> <p>The file <code>console_out</code> never has all 7 states in it. It always misses one or more state. Here is the output from the latest run:</p> <pre><code>Starting at 2016-07-27 21:46:58.638587 Using 12 processes... State 44 started at: 2016-07-27 21:47:01.482322 State 02 started at: 2016-07-27 21:47:01.497947 State 11 started at: 2016-07-27 21:47:01.529198 State 10 started at: 2016-07-27 21:47:01.497947 State 11 finished at: 2016-07-27 21:47:15.701207 State 15 finished at: 2016-07-27 21:47:24.123164 State 44 finished at: 2016-07-27 21:47:32.029489 State 50 finished at: 2016-07-27 21:47:51.203107 State 10 finished at: 2016-07-27 21:47:53.046876 State 33 finished at: 2016-07-27 21:47:58.156301 State 02 finished at: 2016-07-27 21:48:18.856979 All done at 2016-07-27 21:48:18.992277 </code></pre> <p>Why?</p> <p>Note, OS is Windows Server 2012 R2. </p>
1
2016-07-28T03:53:22Z
38,627,411
<p>Since you're running on Windows, <em>nothing</em> is inherited by worker processes. Each process runs the entire main program "from scratch".</p> <p>In particular, with the code as written every process has its own instance of <code>lock</code>, and these instances have nothing to do with each other. In short, <code>lock</code> isn't supplying any inter-process mutual exclusion at all.</p> <p>To fix this, the <code>Pool</code> constructor can be changed to call a once-per-process initialization function, to which you pass an instance of <code>Lock()</code>. For example, like so:</p> <pre><code>def init(L): global lock lock = L </code></pre> <p>and then add these arguments to the <code>Pool()</code> constructor:</p> <pre><code>initializer=init, initargs=(Lock(),), </code></pre> <p>And you no longer need the:</p> <pre><code>lock = Lock() </code></pre> <p>line.</p> <p>Then the inter-process mutual exclusion will work as intended.</p> <h2>WITHOUT A LOCK</h2> <p>If you'd like to delegate all output to a writer process, you could skip the lock and use a queue instead to feed that process [and see later for different version].</p> <pre><code>def writer_process(q): with open(console_out, 'w') as out: while True: message = q.get() if message is None: break out.write(message) out.flush() # can't guess whether you really want this </code></pre> <p>and change <code>writer()</code> to just:</p> <pre><code>def writer(message): q.put(message) </code></pre> <p>You would again need to use <code>initializer=</code> and <code>initargs=</code> in the <code>Pool</code> constructor so that all processes use the <em>same</em> queue.</p> <p>Only one process should run <code>writer_process()</code>, and that can be started on its own as an instance of <code>multiprocessing.Process</code>.</p> <p>Finally, to let <code>writer_process()</code> know it's time to quit, when it <em>is</em> time for it to drain the queue and return just run</p> <pre><code>q.put(None) </code></pre> <p>in the main process.</p> <h2>LATER</h2> <p>The OP settled on this version instead, because they needed to open the output file in other code simultaneously:</p> <pre><code>def writer_process(q): while True: message = q.get() if message == 'done': break else: with open(console_out, 'a') as out: out.write(message) </code></pre> <p>I don't know why the terminating sentinel was changed to <code>"done"</code>. Any unique value works for this; <code>None</code> is traditional.</p>
1
2016-07-28T05:00:21Z
[ "python", "python-multiprocessing" ]
how we can get the result export from Arango DB noSQL
38,626,849
<p>I am very new to arango DB nosql I try to get the exported output of arangoDB with shell commands or arangosh commands but I could not find any way. I know serialization to application can definitely help. However, I am looking for cli methods to get it done. </p> <p>There is a way to use pyarango where we can ostream the results to file. However looking for solution like <code>echo " db._query('return (length(table_name))')"|arangosh --server.database "qadb" --server.endpoint "tcp://127.0.0.1:8529" --server.username "qatest" --server.password "TTT"</code></p> <p>However, In my case I could get the results and command ended to open the arangosh shell. Please help to make understanding.</p>
0
2016-07-28T03:56:53Z
38,658,305
<p>ArangoDB offers several ways of scripting. You can use <a href="https://docs.arangodb.com/3.0/HTTP/Database/index.html" rel="nofollow">curl as documented with the HTTP-API</a></p> <pre><code>curl --dump - http://localhost:8529/_api/version?details=true </code></pre> <p>The HTTP-API is what all drivers are based on. So if its possible to achieve via arangosh, you can do it with curl (maybe with the aid of <a href="http://stedolan.github.io/jq/" rel="nofollow">jq</a> to extract the required information)</p> <p>You can also use arangosh to execute arbitrary commands passed in (as pointed out by CoDEmanX:</p> <pre><code>arangosh --server.database qadb \ --server.username qatest \ --server.password TTTT \ --javascript.execute-string \ "print(db._query('RETURN LENGTH(collection_name)'))" </code></pre> <p>You can also use <code>arangosh</code> to run scripts using the standard unix shebang mechanism:</p> <pre><code>#!/usr/bin/arangosh --javascript-execute print(db._query('RETURN LENGTH(collection_name)')); </code></pre> <p>Save the above to i.e. <code>/tmp/test.js</code> and make it executable with <code>chmod a+x /tmp/test.js</code>, you then can simply invoke it:</p> <pre><code>/tmp/test.js SOME_BASH_VAR=`/tmp/test.js` echo "${SOME_BASH_VAR}" /tmp/test.js &gt; /tmp/output_of_arangosh.json </code></pre> <p>To generally export collections you should use <a href="https://docs.arangodb.com/3.0/Manual/Administration/Arangodump.html" rel="nofollow">arangodump</a>.</p>
1
2016-07-29T12:00:06Z
[ "python", "shell", "nosql", "arangodb" ]
Any ideas how to parse this payload in python?
38,626,883
<p>I am using MQTT to subscribe to a topic and receive messages. I have this code written so far and it works fine subscribing and all but I am having problems determining a way to parse through the payload that I receive from the MQTT broker. I have been trying to obtain the numerical values that I see in the payload but I cannot figure out the right approach to parse this data. Any ideas/suggestions? Thanks!</p> <h1>My Code:</h1> <p>there is more code that is irrelevant. this is just a snippet.</p> <pre><code>import paho.mqtt.client as mqtt import json #Call back functions # gives connection message def on_connect(client,userdata,rc): print("Connected with result code:"+str(rc)) # subscribe for all devices of user client.subscribe('+/devices/+/up') def on_connect(client,userdata,rc): print("Connected with result code:"+str(rc)) # subscribe for all devices of user client.subscribe('+/devices/+/up') def on_message(client,userdata,msg): print"Topic",msg.topic + "\nMessage:" + str(msg.payload) node_data = str(msg.payload) print '\r\n test' print node_data j = json.loads(node_data) print "\r\n after loads: " print j </code></pre> <p><strong>My Outputs</strong>:</p> <pre><code>Message:{"payload":"Dgv+CggGBCYFAPMLAgc=","fields":{"Light":58.32,"Pressure":98569.5,"Temp":32.4375,"X_accel":0.6875,"Y_accel":-0.125,"Z_accel":0.625},"port":1,"counter":8,"dev_eui":"000000007D9050C1","metadata":[{"frequency":904.3,"datarate":"SF7BW125","codingrate":"4/5","gateway_timestamp":2090979635,"gateway_time":"2016-07-28T02:26:15.386371Z","channel":2,"server_time":"2016-07-28T02:06:13.075194806Z","rssi":-13,"lsnr":9.5,"rfchain":0,"crc":1,"modulation":"LORA","gateway_eui":"0080000000009BE6","altitude":911,"longitude":-93.19677,"latitude":45.10303}]} test {"payload":"Dgv+CggGBCYFAPMLAgc=","fields":{"Light":58.32,"Pressure":98569.5,"Temp":32.4375,"X_accel":0.6875,"Y_accel":-0.125,"Z_accel":0.625},"port":1,"counter":8,"dev_eui":"000000007D9050C1","metadata":[{"frequency":904.3,"datarate":"SF7BW125","codingrate":"4/5","gateway_timestamp":2090979635,"gateway_time":"2016-07-28T02:26:15.386371Z","channel":2,"server_time":"2016-07-28T02:06:13.075194806Z","rssi":-13,"lsnr":9.5,"rfchain":0,"crc":1,"modulation":"LORA","gateway_eui":"0080000000009BE6","altitude":911,"longitude":-93.19677,"latitude":45.10303}]} after loads: {u'fields': {u'Y_accel': -0.125, u'Temp': 32.4375, u'X_accel': 0.6875, u'Light': 58.32, u'Pressure': 98569.5, u'Z_accel': 0.625}, u'counter': 8, u'port': 1, u'dev_eui': u'000000007D9050C1', u'payload': u'Dgv+CggGBCYFAPMLAgc=', u'metadata': [{u'gateway_time': u'2016-07-28T02:26:15.386371Z', u'server_time': u'2016-07-28T02:06:13.075194806Z', u'datarate': u'SF7BW125', u'gateway_eui': u'0080000000009BE6', u'modulation': u'LORA', u'gateway_timestamp': 2090979635, u'longitude': -93.19677, u'crc': 1, u'frequency': 904.3, u'rfchain': 0, u'codingrate': u'4/5', u'lsnr': 9.5, u'latitude': 45.10303, u'rssi': -13, u'altitude': 911, u'channel': 2}]} </code></pre> <p>I want to be able to extract the numerical values from this...string?Dict?Json?(payload) for the 'Temp', 'Light', 'Pressure' etc...parameters.Any advice is greatly appreciated.' I have tried the following but I receive this error. Doesn't tell me much...</p> <pre><code>data = json.loads(node_data) Press = data['Pressure'] print Press </code></pre> <p>File "C:\Python27\My_Py_27_Codes\scratch_py_mqtt.py", line 25, in on_message Press = data['Pressure']</p> <pre><code>KeyError: 'Pressure' </code></pre> <p>Apparently 'Pressure' is not a key in this Dictionary? </p>
0
2016-07-28T04:00:47Z
38,626,955
<pre><code>node_data = {"payload":"dsgsg","fields":{"pressure":34,"temp":35}} data = json.loads(node_data) Press = data['fields']['Pressure'] print Press </code></pre> <p>you have to give the exact location of the filed. In your case <code>pressure</code> is inside the <code>fields</code> dictionary </p>
1
2016-07-28T04:09:43Z
[ "python", "json", "parsing", "data-structures", "iot" ]
Any ideas how to parse this payload in python?
38,626,883
<p>I am using MQTT to subscribe to a topic and receive messages. I have this code written so far and it works fine subscribing and all but I am having problems determining a way to parse through the payload that I receive from the MQTT broker. I have been trying to obtain the numerical values that I see in the payload but I cannot figure out the right approach to parse this data. Any ideas/suggestions? Thanks!</p> <h1>My Code:</h1> <p>there is more code that is irrelevant. this is just a snippet.</p> <pre><code>import paho.mqtt.client as mqtt import json #Call back functions # gives connection message def on_connect(client,userdata,rc): print("Connected with result code:"+str(rc)) # subscribe for all devices of user client.subscribe('+/devices/+/up') def on_connect(client,userdata,rc): print("Connected with result code:"+str(rc)) # subscribe for all devices of user client.subscribe('+/devices/+/up') def on_message(client,userdata,msg): print"Topic",msg.topic + "\nMessage:" + str(msg.payload) node_data = str(msg.payload) print '\r\n test' print node_data j = json.loads(node_data) print "\r\n after loads: " print j </code></pre> <p><strong>My Outputs</strong>:</p> <pre><code>Message:{"payload":"Dgv+CggGBCYFAPMLAgc=","fields":{"Light":58.32,"Pressure":98569.5,"Temp":32.4375,"X_accel":0.6875,"Y_accel":-0.125,"Z_accel":0.625},"port":1,"counter":8,"dev_eui":"000000007D9050C1","metadata":[{"frequency":904.3,"datarate":"SF7BW125","codingrate":"4/5","gateway_timestamp":2090979635,"gateway_time":"2016-07-28T02:26:15.386371Z","channel":2,"server_time":"2016-07-28T02:06:13.075194806Z","rssi":-13,"lsnr":9.5,"rfchain":0,"crc":1,"modulation":"LORA","gateway_eui":"0080000000009BE6","altitude":911,"longitude":-93.19677,"latitude":45.10303}]} test {"payload":"Dgv+CggGBCYFAPMLAgc=","fields":{"Light":58.32,"Pressure":98569.5,"Temp":32.4375,"X_accel":0.6875,"Y_accel":-0.125,"Z_accel":0.625},"port":1,"counter":8,"dev_eui":"000000007D9050C1","metadata":[{"frequency":904.3,"datarate":"SF7BW125","codingrate":"4/5","gateway_timestamp":2090979635,"gateway_time":"2016-07-28T02:26:15.386371Z","channel":2,"server_time":"2016-07-28T02:06:13.075194806Z","rssi":-13,"lsnr":9.5,"rfchain":0,"crc":1,"modulation":"LORA","gateway_eui":"0080000000009BE6","altitude":911,"longitude":-93.19677,"latitude":45.10303}]} after loads: {u'fields': {u'Y_accel': -0.125, u'Temp': 32.4375, u'X_accel': 0.6875, u'Light': 58.32, u'Pressure': 98569.5, u'Z_accel': 0.625}, u'counter': 8, u'port': 1, u'dev_eui': u'000000007D9050C1', u'payload': u'Dgv+CggGBCYFAPMLAgc=', u'metadata': [{u'gateway_time': u'2016-07-28T02:26:15.386371Z', u'server_time': u'2016-07-28T02:06:13.075194806Z', u'datarate': u'SF7BW125', u'gateway_eui': u'0080000000009BE6', u'modulation': u'LORA', u'gateway_timestamp': 2090979635, u'longitude': -93.19677, u'crc': 1, u'frequency': 904.3, u'rfchain': 0, u'codingrate': u'4/5', u'lsnr': 9.5, u'latitude': 45.10303, u'rssi': -13, u'altitude': 911, u'channel': 2}]} </code></pre> <p>I want to be able to extract the numerical values from this...string?Dict?Json?(payload) for the 'Temp', 'Light', 'Pressure' etc...parameters.Any advice is greatly appreciated.' I have tried the following but I receive this error. Doesn't tell me much...</p> <pre><code>data = json.loads(node_data) Press = data['Pressure'] print Press </code></pre> <p>File "C:\Python27\My_Py_27_Codes\scratch_py_mqtt.py", line 25, in on_message Press = data['Pressure']</p> <pre><code>KeyError: 'Pressure' </code></pre> <p>Apparently 'Pressure' is not a key in this Dictionary? </p>
0
2016-07-28T04:00:47Z
38,628,695
<p>So after a few hours of scratching my head and 'code-ing' away, I managed to achieve my goal. I am not sure if it is the 'prettiest' way or if it's even the best way to do it but here is what I figured out: I was dealing with a 'Dictionary' and I had to select the appropriate key-name 'fields'. This would then enable me to 'get' the numerical values associated with the parameters (Temp, Pressure, Light, etc...) that are inside the 'fields' portion of the Dictionary.</p> <h1>Code to solve my issue:</h1> <pre><code>def on_message(client,userdata,msg): print"Topic",msg.topic + "\n\nMessage:" + str(msg.payload) node_data = str(msg.payload) print ' \n Sensor Values \r' my_dict = json.loads(node_data) params = my_dict.get("fields",None) light = params.get('Light') pressure = params.get('Pressure') temp = params.get('Temp') x = params.get('X_accel') y = params.get('Y_accel') z = params.get('Z_accel') print '' print 'Light:' + str(light) print 'Pressure:' + str(pressure) print 'Temperature:' + str(temp) print 'X-accel:' + str(x) print 'Y-accel:' + str(y) print 'Z-accel:' + str(z) print '\n\n' </code></pre> <h1>Cheers everyone!</h1>
0
2016-07-28T06:33:41Z
[ "python", "json", "parsing", "data-structures", "iot" ]
Make JSON Object in python
38,626,933
<p>I want make JSON Object in python like this :</p> <pre><code>{ "to":["admin"], "content":{ "message":"everything", "command":0, "date":["tag1",...,"tagn"] }, "time":"YYYYMMDDhhmmss" } </code></pre> <p>This is my code in python :</p> <pre><code>import json cont = [{"message":"everything","command":0,"data":["tag1","tag2"]}] json_content = json.dumps(cont,sort_keys=False,indent=2) print json_content data = [{"to":("admin"),"content":json_content, "time":"YYYYMMDDhhmmss"}] json_obj = json.dumps(data,sort_keys=False, indent =2) print json_obj </code></pre> <p>But I get the result like this :</p> <pre><code>[ { "content": "[\n {\n \"data\": [\n \"tag1\", \n \"tag2\"\n ], \n \"message\": \"everything\", \n \"command\": 0\n }\n]", "to": "admin", "time": "YYYYMMDDhhmmss" } ] </code></pre> <p>Could someone please help me? Thankyou</p>
1
2016-07-28T04:07:07Z
38,626,974
<h1>Nested <code>json</code> content</h1> <p><code>json_content</code> is a <code>json</code> string representation returned by the first call to <code>json.dumps()</code>, this is why you get a string version of the content in the second call to <code>json.dumps()</code>. You need to call <code>json.dumps()</code> once on the whole python object after you place the original content, <code>cont</code>, directly into <code>data</code>.</p> <pre><code>import json cont = [{ "message": "everything", "command": 0, "data" : ["tag1", "tag2"] }] data = [{ "to" : ("admin"), "content" : cont, "time" : "YYYYMMDDhhmmss" }] json_obj = json.dumps(data,sort_keys=False, indent =2) print json_obj </code></pre> <hr> <pre><code>[ { "content": [ { "data": [ "tag1", "tag2" ], "message": "everything", "command": 0 } ], "to": "admin", "time": "YYYYMMDDhhmmss" } ] </code></pre>
0
2016-07-28T04:11:30Z
[ "python", "jsonobject" ]